text
stringlengths 2
1.04M
| meta
dict |
|---|---|
<div class="container">
<div class="row">
<div class="col-md-8" ng-show="notUpdated">
<button
class="btn btn-block btn-primary"
ng-click="scrap()">Actualizar!</button>
</div>
<div class="col-md-8" ng-show="updating">
<div class="progress">
<div class="progress-bar progress-bar-striped active" aria-valuemin="0" aria-valuemax="100" style="width: 100%"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<ul class="list-group">
<li class="list-group-item" ng-repeat="p in products">{{p.artDes}} <b class="pull-right">{{p.artPrlin | currency}}</b></li>
</ul>
</div>
</div>
</div>
|
{
"content_hash": "50acfe7166119bfc113013f406ffc3a5",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 131,
"avg_line_length": 29.869565217391305,
"alnum_prop": 0.5735080058224163,
"repo_name": "cultome/shopping_scraper",
"id": "9c0194ae19e192b286cdc6df8679d1c396e2e5c5",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/main.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39"
},
{
"name": "HTML",
"bytes": "2825"
},
{
"name": "JavaScript",
"bytes": "3046"
}
],
"symlink_target": ""
}
|
package org.gaixie.jibu.config;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jibu 配置,加载 jibu.properties 配置文件。
* <p>
*/
public class JibuConfig {
private static final Logger logger = LoggerFactory.getLogger(JibuConfig.class);
private static String PROPERTIES_FILE = "jibu.properties";
private static Properties prop;
static {
prop = new Properties();
try {
prop.load(JibuConfig.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE));
logger.info("Successfully loaded "+PROPERTIES_FILE+".");
} catch (Exception e) {
logger.error("Failed to load file: "+PROPERTIES_FILE+".", e);
}
}
// 这个类就不用这样实例化了。:-)
private JibuConfig() {}
/**
* Retrieve a property value
* @param key Name of the property
* @return String Value of property requested, null if not found
*/
public static String getProperty(String key) {
return prop.getProperty(key);
}
/**
* 得到 jibu 的当前配置。
* @return Properties
*/
public static Properties getProperties() {
return prop;
}
}
|
{
"content_hash": "fb8b79b1b4787a2b378c400b15c5406c",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 94,
"avg_line_length": 25.67391304347826,
"alnum_prop": 0.6274343776460627,
"repo_name": "geekcheng/jibu",
"id": "f66bee1e306bf8e41b956d3606006de6b5749495",
"size": "1243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jibu-core/src/main/java/org/gaixie/jibu/config/JibuConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
[ImplicitInstance]
[ForceDevirtualization]
public abstract class TypeSystemManager
{
class EmptyManager : TypeSystemManager
{
[NoInline]
public override Object AllocateObject(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Object AllocateReferenceCountingObject(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Object AllocateObjectWithExtensions(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Array AllocateArray(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override Array AllocateReferenceCountingArray(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override Array AllocateArrayNoClear(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override String AllocateString(TS.VTable vTable,
int length)
{
return null;
}
[NoInline]
public override String AllocateReferenceCountingString(TS.VTable vTable,
int length)
{
return null;
}
}
//
// Helper Methods
//
public virtual void InitializeTypeSystemManager()
{
InvokeStaticConstructors();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public object InitializeObject(UIntPtr memory,
TS.VTable vTable,
bool referenceCounting)
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory);
oh.VirtualTable = vTable;
if (referenceCounting)
{
oh.MultiUseWord = (int)((1 << ObjectHeader.ReferenceCountShift) | (int)ObjectHeader.GarbageCollectorFlags.NormalObject | (int)ObjectHeader.GarbageCollectorFlags.Unmarked);
#if REFCOUNT_STAT
ObjectHeader.s_RefCountedObjectsAllocated++;
#endif
#if DEBUG_REFCOUNT
BugCheck.Log( "InitRC (0x%x), new count = 1 +", (int)oh.ToPointer( ) );
#endif
}
else
{
oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked);
}
return oh.Pack();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public object InitializeObjectWithExtensions(UIntPtr memory,
TS.VTable vTable)
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory);
oh.VirtualTable = vTable;
oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked);
return oh.Pack();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public Array InitializeArray(UIntPtr memory,
TS.VTable vTable,
uint length,
bool referenceCounting)
{
object obj = InitializeObject(memory, vTable, referenceCounting);
ArrayImpl array = ArrayImpl.CastAsArray(obj);
array.m_numElements = length;
return array.CastThisAsArray();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public String InitializeString(UIntPtr memory,
TS.VTable vTable,
int length,
bool referenceCounting)
{
object obj = InitializeObject(memory, vTable, referenceCounting);
StringImpl str = StringImpl.CastAsString(obj);
str.m_arrayLength = length;
return str.CastThisAsString();
}
[TS.WellKnownMethod("TypeSystemManager_AllocateObject")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateObject(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingObject")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateReferenceCountingObject(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateObjectWithExtensions")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateObjectWithExtensions(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateArray")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateArray(TS.VTable vTable,
uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingArray")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateReferenceCountingArray(TS.VTable vTable,
uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateArrayNoClear")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateArrayNoClear(TS.VTable vTable,
uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateString")]
[TS.DisableAutomaticReferenceCounting]
public abstract String AllocateString(TS.VTable vTable,
int length);
[TS.DisableAutomaticReferenceCounting]
public abstract String AllocateReferenceCountingString(TS.VTable vTable,
int length);
//--//
[Inline]
public static T AtomicAllocator<T>(ref T obj) where T : class, new()
{
if (obj == null)
{
return AtomicAllocatorSlow(ref obj);
}
return obj;
}
[NoInline]
private static T AtomicAllocatorSlow<T>(ref T obj) where T : class, new()
{
T newObj = new T();
System.Threading.Interlocked.CompareExchange(ref obj, newObj, default(T));
return obj;
}
//--//
public static System.Reflection.MethodInfo CodePointerToMethodInfo(TS.CodePointer ptr)
{
throw new NotImplementedException();
}
//--//
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_InvokeStaticConstructors")]
private void InvokeStaticConstructors()
{
//
// WARNING!
// WARNING! Keep this method empty!!!!
// WARNING!
//
// We need a way to inject calls to the static constructors that are reachable.
// This is the empty vessel for those calls.
//
// WARNING!
// WARNING! Keep this method empty!!!!
// WARNING!
//
}
[TS.WellKnownMethod("TypeSystemManager_CastToType")]
public static object CastToType(object obj,
TS.VTable expected)
{
if (obj != null)
{
obj = CastToTypeNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToTypeNoThrow")]
public static object CastToTypeNoThrow(object obj,
TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (expected.CanBeAssignedFrom(got) == false)
{
return null;
}
}
return obj;
}
//--//
[TS.WellKnownMethod("TypeSystemManager_CastToSealedType")]
public static object CastToSealedType(object obj,
TS.VTable expected)
{
if (obj != null)
{
obj = CastToSealedTypeNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToSealedTypeNoThrow")]
public static object CastToSealedTypeNoThrow(object obj,
TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (got != expected)
{
return null;
}
}
return obj;
}
//--//
[TS.WellKnownMethod("TypeSystemManager_CastToInterface")]
public static object CastToInterface(object obj,
TS.VTable expected)
{
if (obj != null)
{
obj = CastToInterfaceNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToInterfaceNoThrow")]
public static object CastToInterfaceNoThrow(object obj,
TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (got.ImplementsInterface(expected))
{
return obj;
}
}
return null;
}
//--//
[NoReturn]
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_Throw")]
public virtual void Throw(Exception obj)
{
//
// TODO: Capture stack dump.
//
//
// Our LLVM port does not yet support throwing exceptions
//
BugCheck.Log("!!! WARNING !!!");
BugCheck.Log("!!! Throwing Exceptions is not yet supported for LLVM CodeGen !!!");
BugCheck.Log("!!! WARNING !!!");
BugCheck.Raise(BugCheck.StopCode.InvalidOperation);
DeliverException(obj);
}
[NoReturn]
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_Rethrow")]
public virtual void Rethrow()
{
DeliverException(ThreadImpl.GetCurrentException());
}
[NoReturn]
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_Rethrow__Exception")]
public virtual void Rethrow(Exception obj)
{
DeliverException(obj);
}
//--//
private void DeliverException(Exception obj)
{
//
// TODO: LT72: Only RT.ThreadManager can implement this method correctly
//
ThreadImpl thread = ThreadManager.Instance.CurrentThread;
Processor.Context ctx = thread.ThrowContext;
thread.CurrentException = obj;
ctx.Populate();
while (true)
{
//
// The PC points to the instruction AFTER the call, but the ExceptionMap could not cover it.
//
UIntPtr pc = AddressMath.Decrement(ctx.ProgramCounter, sizeof(uint));
TS.CodeMap cm = TS.CodeMap.ResolveAddressToCodeMap(pc);
if (cm != null && cm.ExceptionMap != null)
{
TS.CodePointer cp = cm.ExceptionMap.ResolveAddressToHandler(pc, TS.VTable.Get(obj));
if (cp.IsValid)
{
ctx.ProgramCounter = new UIntPtr((uint)cp.Target.ToInt32());
ctx.SwitchTo();
}
}
if (ctx.Unwind() == false)
{
break;
}
}
BugCheck.Raise(BugCheck.StopCode.UnwindFailure);
}
//
// Access Methods
//
public static extern TypeSystemManager Instance
{
[TS.WellKnownMethod("TypeSystemManager_get_Instance")]
[SingletonFactory(Fallback = typeof(EmptyManager))]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
}
}
|
{
"content_hash": "50013abf6a055350cceaa6ba741bc152",
"timestamp": "",
"source": "github",
"line_count": 440,
"max_line_length": 187,
"avg_line_length": 31.852272727272727,
"alnum_prop": 0.47884409561184443,
"repo_name": "ZachNL/llilum",
"id": "97473d025cb7645d46591aa92c492d7ea45a6a45",
"size": "14088",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "Zelig/Zelig/RunTime/Zelig/Kernel/SystemServices/TypeSystemManager.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "93636"
},
{
"name": "Batchfile",
"bytes": "33609"
},
{
"name": "C",
"bytes": "20007038"
},
{
"name": "C#",
"bytes": "24028792"
},
{
"name": "C++",
"bytes": "1925041"
},
{
"name": "Makefile",
"bytes": "74180"
},
{
"name": "Objective-C",
"bytes": "403"
},
{
"name": "Smalltalk",
"bytes": "170596"
}
],
"symlink_target": ""
}
|
.class Lcom/android/internal/policy/impl/keyguard/KeyguardHostView$8;
.super Ljava/lang/Object;
.source "KeyguardHostView.java"
# interfaces
.implements Landroid/view/View$OnClickListener;
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;->addDefaultWidgets()V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;
# direct methods
.method constructor <init>(Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;)V
.locals 0
.parameter
.prologue
.line 1128
iput-object p1, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardHostView$8;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public onClick(Landroid/view/View;)V
.locals 2
.parameter "v"
.prologue
.line 1132
iget-object v0, p0, Lcom/android/internal/policy/impl/keyguard/KeyguardHostView$8;->this$0:Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;
#getter for: Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;->mActivityLauncher:Lcom/android/internal/policy/impl/keyguard/KeyguardActivityLauncher;
invoke-static {v0}, Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;->access$1800(Lcom/android/internal/policy/impl/keyguard/KeyguardHostView;)Lcom/android/internal/policy/impl/keyguard/KeyguardActivityLauncher;
move-result-object v0
const/4 v1, 0x0
invoke-virtual {v0, v1}, Lcom/android/internal/policy/impl/keyguard/KeyguardActivityLauncher;->launchWidgetPicker(I)V
.line 1133
return-void
.end method
|
{
"content_hash": "15b9af3acd5854fa5221e1dbe13249ea",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 227,
"avg_line_length": 32.23728813559322,
"alnum_prop": 0.7744479495268138,
"repo_name": "baidurom/reference",
"id": "ea61cbb14c9e4439b3cdda123626bf4a5320d303",
"size": "1902",
"binary": false,
"copies": "1",
"ref": "refs/heads/coron-4.2",
"path": "bosp/android.policy.jar.out/smali/com/android/internal/policy/impl/keyguard/KeyguardHostView$8.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/CharacterMovementComponent.h"
#include "SideScrollerMovementComponent.generated.h"
/** Movement modes for Characters. */
UENUM(BlueprintType)
enum class ECustomMovementMode :uint8
{
MOVE_Climbing UMETA(DisplayName = "Climbing"),
};
/**
*
*/
UCLASS()
class ALCHEMYSIDESCROLLER_API USideScrollerMovementComponent : public UCharacterMovementComponent
{
GENERATED_UCLASS_BODY()
//public:
//UPROPERTY(Category = MovementMode, BlueprintReadOnly)
//TEnumAsByte<enum ECustomMovementMode> NewCustomMovementMode;
public:
virtual bool IsClimbing() const;
protected:
//virtual void PhysCustom(float deltaTime, int32 Iterations) override;
virtual void InitializeComponent() override;
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override;
};
|
{
"content_hash": "31eecfa147a223f101e1140ddfb7748c",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 127,
"avg_line_length": 26.885714285714286,
"alnum_prop": 0.79596174282678,
"repo_name": "aarmbruster/AlchemyTools",
"id": "c83d7c8569e7ed4d3bba58314bb7d7952332bc60",
"size": "941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/AlchemySideScroller/Public/SideScrollerMovementComponent.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "703"
},
{
"name": "C#",
"bytes": "5404"
},
{
"name": "C++",
"bytes": "51722"
}
],
"symlink_target": ""
}
|
<?php
/**
* @author Alexey Samoylov <alexey.samoylov@gmail.com>
* @author Valentin Konusov <rlng-krsk@yandex.ru>
*/
namespace yarcode\email\transports;
use yarcode\email\interfaces\TransportInterface;
use yii\base\Component;
use yii\mail\MailerInterface;
/**
* Class YiiMailer
* Transport for sending emails using yii mailer component
*
* @package email\transports
*/
class YiiMailer extends Component implements TransportInterface
{
public function send($from, $to, $subject, $text, $files = [], $bcc = null)
{
/** @var MailerInterface $mailer */
$mailer = \Yii::$app->get('mailer');
$message = $mailer->compose()
->setFrom($this->parseFrom($from))
->setTo($to)
->setSubject($subject)
->setHtmlBody($text);
if ($bcc) {
$message->setBcc($this->parseRecipients($bcc));
}
if (count($files) > 0) {
foreach ($files as $filePath) {
$message->attach($filePath);
}
}
return $message->send();
}
/**
* Quick workaround for sender email
*
* @param $from
* @return string|array
*/
protected function parseFrom($from)
{
$parts = explode(' ', $from);
if (count($parts) == 1) {
return $from;
}
$email = array_pop($parts);
$email = trim($email, '<>');
$name = implode(' ', $parts);
return [$email => $name];
}
/**
* @param string $string
* @return array|string
*/
public function parseRecipients($string)
{
$parts = explode(', ', $string);
if (count($parts) == 1) {
return $string;
}
return $parts;
}
}
|
{
"content_hash": "2a38e4b67db46bf7c2e706797ee75fca",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 79,
"avg_line_length": 22.935064935064936,
"alnum_prop": 0.5322763306908267,
"repo_name": "yarcode/yii2-email-manager",
"id": "5e6f887dac59330747d686be14da68b04699ed44",
"size": "1766",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/transports/YiiMailer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "27038"
}
],
"symlink_target": ""
}
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <limits>
#include <memory>
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/apps/platform_apps/app_browsertest_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/guest_view/browser/guest_view_base.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "components/guest_view/browser/guest_view_manager_delegate.h"
#include "components/guest_view/browser/guest_view_manager_factory.h"
#include "components/guest_view/browser/test_guest_view_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/hit_test_region_observer.h"
#include "content/public/test/test_frame_navigation_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/text_input_test_utils.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/test/extension_test_message_listener.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/blink/public/common/switches.h"
#include "ui/base/buildflags.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/ime_text_span.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/test/ui_controls.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/range/range.h"
#include "ui/touch_selection/touch_selection_menu_runner.h"
#if BUILDFLAG(IS_MAC)
#include "ui/base/test/scoped_fake_nswindow_fullscreen.h"
#endif
using extensions::AppWindow;
using extensions::ExtensionsAPIClient;
using guest_view::GuestViewBase;
using guest_view::GuestViewManager;
using guest_view::TestGuestViewManager;
using guest_view::TestGuestViewManagerFactory;
#if BUILDFLAG(IS_MAC)
// This class observes the RenderWidgetHostViewCocoa corresponding to the outer
// most WebContents provided for newly added subviews. The added subview
// corresponds to a NSPopUpButtonCell which will be removed shortly after being
// shown.
class NewSubViewAddedObserver : content::RenderWidgetHostViewCocoaObserver {
public:
explicit NewSubViewAddedObserver(content::WebContents* web_contents)
: content::RenderWidgetHostViewCocoaObserver(web_contents) {}
NewSubViewAddedObserver(const NewSubViewAddedObserver&) = delete;
NewSubViewAddedObserver& operator=(const NewSubViewAddedObserver&) = delete;
~NewSubViewAddedObserver() override {}
void WaitForNextSubView() {
if (did_receive_rect_)
return;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
const gfx::Rect& view_bounds_in_screen() const { return bounds_; }
private:
void DidAddSubviewWillBeDismissed(
const gfx::Rect& bounds_in_root_view) override {
did_receive_rect_ = true;
bounds_ = bounds_in_root_view;
if (run_loop_)
run_loop_->Quit();
}
bool did_receive_rect_ = false;
gfx::Rect bounds_;
std::unique_ptr<base::RunLoop> run_loop_;
};
#endif // BUILDFLAG(IS_MAC)
class WebViewInteractiveTest : public extensions::PlatformAppBrowserTest {
public:
WebViewInteractiveTest()
: guest_view_(nullptr),
embedder_web_contents_(nullptr),
corner_(gfx::Point()),
mouse_click_result_(false),
first_click_(true) {
GuestViewManager::set_factory_for_testing(&factory_);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
// Some bots are flaky due to slower loading interacting with
// deferred commits.
command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
}
TestGuestViewManager* GetGuestViewManager() {
TestGuestViewManager* manager = static_cast<TestGuestViewManager*>(
TestGuestViewManager::FromBrowserContext(browser()->profile()));
// Test code may access the TestGuestViewManager before it would be created
// during creation of the first guest.
if (!manager) {
manager = static_cast<TestGuestViewManager*>(
GuestViewManager::CreateWithDelegate(
browser()->profile(),
ExtensionsAPIClient::Get()->CreateGuestViewManagerDelegate(
browser()->profile())));
}
return manager;
}
void MoveMouseInsideWindowWithListener(gfx::Point point,
const std::string& message) {
ExtensionTestMessageListener move_listener(message);
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner_.x() + point.x(), corner_.y() + point.y())));
ASSERT_TRUE(move_listener.WaitUntilSatisfied());
}
void SendMouseClickWithListener(ui_controls::MouseButton button,
const std::string& message) {
ExtensionTestMessageListener listener(message);
SendMouseClick(button);
ASSERT_TRUE(listener.WaitUntilSatisfied());
}
void SendMouseClick(ui_controls::MouseButton button) {
SendMouseEvent(button, ui_controls::DOWN);
SendMouseEvent(button, ui_controls::UP);
}
void MoveMouseInsideWindow(const gfx::Point& point) {
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner_.x() + point.x(), corner_.y() + point.y())));
}
gfx::NativeWindow GetPlatformAppWindow() {
const extensions::AppWindowRegistry::AppWindowList& app_windows =
extensions::AppWindowRegistry::Get(browser()->profile())->app_windows();
return (*app_windows.begin())->GetNativeWindow();
}
void SendKeyPressToPlatformApp(ui::KeyboardCode key) {
ASSERT_EQ(1U, GetAppWindowCount());
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), key, false, false, false, false));
}
void SendCopyKeyPressToPlatformApp() {
ASSERT_EQ(1U, GetAppWindowCount());
#if BUILDFLAG(IS_MAC)
// Send Cmd+C on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, false, false, false, true));
#else
// Send Ctrl+C on Windows and Linux/ChromeOS.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, true, false, false, false));
#endif
}
void SendStartOfLineKeyPressToPlatformApp() {
#if BUILDFLAG(IS_MAC)
// Send Cmd+Left on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_LEFT, false, false, false, true));
#else
// Send Ctrl+Left on Windows and Linux/ChromeOS.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_LEFT, true, false, false, false));
#endif
}
void SendBackShortcutToPlatformApp() {
#if BUILDFLAG(IS_MAC)
// Send Cmd+[ on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_OEM_4, false, false, false, true));
#else
// Send browser back key on Linux/Windows.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_BROWSER_BACK, false, false, false,
false));
#endif
}
void SendForwardShortcutToPlatformApp() {
#if BUILDFLAG(IS_MAC)
// Send Cmd+] on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_OEM_6, false, false, false, true));
#else
// Send browser back key on Linux/Windows.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_BROWSER_FORWARD, false, false, false,
false));
#endif
}
void SendMouseEvent(ui_controls::MouseButton button,
ui_controls::MouseButtonState state) {
if (first_click_) {
mouse_click_result_ = ui_test_utils::SendMouseEventsSync(button, state);
first_click_ = false;
} else {
ASSERT_EQ(mouse_click_result_,
ui_test_utils::SendMouseEventsSync(button, state));
}
}
enum TestServer { NEEDS_TEST_SERVER, NO_TEST_SERVER };
std::unique_ptr<ExtensionTestMessageListener> RunAppHelper(
const std::string& test_name,
const std::string& app_location,
TestServer test_server,
content::WebContents** embedder_web_contents) {
// For serving guest pages.
if ((test_server == NEEDS_TEST_SERVER) && !StartEmbeddedTestServer()) {
LOG(ERROR) << "FAILED TO START TEST SERVER.";
return nullptr;
}
LoadAndLaunchPlatformApp(app_location.c_str(), "Launched");
if (!ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow())) {
LOG(ERROR) << "UNABLE TO FOCUS TEST WINDOW.";
return nullptr;
}
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
*embedder_web_contents = GetFirstAppWindowWebContents();
auto done_listener =
std::make_unique<ExtensionTestMessageListener>("TEST_PASSED");
done_listener->set_failure_message("TEST_FAILED");
if (!content::ExecuteScript(
*embedder_web_contents,
base::StringPrintf("runTest('%s')", test_name.c_str()))) {
LOG(ERROR) << "UNABLE TO START TEST";
return nullptr;
}
return done_listener;
}
void TestHelper(const std::string& test_name,
const std::string& app_location,
TestServer test_server) {
content::WebContents* embedder_web_contents = nullptr;
std::unique_ptr<ExtensionTestMessageListener> done_listener(RunAppHelper(
test_name, app_location, test_server, &embedder_web_contents));
ASSERT_TRUE(done_listener);
ASSERT_TRUE(done_listener->WaitUntilSatisfied());
embedder_web_contents_ = embedder_web_contents;
guest_view_ = GetGuestViewManager()->WaitForSingleGuestViewCreated();
}
void SendMessageToEmbedder(const std::string& message) {
ASSERT_TRUE(content::ExecuteScript(
GetFirstAppWindowWebContents(),
base::StringPrintf("onAppMessage('%s');", message.c_str())));
}
void SetupTest(const std::string& app_name,
const std::string& guest_url_spec) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp(app_name.c_str(), "connected");
guest_view_ = GetGuestViewManager()->WaitForSingleGuestViewCreated();
ASSERT_TRUE(
guest_view_->GetGuestMainFrame()->GetProcess()->IsForGuestsOnly());
embedder_web_contents_ = guest_view_->embedder_web_contents();
gfx::Rect offset = embedder_web_contents_->GetContainerBounds();
corner_ = offset.origin();
}
content::WebContents* DeprecatedGuestWebContents() {
return guest_view_->web_contents();
}
guest_view::GuestViewBase* GetGuestView() { return guest_view_; }
content::RenderFrameHost* GetGuestRenderFrameHost() {
return guest_view_->GetGuestMainFrame();
}
content::WebContents* embedder_web_contents() {
return embedder_web_contents_;
}
gfx::Point corner() { return corner_; }
void SimulateRWHMouseClick(content::RenderWidgetHost* rwh,
blink::WebMouseEvent::Button button,
int x,
int y) {
blink::WebMouseEvent mouse_event(
blink::WebInputEvent::Type::kMouseDown,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests());
mouse_event.button = button;
mouse_event.SetPositionInWidget(x, y);
// Needed for the WebViewTest.ContextMenuPositionAfterCSSTransforms
gfx::Rect rect = rwh->GetView()->GetViewBounds();
mouse_event.SetPositionInScreen(x + rect.x(), y + rect.y());
rwh->ForwardMouseEvent(mouse_event);
mouse_event.SetType(blink::WebInputEvent::Type::kMouseUp);
rwh->ForwardMouseEvent(mouse_event);
}
class PopupCreatedObserver {
public:
PopupCreatedObserver() = default;
PopupCreatedObserver(const PopupCreatedObserver&) = delete;
PopupCreatedObserver& operator=(const PopupCreatedObserver&) = delete;
~PopupCreatedObserver() = default;
void Wait(int wait_retry_left = 10) {
if (wait_retry_left <= 0) {
LOG(ERROR) << "Wait failed";
return;
}
if (CountWidgets() == initial_widget_count_ + 1 &&
last_render_widget_host_->GetView()->GetNativeView()) {
gfx::Rect popup_bounds =
last_render_widget_host_->GetView()->GetViewBounds();
if (!popup_bounds.size().IsEmpty()) {
if (message_loop_.get())
message_loop_->Quit();
return;
}
}
// If we haven't seen any new widget or we get 0 size widget, we need to
// schedule waiting.
ScheduleWait(wait_retry_left - 1);
if (!message_loop_.get()) {
message_loop_ = new content::MessageLoopRunner;
message_loop_->Run();
}
}
void Init() { initial_widget_count_ = CountWidgets(); }
// Returns the last widget created.
content::RenderWidgetHost* last_render_widget_host() {
return last_render_widget_host_;
}
private:
void ScheduleWait(int wait_retry_left) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&PopupCreatedObserver::Wait, base::Unretained(this),
wait_retry_left),
base::Milliseconds(200));
}
size_t CountWidgets() {
std::unique_ptr<content::RenderWidgetHostIterator> widgets(
content::RenderWidgetHost::GetRenderWidgetHosts());
size_t num_widgets = 0;
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (content::RenderViewHost::From(widget))
continue;
++num_widgets;
last_render_widget_host_ = widget;
}
return num_widgets;
}
size_t initial_widget_count_ = 0;
content::RenderWidgetHost* last_render_widget_host_ = nullptr;
scoped_refptr<content::MessageLoopRunner> message_loop_;
};
void PopupTestHelper(const gfx::Point& padding) {
PopupCreatedObserver popup_observer;
popup_observer.Init();
// Press alt+DOWN to open popup.
bool alt = true;
content::SimulateKeyPress(DeprecatedGuestWebContents(),
ui::DomKey::ARROW_DOWN, ui::DomCode::ARROW_DOWN,
ui::VKEY_DOWN, false, false, alt, false);
popup_observer.Wait();
content::RenderWidgetHost* popup_rwh =
popup_observer.last_render_widget_host();
gfx::Rect popup_bounds = popup_rwh->GetView()->GetViewBounds();
content::RenderViewHost* embedder_rvh = GetFirstAppWindowWebContents()
->GetPrimaryMainFrame()
->GetRenderViewHost();
gfx::Rect embedder_bounds =
embedder_rvh->GetWidget()->GetView()->GetViewBounds();
gfx::Vector2d diff = popup_bounds.origin() - embedder_bounds.origin();
LOG(INFO) << "DIFF: x = " << diff.x() << ", y = " << diff.y();
const int left_spacing = 40 + padding.x(); // div.style.paddingLeft = 40px.
// div.style.paddingTop = 60px + (input box height = 26px).
const int top_spacing = 60 + 26 + padding.y();
// If the popup is placed within |threshold_px| of the expected position,
// then we consider the test as a pass.
const int threshold_px = 10;
EXPECT_LE(std::abs(diff.x() - left_spacing), threshold_px);
EXPECT_LE(std::abs(diff.y() - top_spacing), threshold_px);
// Close the popup.
content::SimulateKeyPress(DeprecatedGuestWebContents(), ui::DomKey::ESCAPE,
ui::DomCode::ESCAPE, ui::VKEY_ESCAPE, false,
false, false, false);
}
void FullscreenTestHelper(const std::string& test_name,
const std::string& test_dir) {
TestHelper(test_name, test_dir, NO_TEST_SERVER);
content::WebContents* embedder_web_contents =
GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
ASSERT_TRUE(DeprecatedGuestWebContents());
// Click the guest to request fullscreen.
ExtensionTestMessageListener passed_listener("FULLSCREEN_STEP_PASSED");
passed_listener.set_failure_message("TEST_FAILED");
content::SimulateMouseClickAt(DeprecatedGuestWebContents(), 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(20, 20));
ASSERT_TRUE(passed_listener.WaitUntilSatisfied());
}
protected:
TestGuestViewManagerFactory factory_;
// Only set if `SetupTest` or `TestHelper` are called.
raw_ptr<guest_view::GuestViewBase> guest_view_;
raw_ptr<content::WebContents> embedder_web_contents_;
gfx::Point corner_;
bool mouse_click_result_;
bool first_click_;
};
class WebViewImeInteractiveTest : public WebViewInteractiveTest {
protected:
// This class observes all the composition range updates associated with the
// TextInputManager of the provided WebContents. The WebContents should be an
// outer most WebContents.
class CompositionRangeUpdateObserver {
public:
explicit CompositionRangeUpdateObserver(content::WebContents* web_contents)
: tester_(web_contents) {
tester_.SetOnImeCompositionRangeChangedCallback(base::BindRepeating(
&CompositionRangeUpdateObserver::OnCompositionRangeUpdated,
base::Unretained(this)));
}
CompositionRangeUpdateObserver(const CompositionRangeUpdateObserver&) =
delete;
CompositionRangeUpdateObserver& operator=(
const CompositionRangeUpdateObserver&) = delete;
~CompositionRangeUpdateObserver() = default;
// Wait until a composition range update with a range length equal to
// |length| is received.
void WaitForCompositionRangeLength(uint32_t length) {
if (last_composition_range_length_.has_value() &&
last_composition_range_length_.value() == length)
return;
expected_length_ = length;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
private:
void OnCompositionRangeUpdated() {
uint32_t length = std::numeric_limits<uint32_t>::max();
if (tester_.GetLastCompositionRangeLength(&length)) {
last_composition_range_length_ = length;
}
if (last_composition_range_length_.value() == expected_length_)
run_loop_->Quit();
}
content::TextInputManagerTester tester_;
std::unique_ptr<base::RunLoop> run_loop_;
absl::optional<uint32_t> last_composition_range_length_;
uint32_t expected_length_ = 0;
};
};
class WebViewNewWindowInteractiveTest : public WebViewInteractiveTest {};
class WebViewFocusInteractiveTest : public WebViewInteractiveTest {};
class WebViewPointerLockInteractiveTest : public WebViewInteractiveTest {};
// The following class of tests do not work for OOPIF <webview>.
// TODO(ekaramad): Make this tests work with OOPIF and replace the test classes
// with WebViewInteractiveTest (see crbug.com/582562).
class DISABLED_WebViewPopupInteractiveTest : public WebViewInteractiveTest {};
// ui_test_utils::SendMouseMoveSync doesn't seem to work on OS_MAC, and
// likely won't work on many other platforms as well, so for now this test
// is for Windows and Linux only. As of Sept 17th, 2013 this test is disabled
// on Windows due to flakines, see http://crbug.com/293445.
// Disabled on Linux Aura because pointer lock does not work on Linux Aura.
// crbug.com/341876
// Timeouts flakily: crbug.com/1003345
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
IN_PROC_BROWSER_TEST_F(WebViewPointerLockInteractiveTest,
DISABLED_PointerLock) {
SetupTest("web_view/pointer_lock",
"/extensions/platform_apps/web_view/pointer_lock/guest.html");
// Move the mouse over the Lock Pointer button.
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 75, corner().y() + 25)));
// Click the Lock Pointer button. The first two times the button is clicked
// the permission API will deny the request (intentional).
ExtensionTestMessageListener exception_listener("request exception");
SendMouseClickWithListener(ui_controls::LEFT, "lock error");
ASSERT_TRUE(exception_listener.WaitUntilSatisfied());
SendMouseClickWithListener(ui_controls::LEFT, "lock error");
// Click the Lock Pointer button, locking the mouse to lockTarget1.
SendMouseClickWithListener(ui_controls::LEFT, "locked");
// Attempt to move the mouse off of the lock target, and onto lockTarget2,
// (which would trigger a test failure).
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 74, corner().y() + 74)));
MoveMouseInsideWindowWithListener(gfx::Point(75, 75), "mouse-move");
#if BUILDFLAG(IS_WIN)
// When the mouse is unlocked on win aura, sending a test mouse click clicks
// where the mouse moved to while locked. I was unable to figure out why, and
// since the issue only occurs with the test mouse events, just fix it with
// a simple workaround - moving the mouse back to where it should be.
// TODO(mthiesse): Fix Win Aura simulated mouse events while mouse locked.
MoveMouseInsideWindowWithListener(gfx::Point(75, 25), "mouse-move");
#endif
ExtensionTestMessageListener unlocked_listener("unlocked");
// Send a key press to unlock the mouse.
SendKeyPressToPlatformApp(ui::VKEY_ESCAPE);
// Wait for page to receive (successful) mouse unlock response.
ASSERT_TRUE(unlocked_listener.WaitUntilSatisfied());
// After the second lock, guest.js sends a message to main.js to remove the
// webview object. main.js then removes the div containing the webview, which
// should unlock, and leave the mouse over the mousemove-capture-container
// div. We then move the mouse over that div to ensure the mouse was properly
// unlocked and that the div receives the message.
ExtensionTestMessageListener move_captured_listener("move-captured");
move_captured_listener.set_failure_message("timeout");
// Mouse should already be over lock button (since we just unlocked), so send
// click to re-lock the mouse.
SendMouseClickWithListener(ui_controls::LEFT, "deleted");
// A mousemove event is triggered on the mousemove-capture-container element
// when we delete the webview container (since the mouse moves onto the
// element), but just in case, send an explicit mouse movement to be safe.
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 50, corner().y() + 10)));
// Wait for page to receive second (successful) mouselock response.
bool success = move_captured_listener.WaitUntilSatisfied();
if (!success) {
fprintf(stderr, "TIMEOUT - retrying\n");
// About 1 in 40 tests fail to detect mouse moves at this point (why?).
// Sending a right click seems to fix this (why?).
ExtensionTestMessageListener move_listener2("move-captured");
SendMouseClick(ui_controls::RIGHT);
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 51, corner().y() + 11)));
ASSERT_TRUE(move_listener2.WaitUntilSatisfied());
}
}
// flaky http://crbug.com/412086
IN_PROC_BROWSER_TEST_F(WebViewPointerLockInteractiveTest,
DISABLED_PointerLockFocus) {
SetupTest("web_view/pointer_lock_focus",
"/extensions/platform_apps/web_view/pointer_lock_focus/guest.html");
// Move the mouse over the Lock Pointer button.
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 75, corner().y() + 25)));
// Click the Lock Pointer button, locking the mouse to lockTarget.
// This will also change focus to another element
SendMouseClickWithListener(ui_controls::LEFT, "locked");
// Try to unlock the mouse now that the focus is outside of the BrowserPlugin
ExtensionTestMessageListener unlocked_listener("unlocked");
// Send a key press to unlock the mouse.
SendKeyPressToPlatformApp(ui::VKEY_ESCAPE);
// Wait for page to receive (successful) mouse unlock response.
ASSERT_TRUE(unlocked_listener.WaitUntilSatisfied());
}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
// Tests that if a <webview> is focused before navigation then the guest starts
// off focused.
// Flaky. https://crbug.com/1013552
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest,
DISABLED_Focus_FocusBeforeNavigation) {
TestHelper("testFocusBeforeNavigation", "web_view/focus", NO_TEST_SERVER);
}
// Tests that setting focus on the <webview> sets focus on the guest.
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, Focus_FocusEvent) {
TestHelper("testFocusEvent", "web_view/focus", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, Focus_FocusTakeFocus) {
TestHelper("testFocusTakeFocus", "web_view/focus", NO_TEST_SERVER);
// Compute where to click in the window to focus the guest input box.
int clickX, clickY;
EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
embedder_web_contents(),
"domAutomationController.send(Math.floor(window.clickX));", &clickX));
EXPECT_TRUE(content::ExecuteScriptAndExtractInt(
embedder_web_contents(),
"domAutomationController.send(Math.floor(window.clickY));", &clickY));
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
content::SimulateMouseClickAt(DeprecatedGuestWebContents(), 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(clickX, clickY));
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
// TAB back out to the embedder's input.
next_step_listener.Reset();
content::SimulateKeyPress(embedder_web_contents(), ui::DomKey::TAB,
ui::DomCode::TAB, ui::VKEY_TAB, false, false, false,
false);
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// Flaky on Mac and Linux - https://crbug.com/707648
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_Focus_FocusTracksEmbedder DISABLED_Focus_FocusTracksEmbedder
#else
#define MAYBE_Focus_FocusTracksEmbedder Focus_FocusTracksEmbedder
#endif
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest,
MAYBE_Focus_FocusTracksEmbedder) {
content::WebContents* embedder_web_contents = nullptr;
std::unique_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper("testFocusTracksEmbedder", "web_view/focus", NO_TEST_SERVER,
&embedder_web_contents));
EXPECT_TRUE(done_listener->WaitUntilSatisfied());
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testFocusTracksEmbedderRunNextStep');"));
// Blur the embedder.
embedder_web_contents->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->Blur();
// Ensure that the guest is also blurred.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, Focus_AdvanceFocus) {
content::WebContents* embedder_web_contents = nullptr;
{
std::unique_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper("testAdvanceFocus", "web_view/focus", NO_TEST_SERVER,
&embedder_web_contents));
EXPECT_TRUE(done_listener->WaitUntilSatisfied());
}
{
ExtensionTestMessageListener listener("button1-focused");
listener.set_failure_message("TEST_FAILED");
// In oopif-webview, the click it directly routed to the guest.
content::RenderFrameHost* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
SimulateRWHMouseClick(guest_rfh->GetRenderWidgetHost(),
blink::WebMouseEvent::Button::kLeft, 200, 20);
content::SimulateKeyPress(embedder_web_contents, ui::DomKey::TAB,
ui::DomCode::TAB, ui::VKEY_TAB, false, false,
false, false);
ASSERT_TRUE(listener.WaitUntilSatisfied());
}
{
// Wait for button1 to be focused again, this means we were asked to
// move the focus to the next focusable element.
ExtensionTestMessageListener listener("button1-advance-focus");
listener.set_failure_message("TEST_FAILED");
content::SimulateKeyPress(embedder_web_contents, ui::DomKey::TAB,
ui::DomCode::TAB, ui::VKEY_TAB, false, false,
false, false);
content::SimulateKeyPress(embedder_web_contents, ui::DomKey::TAB,
ui::DomCode::TAB, ui::VKEY_TAB, false, false,
false, false);
ASSERT_TRUE(listener.WaitUntilSatisfied());
}
}
// Tests that blurring <webview> also blurs the guest.
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, Focus_BlurEvent) {
TestHelper("testBlurEvent", "web_view/focus", NO_TEST_SERVER);
}
// Tests that a <webview> can't steal focus from the embedder.
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest,
FrameInGuestWontStealFocus) {
LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
content::RenderFrameHost* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
content::RenderWidgetHost* guest_rwh = guest_rfh->GetRenderWidgetHost();
content::RenderFrameHost* embedder_rfh =
embedder_web_contents->GetPrimaryMainFrame();
content::RenderWidgetHost* embedder_rwh = embedder_rfh->GetRenderWidgetHost();
// Embedder should be focused initially.
EXPECT_TRUE(content::IsRenderWidgetHostFocused(embedder_rwh));
EXPECT_FALSE(content::IsRenderWidgetHostFocused(guest_rwh));
EXPECT_NE(guest_rfh, embedder_rfh);
// Try to focus an iframe in the guest.
content::MainThreadFrameObserver embedder_observer(embedder_rwh);
content::MainThreadFrameObserver guest_observer(guest_rwh);
EXPECT_TRUE(content::ExecuteScript(
guest_rfh,
"document.body.appendChild(document.createElement('iframe')); "
"document.querySelector('iframe').focus()"));
embedder_observer.Wait();
guest_observer.Wait();
// Embedder should still be focused.
EXPECT_TRUE(content::IsRenderWidgetHostFocused(embedder_rwh));
EXPECT_FALSE(content::IsRenderWidgetHostFocused(guest_rwh));
EXPECT_NE(guest_rfh, embedder_web_contents->GetFocusedFrame());
// Try to focus the guest from the embedder.
content::FrameFocusedObserver focus_observer(guest_rfh);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents, "document.querySelector('webview').focus()"));
focus_observer.Wait();
// Guest should be focused.
EXPECT_FALSE(content::IsRenderWidgetHostFocused(embedder_rwh));
EXPECT_TRUE(content::IsRenderWidgetHostFocused(guest_rwh));
EXPECT_EQ(guest_rfh, embedder_web_contents->GetFocusedFrame());
// Try to focus an iframe in the embedder.
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"document.body.appendChild(document.createElement('iframe'))"));
content::RenderFrameHost* iframe_rfh = ChildFrameAt(embedder_rfh, 1);
content::FrameFocusedObserver iframe_focus_observer(iframe_rfh);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents, "document.querySelector('iframe').focus()"));
// Embedder is allowed to steal focus from guest.
iframe_focus_observer.Wait();
EXPECT_TRUE(content::IsRenderWidgetHostFocused(embedder_rwh));
EXPECT_FALSE(content::IsRenderWidgetHostFocused(guest_rwh));
EXPECT_EQ(iframe_rfh, embedder_web_contents->GetFocusedFrame());
}
// Tests that guests receive edit commands and respond appropriately.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, EditCommands) {
LoadAndLaunchPlatformApp("web_view/edit_commands", "connected");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
ExtensionTestMessageListener copy_listener("copy");
SendCopyKeyPressToPlatformApp();
// Wait for the guest to receive a 'copy' edit command.
ASSERT_TRUE(copy_listener.WaitUntilSatisfied());
}
// Tests that guests receive edit commands and respond appropriately.
// Flaky test - crbug.com/859478
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, DISABLED_EditCommandsNoMenu) {
SetupTest("web_view/edit_commands_no_menu",
"/extensions/platform_apps/web_view/edit_commands_no_menu/"
"guest.html");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
ExtensionTestMessageListener start_of_line_listener("StartOfLine");
SendStartOfLineKeyPressToPlatformApp();
#if BUILDFLAG(IS_MAC)
// On macOS, sending an accelerator [key-down] will also cause the subsequent
// key-up to be swallowed. The implementation of guest.html is waiting for a
// key-up to send the caret-position message. So we send a key-down/key-up of
// a character that otherwise has no effect.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_UP, false, false, false, false));
#endif
// Wait for the guest to receive a 'copy' edit command.
ASSERT_TRUE(start_of_line_listener.WaitUntilSatisfied());
}
// There is a problem of missing keyup events with the command key after
// the NSEvent is sent to NSApplication in ui/base/test/ui_controls_mac.mm .
// This test is disabled on only the Mac until the problem is resolved.
// See http://crbug.com/425859 for more information.
#if BUILDFLAG(IS_MAC)
#define MAYBE_NewWindow_OpenInNewTab DISABLED_NewWindow_OpenInNewTab
#else
#define MAYBE_NewWindow_OpenInNewTab NewWindow_OpenInNewTab
#endif
// Tests that Ctrl+Click/Cmd+Click on a link fires up the newwindow API.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, MAYBE_NewWindow_OpenInNewTab) {
content::WebContents* embedder_web_contents = nullptr;
ExtensionTestMessageListener loaded_listener("Loaded");
std::unique_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper("testNewWindowOpenInNewTab", "web_view/newwindow",
NEEDS_TEST_SERVER, &embedder_web_contents));
EXPECT_TRUE(loaded_listener.WaitUntilSatisfied());
#if BUILDFLAG(IS_MAC)
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_RETURN, false, false, false,
true /* cmd */));
#else
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_RETURN, true /* ctrl */, false, false,
false));
#endif
// Wait for the embedder to receive a 'newwindow' event.
ASSERT_TRUE(done_listener->WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(DISABLED_WebViewPopupInteractiveTest,
PopupPositioningBasic) {
TestHelper("testBasic", "web_view/popup_positioning", NO_TEST_SERVER);
ASSERT_TRUE(DeprecatedGuestWebContents());
PopupTestHelper(gfx::Point());
// TODO(lazyboy): Move the embedder window to a random location and
// make sure we keep rendering popups correct in webview.
}
// Flaky on ChromeOS and Linux: http://crbug.com/526886
// TODO(crbug.com/807446): Flaky on Mac.
// TODO(crbug.com/809383): Flaky on Windows.
// Tests that moving browser plugin (without resize/UpdateRects) correctly
// repositions popup.
IN_PROC_BROWSER_TEST_F(DISABLED_WebViewPopupInteractiveTest,
PopupPositioningMoved) {
TestHelper("testMoved", "web_view/popup_positioning", NO_TEST_SERVER);
ASSERT_TRUE(DeprecatedGuestWebContents());
PopupTestHelper(gfx::Point(20, 0));
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Navigation) {
TestHelper("testNavigation", "web_view/navigation", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Navigation_BackForwardKeys) {
LoadAndLaunchPlatformApp("web_view/navigation", "Launched");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
ExtensionTestMessageListener done_listener("TEST_PASSED");
done_listener.set_failure_message("TEST_FAILED");
ExtensionTestMessageListener ready_back_key_listener("ReadyForBackKey");
ExtensionTestMessageListener ready_forward_key_listener("ReadyForForwardKey");
EXPECT_TRUE(content::ExecuteScript(embedder_web_contents,
"runTest('testBackForwardKeys')"));
ASSERT_TRUE(ready_back_key_listener.WaitUntilSatisfied());
SendBackShortcutToPlatformApp();
ASSERT_TRUE(ready_forward_key_listener.WaitUntilSatisfied());
SendForwardShortcutToPlatformApp();
ASSERT_TRUE(done_listener.WaitUntilSatisfied());
}
// Trips over a DCHECK in content::MouseLockDispatcher::OnLockMouseACK; see
// https://crbug.com/761783.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PointerLock_PointerLockLostWithFocus \
PointerLock_PointerLockLostWithFocus
#else
#define MAYBE_PointerLock_PointerLockLostWithFocus \
DISABLED_PointerLock_PointerLockLostWithFocus
#endif
IN_PROC_BROWSER_TEST_F(WebViewPointerLockInteractiveTest,
MAYBE_PointerLock_PointerLockLostWithFocus) {
TestHelper("testPointerLockLostWithFocus", "web_view/pointerlock",
NO_TEST_SERVER);
}
// These tests are flaky on some platforms:
// http://crbug.com/468660
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#define MAYBE_FullscreenAllow_EmbedderHasPermission \
FullscreenAllow_EmbedderHasPermission
#else
#define MAYBE_FullscreenAllow_EmbedderHasPermission \
DISABLED_FullscreenAllow_EmbedderHasPermission
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
MAYBE_FullscreenAllow_EmbedderHasPermission) {
#if BUILDFLAG(IS_MAC)
ui::test::ScopedFakeNSWindowFullscreen fake_fullscreen;
#endif
FullscreenTestHelper("testFullscreenAllow",
"web_view/fullscreen/embedder_has_permission");
}
#if BUILDFLAG(IS_WIN)
#define MAYBE_FullscreenDeny_EmbedderHasPermission \
FullscreenDeny_EmbedderHasPermission
#else
#define MAYBE_FullscreenDeny_EmbedderHasPermission \
DISABLED_FullscreenDeny_EmbedderHasPermission
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
MAYBE_FullscreenDeny_EmbedderHasPermission) {
FullscreenTestHelper("testFullscreenDeny",
"web_view/fullscreen/embedder_has_permission");
}
#if BUILDFLAG(IS_WIN)
#define MAYBE_FullscreenAllow_EmbedderHasNoPermission \
FullscreenAllow_EmbedderHasNoPermission
#else
#define MAYBE_FullscreenAllow_EmbedderHasNoPermission \
DISABLED_FullscreenAllow_EmbedderHasNoPermission
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
MAYBE_FullscreenAllow_EmbedderHasNoPermission) {
FullscreenTestHelper("testFullscreenAllow",
"web_view/fullscreen/embedder_has_no_permission");
}
#if BUILDFLAG(IS_WIN)
#define MAYBE_FullscreenDeny_EmbedderHasNoPermission \
FullscreenDeny_EmbedderHasNoPermission
#else
#define MAYBE_FullscreenDeny_EmbedderHasNoPermission \
DISABLED_FullscreenDeny_EmbedderHasNoPermission
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
MAYBE_FullscreenDeny_EmbedderHasNoPermission) {
FullscreenTestHelper("testFullscreenDeny",
"web_view/fullscreen/embedder_has_no_permission");
}
// This test exercies the following scenario:
// 1. An <input> in guest has focus.
// 2. User takes focus to embedder by clicking e.g. an <input> in embedder.
// 3. User brings back the focus directly to the <input> in #1.
//
// Now we need to make sure TextInputTypeChanged fires properly for the guest's
// view upon step #3. We simply read the input type's state after #3 to
// make sure it's not TEXT_INPUT_TYPE_NONE.
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, Focus_FocusRestored) {
TestHelper("testFocusRestored", "web_view/focus", NO_TEST_SERVER);
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
ASSERT_TRUE(DeprecatedGuestWebContents());
// 1) We click on the guest so that we get a focus event.
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
{
content::SimulateMouseClickAt(DeprecatedGuestWebContents(), 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(10, 10));
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testFocusRestoredRunNextStep', 1);"));
}
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
// 2) We click on the embedder so the guest's focus goes away and it observes
// a blur event.
next_step_listener.Reset();
{
content::SimulateMouseClickAt(embedder_web_contents, 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(200, 20));
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testFocusRestoredRunNextStep', 2);"));
}
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
// 3) We click on the guest again to bring back focus directly to the previous
// input element, then we ensure text_input_type is properly set.
next_step_listener.Reset();
{
content::SimulateMouseClickAt(DeprecatedGuestWebContents(), 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(10, 10));
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testFocusRestoredRunNextStep', 3)"));
}
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
// |text_input_client| is not available for mac and android.
#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_ANDROID)
ui::TextInputClient* text_input_client =
embedder_web_contents->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->GetView()
->GetTextInputClient();
ASSERT_TRUE(text_input_client);
ASSERT_TRUE(text_input_client->GetTextInputType() !=
ui::TEXT_INPUT_TYPE_NONE);
#endif
}
// ui::TextInputClient is NULL for mac and android.
#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_ANDROID)
#if defined(ADDRESS_SANITIZER) || BUILDFLAG(IS_WIN)
#define MAYBE_Focus_InputMethod DISABLED_Focus_InputMethod
#else
#define MAYBE_Focus_InputMethod Focus_InputMethod
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, MAYBE_Focus_InputMethod) {
content::WebContents* embedder_web_contents = nullptr;
std::unique_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper("testInputMethod", "web_view/focus", NO_TEST_SERVER,
&embedder_web_contents));
ASSERT_TRUE(done_listener->WaitUntilSatisfied());
ui::TextInputClient* text_input_client =
embedder_web_contents->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->GetView()
->GetTextInputClient();
ASSERT_TRUE(text_input_client);
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
// An input element inside the <webview> gets focus and is given some
// user input via IME.
{
ui::CompositionText composition;
composition.text = u"InputTest123";
text_input_client->SetCompositionText(composition);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testInputMethodRunNextStep', 1);"));
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// A composition is committed via IME.
{
next_step_listener.Reset();
ui::CompositionText composition;
composition.text = u"InputTest456";
text_input_client->SetCompositionText(composition);
text_input_client->ConfirmCompositionText(/* keep_selection */ false);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testInputMethodRunNextStep', 2);"));
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// TODO(lazyboy): http://crbug.com/457007, Add a step or a separate test to
// check the following, currently it turns this test to be flaky:
// If we move the focus from the first <input> to the second one after we
// have some composition text set but *not* committed (by calling
// text_input_client->SetCompositionText()), then it would cause IME cancel
// and the onging composition is committed in the first <input> in the
// <webview>, not the second one.
// Tests ExtendSelectionAndDelete message works in <webview>.
// https://crbug.com/971985
{
next_step_listener.Reset();
// At this point we have set focus on first <input> in the <webview>,
// and the value it contains is 'InputTest456' with caret set after 'T'.
// Now we delete 'Test' in 'InputTest456', as the caret is after 'T':
// delete before 1 character ('T') and after 3 characters ('est').
text_input_client->ExtendSelectionAndDelete(1, 3);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"window.runCommand('testInputMethodRunNextStep', 3);"));
// Wait for the next step to complete.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
}
#endif
#if BUILDFLAG(IS_LINUX) || \
BUILDFLAG(IS_CHROMEOS) // TODO(https://crbug.com/801552): Flaky.
#define MAYBE_LongPressSelection DISABLED_LongPressSelection
#else
#define MAYBE_LongPressSelection LongPressSelection
#endif
#if !BUILDFLAG(IS_MAC)
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, MAYBE_LongPressSelection) {
SetupTest("web_view/text_selection",
"/extensions/platform_apps/web_view/text_selection/guest.html");
ASSERT_TRUE(DeprecatedGuestWebContents());
ASSERT_TRUE(embedder_web_contents());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
blink::WebInputEvent::Type context_menu_gesture_event_type =
blink::WebInputEvent::Type::kGestureLongPress;
#if BUILDFLAG(IS_WIN)
context_menu_gesture_event_type = blink::WebInputEvent::Type::kGestureLongTap;
#endif
auto filter = std::make_unique<content::InputMsgWatcher>(
DeprecatedGuestWebContents()
->GetRenderWidgetHostView()
->GetRenderWidgetHost(),
context_menu_gesture_event_type);
// Wait for guest to load (without this the events never reach the guest).
scoped_refptr<content::MessageLoopRunner> message_loop_runner =
new content::MessageLoopRunner;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, message_loop_runner->QuitClosure(), base::Milliseconds(200));
message_loop_runner->Run();
gfx::Rect guest_rect = DeprecatedGuestWebContents()->GetContainerBounds();
gfx::Point embedder_origin =
embedder_web_contents()->GetContainerBounds().origin();
guest_rect.Offset(-embedder_origin.x(), -embedder_origin.y());
// Mouse click is necessary for focus.
content::SimulateMouseClickAt(embedder_web_contents(), 0,
blink::WebMouseEvent::Button::kLeft,
guest_rect.CenterPoint());
content::SimulateLongTapAt(embedder_web_contents(), guest_rect.CenterPoint());
EXPECT_EQ(blink::mojom::InputEventResultState::kConsumed,
filter->GetAckStateWaitIfNecessary());
// Give enough time for the quick menu to fire.
message_loop_runner = new content::MessageLoopRunner;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, message_loop_runner->QuitClosure(), base::Milliseconds(200));
message_loop_runner->Run();
// TODO: Fix quick menu opening on Windows.
#if !BUILDFLAG(IS_WIN)
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
#endif
EXPECT_FALSE(DeprecatedGuestWebContents()->IsShowingContextMenu());
}
#endif
#if BUILDFLAG(IS_MAC)
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, TextSelection) {
SetupTest("web_view/text_selection",
"/extensions/platform_apps/web_view/text_selection/guest.html");
ASSERT_TRUE(DeprecatedGuestWebContents());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(
GetPlatformAppWindow()));
// Wait until guest sees a context menu.
ExtensionTestMessageListener ctx_listener("MSG_CONTEXTMENU");
ContextMenuWaiter menu_observer;
SimulateRWHMouseClick(
DeprecatedGuestWebContents()->GetRenderViewHost()->GetWidget(),
blink::WebMouseEvent::Button::kRight, 20, 20);
menu_observer.WaitForMenuOpenAndClose();
ASSERT_TRUE(ctx_listener.WaitUntilSatisfied());
// Now verify that the selection text propagates properly to RWHV.
content::RenderWidgetHostView* guest_rwhv =
DeprecatedGuestWebContents()->GetRenderWidgetHostView();
ASSERT_TRUE(guest_rwhv);
std::string selected_text = base::UTF16ToUTF8(guest_rwhv->GetSelectedText());
ASSERT_GE(selected_text.size(), 10u);
ASSERT_EQ("AAAAAAAAAA", selected_text.substr(0, 10));
}
// Verifies that asking for a word lookup from a guest will lead to a returned
// mojo callback from the renderer containing the right selected word.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, WordLookup) {
SetupTest("web_view/text_selection",
"/extensions/platform_apps/web_view/text_selection/guest.html");
ASSERT_TRUE(DeprecatedGuestWebContents());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
content::TextInputTestLocalFrame text_input_local_frame;
text_input_local_frame.SetUp(
DeprecatedGuestWebContents()->GetPrimaryMainFrame());
// Lookup some string through context menu.
ContextMenuNotificationObserver menu_observer(IDC_CONTENT_CONTEXT_LOOK_UP);
// Simulating a mouse click at a position to highlight text in guest and
// showing the context menu.
SimulateRWHMouseClick(
DeprecatedGuestWebContents()->GetRenderViewHost()->GetWidget(),
blink::WebMouseEvent::Button::kRight, 20, 20);
// Wait for the response form the guest renderer.
text_input_local_frame.WaitForGetStringForRange();
// Sanity check.
ASSERT_EQ("AAAA", text_input_local_frame.GetStringFromRange().substr(0, 4));
}
#endif
// Flaky on Mac: http://crbug.com/811893
// Flaky on Linux/ChromeOS/Windows: http://crbug.com/845638
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
BUILDFLAG(IS_WIN)
#define MAYBE_FocusAndVisibility DISABLED_FocusAndVisibility
#else
#define MAYBE_FocusAndVisibility FocusAndVisibility
#endif
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest, MAYBE_FocusAndVisibility) {
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/focus_visibility",
"WebViewInteractiveTest.LOADED");
ExtensionTestMessageListener test_init_listener(
"WebViewInteractiveTest.WebViewInitialized");
SendMessageToEmbedder("init-oopif");
EXPECT_TRUE(test_init_listener.WaitUntilSatisfied());
// Send several tab-keys. The button inside webview should receive focus at
// least once.
ExtensionTestMessageListener key_processed_listener(
"WebViewInteractiveTest.KeyUp");
#if BUILDFLAG(IS_MAC)
// On mac, the event listener seems one key event behind and deadlocks. Send
// an extra tab to get things unblocked. See http://crbug.com/685281 when
// fixed, this can be removed.
SendKeyPressToPlatformApp(ui::VKEY_TAB);
#endif
for (size_t i = 0; i < 4; ++i) {
key_processed_listener.Reset();
SendKeyPressToPlatformApp(ui::VKEY_TAB);
EXPECT_TRUE(key_processed_listener.WaitUntilSatisfied());
}
// Verify that the button in the guest receives focus.
ExtensionTestMessageListener webview_button_focused_listener(
"WebViewInteractiveTest.WebViewButtonWasFocused");
webview_button_focused_listener.set_failure_message(
"WebViewInteractiveTest.WebViewButtonWasNotFocused");
SendMessageToEmbedder("verify");
EXPECT_TRUE(webview_button_focused_listener.WaitUntilSatisfied());
// Reset the test and now make the <webview> invisible.
ExtensionTestMessageListener reset_listener(
"WebViewInteractiveTest.DidReset");
SendMessageToEmbedder("reset");
EXPECT_TRUE(reset_listener.WaitUntilSatisfied());
ExtensionTestMessageListener did_hide_webview_listener(
"WebViewInteractiveTest.DidHideWebView");
SendMessageToEmbedder("hide-webview");
EXPECT_TRUE(did_hide_webview_listener.WaitUntilSatisfied());
// Send the same number of keys and verify that the webview button was not
// this time.
for (size_t i = 0; i < 4; ++i) {
key_processed_listener.Reset();
SendKeyPressToPlatformApp(ui::VKEY_TAB);
EXPECT_TRUE(key_processed_listener.WaitUntilSatisfied());
}
ExtensionTestMessageListener webview_button_not_focused_listener(
"WebViewInteractiveTest.WebViewButtonWasNotFocused");
webview_button_not_focused_listener.set_failure_message(
"WebViewInteractiveTest.WebViewButtonWasFocused");
SendMessageToEmbedder("verify");
EXPECT_TRUE(webview_button_not_focused_listener.WaitUntilSatisfied());
}
// Flaky on MacOSX, crbug.com/817066.
// Flaky timeouts on Linux. https://crbug.com/709202
// Flaky timeouts on Win. https://crbug.com/846695
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || \
BUILDFLAG(IS_WIN)
#define MAYBE_KeyboardFocusSimple DISABLED_KeyboardFocusSimple
#else
#define MAYBE_KeyboardFocusSimple KeyboardFocusSimple
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, MAYBE_KeyboardFocusSimple) {
TestHelper("testKeyboardFocusSimple", "web_view/focus", NO_TEST_SERVER);
EXPECT_EQ(embedder_web_contents()->GetFocusedFrame(),
embedder_web_contents()->GetPrimaryMainFrame());
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
{
gfx::Rect offset = embedder_web_contents()->GetContainerBounds();
// Click the <input> element inside the <webview>.
// If we wanted, we could ask the embedder to compute an appropriate point.
MoveMouseInsideWindow(gfx::Point(offset.x() + 40, offset.y() + 40));
SendMouseClick(ui_controls::LEFT);
}
// Waits for the renderer to know the input has focus.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_A, false, false, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_B, false, true, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, false, false, false, false));
next_step_listener.Reset();
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents(),
"window.runCommand('testKeyboardFocusRunNextStep', 'aBc');"));
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// Ensures that input is routed to the webview after the containing window loses
// and regains focus. Additionally, the webview does not process keypresses sent
// while another window is focused.
// http://crbug.com/660044.
// Flaky on MacOSX, crbug.com/817067.
// Flaky on linux, crbug.com/706830.
// Flaky on Windows, crbug.com/847201.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || \
BUILDFLAG(IS_WIN)
#define MAYBE_KeyboardFocusWindowCycle DISABLED_KeyboardFocusWindowCycle
#else
#define MAYBE_KeyboardFocusWindowCycle KeyboardFocusWindowCycle
#endif
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, MAYBE_KeyboardFocusWindowCycle) {
TestHelper("testKeyboardFocusWindowFocusCycle", "web_view/focus",
NO_TEST_SERVER);
EXPECT_EQ(embedder_web_contents()->GetFocusedFrame(),
embedder_web_contents()->GetPrimaryMainFrame());
ExtensionTestMessageListener next_step_listener("TEST_STEP_PASSED");
next_step_listener.set_failure_message("TEST_STEP_FAILED");
{
gfx::Rect offset = embedder_web_contents()->GetContainerBounds();
// Click the <input> element inside the <webview>.
// If we wanted, we could ask the embedder to compute an appropriate point.
MoveMouseInsideWindow(gfx::Point(offset.x() + 40, offset.y() + 40));
SendMouseClick(ui_controls::LEFT);
}
// Waits for the renderer to know the input has focus.
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_A, false, false, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_B, false, true, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, false, false, false, false));
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("minimal", "Launched");
extensions::AppWindow* window = GetFirstAppWindowForApp(extension->id());
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents(),
"window.runCommand('monitorGuestEvent', 'focus');"));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_F, false, false, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_O, false, true, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_O, false, true, false, false));
// Close the other window and wait for the webview to regain focus.
CloseAppWindow(window);
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
next_step_listener.Reset();
EXPECT_TRUE(
content::ExecuteScript(embedder_web_contents(),
"window.runCommand('waitGuestEvent', 'focus');"));
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_X, false, false, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_Y, false, true, false, false));
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_Z, false, false, false, false));
next_step_listener.Reset();
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents(),
"window.runCommand('testKeyboardFocusRunNextStep', 'aBcxYz');"));
ASSERT_TRUE(next_step_listener.WaitUntilSatisfied());
}
// Ensure that destroying a <webview> with a pending mouse lock request doesn't
// leave a stale mouse lock widget pointer in the embedder WebContents. See
// https://crbug.com/1346245.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
DestroyGuestWithPendingPointerLock) {
LoadAndLaunchPlatformApp("web_view/pointer_lock_pending",
"WebViewTest.LAUNCHED");
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
content::RenderFrameHost* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
// The embedder is configured to remove the <webview> as soon as it receives
// the pointer lock permission request from the guest, without responding to
// it. Hence, have the guest request pointer lock and wait for its
// destruction.
content::RenderFrameDeletedObserver observer(guest_rfh);
EXPECT_TRUE(content::ExecuteScript(
guest_rfh, "document.querySelector('div').requestPointerLock()"));
observer.WaitUntilDeleted();
// The embedder WebContents shouldn't have a mouse lock widget.
EXPECT_FALSE(GetMouseLockWidget(embedder_web_contents));
// Close the embedder app and ensure that this doesn't crash, which used to
// be the case if the mouse lock widget (now destroyed) hadn't been cleared
// in the embedder.
content::WebContentsDestroyedWatcher destroyed_watcher(embedder_web_contents);
CloseAppWindow(GetFirstAppWindow());
destroyed_watcher.Wait();
}
#if BUILDFLAG(IS_MAC)
// This test verifies that replacement range for IME works with <webview>s. To
// verify this, a <webview> with an <input> inside is loaded. Then the <input>
// is focused and populated with some text. The test then sends an IPC to
// commit some text which will replace part of the previous text some new text.
IN_PROC_BROWSER_TEST_F(WebViewImeInteractiveTest,
CommitTextWithReplacementRange) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/ime", "WebViewImeTest.Launched");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
content::WebContents* guest_web_contents =
GetGuestViewManager()->DeprecatedGetLastGuestCreated();
// Click the <input> element inside the <webview>. In its focus handle, the
// <input> inside the <webview> initializes its value to "A B X D".
ExtensionTestMessageListener focus_listener("WebViewImeTest.InputFocused");
content::WebContents* target_web_contents = guest_web_contents;
WaitForHitTestData(guest_web_contents);
// The guest page has a large input box and (50, 50) lies inside the box.
content::SimulateMouseClickAt(target_web_contents, 0,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(50, 50));
EXPECT_TRUE(focus_listener.WaitUntilSatisfied());
// Verify the text inside the <input> is "A B X D".
std::string value;
ASSERT_TRUE(ExecuteScriptAndExtractString(guest_web_contents,
"window.domAutomationController."
"send(document.querySelector('"
"input').value)",
&value));
EXPECT_EQ("A B X D", value);
// Now commit "C" to to replace the range (4, 5).
// For OOPIF guests, the target for IME is the RWH for the guest's main frame.
// For BrowserPlugin-based guests, input always goes to the embedder.
ExtensionTestMessageListener input_listener("WebViewImetest.InputReceived");
content::RenderWidgetHost* target_rwh_for_input =
target_web_contents->GetRenderWidgetHostView()->GetRenderWidgetHost();
content::SendImeCommitTextToWidget(target_rwh_for_input, u"C",
std::vector<ui::ImeTextSpan>(),
gfx::Range(4, 5), 0);
EXPECT_TRUE(input_listener.WaitUntilSatisfied());
// Get the input value from the guest.
value.clear();
ASSERT_TRUE(ExecuteScriptAndExtractString(guest_web_contents,
"window.domAutomationController."
"send(document.querySelector('"
"input').value)",
&value));
EXPECT_EQ("A B C D", value);
}
#endif // OS_MAC
// This test verifies that focusing an input inside a <webview> will put the
// guest process's render widget into a monitoring mode for composition range
// changes.
IN_PROC_BROWSER_TEST_F(WebViewImeInteractiveTest, CompositionRangeUpdates) {
ASSERT_TRUE(StartEmbeddedTestServer()); // For serving guest pages.
LoadAndLaunchPlatformApp("web_view/ime", "WebViewImeTest.Launched");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
guest_view::GuestViewBase* guest_view =
GetGuestViewManager()->GetLastGuestViewCreated();
// Click the <input> element inside the <webview>. In its focus handle, the
// <input> inside the <webview> initializes its value to "A B X D".
ExtensionTestMessageListener focus_listener("WebViewImeTest.InputFocused");
content::WebContents* embedder_web_contents =
guest_view->embedder_web_contents();
WaitForHitTestData(guest_view->GetGuestMainFrame());
// The guest page has a large input box and (50, 50) lies inside the box.
content::SimulateMouseClickAt(
embedder_web_contents, 0, blink::WebMouseEvent::Button::kLeft,
guest_view->GetGuestMainFrame()
->GetView()
->TransformPointToRootCoordSpace(gfx::Point(50, 50)));
EXPECT_TRUE(focus_listener.WaitUntilSatisfied());
// Clear the string as it already contains some text. Then verify the text in
// the <input> is empty.
std::string value;
ASSERT_TRUE(ExecuteScriptAndExtractString(
guest_view->GetGuestMainFrame(),
"var input = document.querySelector('input');"
"input.value = '';"
"window.domAutomationController.send("
" document.querySelector('input').value)",
&value));
EXPECT_EQ("", value);
// Now set some composition text which should lead to an update in composition
// range information.
CompositionRangeUpdateObserver observer(embedder_web_contents);
content::SendImeSetCompositionTextToWidget(
guest_view->GetGuestMainFrame()->GetRenderWidgetHost(), u"ABC",
std::vector<ui::ImeTextSpan>(), gfx::Range::InvalidRange(), 0, 3);
observer.WaitForCompositionRangeLength(3U);
}
#if BUILDFLAG(IS_MAC)
// This test verifies that drop-down lists appear correctly inside OOPIF-based
// webviews which have offset inside embedder. This is a test for all guest
// views as the logic for showing such popups is inside content/ layer. For more
// context see https://crbug.com/772840.
IN_PROC_BROWSER_TEST_F(WebViewFocusInteractiveTest,
DropDownPopupInCorrectPosition) {
TestHelper("testSelectPopupPositionInMac", "web_view/shim", NO_TEST_SERVER);
ASSERT_TRUE(DeprecatedGuestWebContents());
// This is set in javascript.
const float distance_from_root_view_origin = 250.0;
// Verify that the view is offset inside root view as expected.
content::RenderWidgetHostView* guest_rwhv =
DeprecatedGuestWebContents()->GetRenderWidgetHostView();
while (guest_rwhv->TransformPointToRootCoordSpace(gfx::Point())
.OffsetFromOrigin()
.Length() < distance_from_root_view_origin) {
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
run_loop.Run();
}
// Now trigger the popup and wait until it is displayed. The popup will get
// dismissed after being shown.
NewSubViewAddedObserver popup_observer(embedder_web_contents_);
// Now send a mouse click and wait until the <select> tag is focused.
SimulateRWHMouseClick(guest_rwhv->GetRenderWidgetHost(),
blink::WebMouseEvent::Button::kLeft, 5, 5);
popup_observer.WaitForNextSubView();
// Verify the popup bounds intersect with those of the guest. Since the popup
// is relatively small (the width is determined by the <select> element's
// width and the hight is a factor of font-size and number of items), the
// intersection alone is a good indication the popup is shown properly inside
// the screen.
gfx::Rect guest_bounds_in_embedder(
guest_rwhv->TransformPointToRootCoordSpace(gfx::Point()),
guest_rwhv->GetViewBounds().size());
EXPECT_TRUE(guest_bounds_in_embedder.Intersects(
popup_observer.view_bounds_in_screen()))
<< "Guest bounds:" << guest_bounds_in_embedder.ToString()
<< " do not intersect with popup bounds:"
<< popup_observer.view_bounds_in_screen().ToString();
}
#endif
// Base class for interactive tests that enable site isolation in <webview>
// guests.
class SitePerProcessWebViewInteractiveTest : public WebViewInteractiveTest {
public:
SitePerProcessWebViewInteractiveTest() = default;
~SitePerProcessWebViewInteractiveTest() override = default;
SitePerProcessWebViewInteractiveTest(
const SitePerProcessWebViewInteractiveTest&) = delete;
SitePerProcessWebViewInteractiveTest& operator=(
const SitePerProcessWebViewInteractiveTest&) = delete;
void SetUp() override {
feature_list_.InitAndEnableFeature(features::kSiteIsolationForGuests);
WebViewInteractiveTest::SetUp();
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
WebViewInteractiveTest::SetUpOnMainThread();
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Check that when a focused <webview> navigates cross-process, the focus
// is preserved in the new page. See https://crbug.com/1358210.
IN_PROC_BROWSER_TEST_F(SitePerProcessWebViewInteractiveTest,
FocusPreservedAfterCrossProcessNavigation) {
// Load and show a platform app with a <webview> on a data: URL.
ASSERT_TRUE(StartEmbeddedTestServer());
LoadAndLaunchPlatformApp("web_view/simple", "WebViewTest.LAUNCHED");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
embedder_web_contents->Focus();
// Ensure that the guest is focused before the next navigation. To do so,
// have the embedder focus the <webview> element.
content::RenderFrameHost* guest_rfh =
GetGuestViewManager()->WaitForSingleGuestRenderFrameHostCreated();
content::FrameFocusedObserver focus_observer(guest_rfh);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents, "document.querySelector('webview').focus()"));
focus_observer.Wait();
ASSERT_TRUE(
content::IsRenderWidgetHostFocused(guest_rfh->GetRenderWidgetHost()));
EXPECT_EQ(guest_rfh, embedder_web_contents->GetFocusedFrame());
// Wait for guest's document to consider itself focused. This avoids
// flakiness on some platforms.
while (!content::EvalJs(guest_rfh, "document.hasFocus()").ExtractBool()) {
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::tiny_timeout());
run_loop.Run();
}
// Perform a cross-process navigation in the <webview> and verify that the
// new RenderFrameHost's RenderWidgetHost remains focused.
const GURL guest_url =
embedded_test_server()->GetURL("a.test", "/title1.html");
content::TestFrameNavigationObserver observer(guest_rfh);
EXPECT_TRUE(
ExecuteScript(guest_rfh, "location.href = '" + guest_url.spec() + "';"));
observer.Wait();
EXPECT_TRUE(observer.last_navigation_succeeded());
content::RenderFrameHost* guest_rfh2 =
GetGuestViewManager()->GetLastGuestRenderFrameHostCreated();
EXPECT_NE(guest_rfh, guest_rfh2);
EXPECT_EQ(guest_url, guest_rfh2->GetLastCommittedURL());
EXPECT_TRUE(
content::IsRenderWidgetHostFocused(guest_rfh2->GetRenderWidgetHost()));
EXPECT_EQ(true, content::EvalJs(guest_rfh2, "document.hasFocus()"));
EXPECT_EQ(guest_rfh2, embedder_web_contents->GetFocusedFrame());
}
|
{
"content_hash": "1312b114bf05c14784ed8c6a6439ccc7",
"timestamp": "",
"source": "github",
"line_count": 1752,
"max_line_length": 91,
"avg_line_length": 41.861301369863014,
"alnum_prop": 0.7110074855810529,
"repo_name": "nwjs/chromium.src",
"id": "f9eff3476effdfffad07c98c4bb8cfc868ee4a3c",
"size": "73341",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package com.fsck.k9.activity;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.K9;
import com.fsck.k9.K9.SplitViewMode;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener;
import com.fsck.k9.activity.setup.AccountSettings;
import com.fsck.k9.activity.setup.FolderSettings;
import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.SearchField;
import com.fsck.k9.ui.messageview.MessageViewFragment;
import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener;
import com.fsck.k9.view.MessageHeader;
import com.fsck.k9.view.MessageTitleView;
import com.fsck.k9.view.ViewSwitcher;
import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import de.cketti.library.changelog.ChangeLog;
/**
* MessageList is the primary user interface for the program. This Activity
* shows a list of messages.
* From this Activity the user can perform all standard message operations.
*/
public class MessageList extends K9Activity implements MessageListFragmentListener,
MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,
OnSwitchCompleteListener {
// for this activity
private static final String EXTRA_SEARCH = "search";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
private static final String EXTRA_SPECIAL_FOLDER = "special_folder";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
// used for remote search
public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account";
private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder";
private static final String STATE_DISPLAY_MODE = "displayMode";
private static final String STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed";
// Used for navigating to next/previous message
private static final int PREVIOUS = 1;
private static final int NEXT = 2;
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask) {
actionDisplaySearch(context, search, noThreading, newTask, true);
}
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
context.startActivity(
intentDisplaySearch(context, search, noThreading, newTask, clearTop));
}
public static Intent intentDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_SEARCH, search);
intent.putExtra(EXTRA_NO_THREADING, noThreading);
if (clearTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
return intent;
}
public static Intent shortcutIntent(Context context, String specialFolder) {
Intent intent = new Intent(context, MessageList.class);
intent.setAction(ACTION_SHORTCUT);
intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
public static Intent actionDisplayMessageIntent(Context context,
MessageReference messageReference) {
Intent intent = new Intent(context, MessageList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference);
return intent;
}
private enum DisplayMode {
MESSAGE_LIST,
MESSAGE_VIEW,
SPLIT_VIEW
}
private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation();
private ActionBar mActionBar;
private View mActionBarMessageList;
private View mActionBarMessageView;
private MessageTitleView mActionBarSubject;
private TextView mActionBarTitle;
private TextView mActionBarSubTitle;
private TextView mActionBarUnread;
private Menu mMenu;
private ViewGroup mMessageViewContainer;
private View mMessageViewPlaceHolder;
private MessageListFragment mMessageListFragment;
private MessageViewFragment mMessageViewFragment;
private int mFirstBackStackId = -1;
private Account mAccount;
private String mFolderName;
private LocalSearch mSearch;
private boolean mSingleFolderMode;
private boolean mSingleAccountMode;
private ProgressBar mActionBarProgress;
private MenuItem mMenuButtonCheckMail;
private View mActionButtonIndeterminateProgress;
private int mLastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS;
/**
* {@code true} if the message list should be displayed as flat list (i.e. no threading)
* regardless whether or not message threading was enabled in the settings. This is used for
* filtered views, e.g. when only displaying the unread messages in a folder.
*/
private boolean mNoThreading;
private DisplayMode mDisplayMode;
private MessageReference mMessageReference;
/**
* {@code true} when the message list was displayed once. This is used in
* {@link #onBackPressed()} to decide whether to go from the message view to the message list or
* finish the activity.
*/
private boolean mMessageListWasDisplayed = false;
private ViewSwitcher mViewSwitcher;
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return super.onCreatePanelMenu(featureId, menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setOverflowShowingAlways();
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
if (useSplitView()) {
setContentView(R.layout.split_message_list);
} else {
setContentView(R.layout.message_list);
mViewSwitcher = (ViewSwitcher) findViewById(R.id.container);
mViewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
mViewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
mViewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
mViewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
mViewSwitcher.setOnSwitchCompleteListener(this);
}
initializeActionBar();
// Enable gesture detection for MessageLists
setupGestureDetector(this);
if (!decodeExtras(getIntent())) {
return;
}
findFragments();
initializeDisplayMode(savedInstanceState);
initializeLayout();
initializeFragments();
displayViews();
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
// cl.getLogDialog().show();
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (mFirstBackStackId >= 0) {
getFragmentManager().popBackStackImmediate(mFirstBackStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
mFirstBackStackId = -1;
}
removeMessageListFragment();
removeMessageViewFragment();
mMessageReference = null;
mSearch = null;
mFolderName = null;
if (!decodeExtras(intent)) {
return;
}
initializeDisplayMode(null);
initializeFragments();
displayViews();
}
/**
* Get references to existing fragments if the activity was restarted.
*/
private void findFragments() {
FragmentManager fragmentManager = getFragmentManager();
mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById(
R.id.message_list_container);
mMessageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById(
R.id.message_view_container);
}
/**
* Create fragment instances if necessary.
*
* @see #findFragments()
*/
private void initializeFragments() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
boolean hasMessageListFragment = (mMessageListFragment != null);
if (!hasMessageListFragment) {
FragmentTransaction ft = fragmentManager.beginTransaction();
mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
(K9.isThreadedViewEnabled() && !mNoThreading));
ft.add(R.id.message_list_container, mMessageListFragment);
ft.commit();
}
// Check if the fragment wasn't restarted and has a MessageReference in the arguments. If
// so, open the referenced message.
if (!hasMessageListFragment && mMessageViewFragment == null &&
mMessageReference != null) {
openMessage(mMessageReference);
}
}
/**
* Set the initial display mode (message list, message view, or split view).
*
* <p><strong>Note:</strong>
* This method has to be called after {@link #findFragments()} because the result depends on
* the availability of a {@link MessageViewFragment} instance.
* </p>
*
* @param savedInstanceState
* The saved instance state that was passed to the activity as argument to
* {@link #onCreate(Bundle)}. May be {@code null}.
*/
private void initializeDisplayMode(Bundle savedInstanceState) {
if (useSplitView()) {
mDisplayMode = DisplayMode.SPLIT_VIEW;
return;
}
if (savedInstanceState != null) {
DisplayMode savedDisplayMode =
(DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
if (savedDisplayMode != DisplayMode.SPLIT_VIEW) {
mDisplayMode = savedDisplayMode;
return;
}
}
if (mMessageViewFragment != null || mMessageReference != null) {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
} else {
mDisplayMode = DisplayMode.MESSAGE_LIST;
}
}
private boolean useSplitView() {
SplitViewMode splitViewMode = K9.getSplitViewMode();
int orientation = getResources().getConfiguration().orientation;
return (splitViewMode == SplitViewMode.ALWAYS ||
(splitViewMode == SplitViewMode.WHEN_IN_LANDSCAPE &&
orientation == Configuration.ORIENTATION_LANDSCAPE));
}
private void initializeLayout() {
mMessageViewContainer = (ViewGroup) findViewById(R.id.message_view_container);
mMessageViewPlaceHolder = getLayoutInflater().inflate(R.layout.empty_message_view, null);
}
private void displayViews() {
switch (mDisplayMode) {
case MESSAGE_LIST: {
showMessageList();
break;
}
case MESSAGE_VIEW: {
showMessageView();
break;
}
case SPLIT_VIEW: {
mMessageListWasDisplayed = true;
if (mMessageViewFragment == null) {
showMessageViewPlaceHolder();
} else {
MessageReference activeMessage = mMessageViewFragment.getMessageReference();
if (activeMessage != null) {
mMessageListFragment.setActiveMessage(activeMessage);
}
}
break;
}
}
}
private boolean decodeExtras(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) {
Uri uri = intent.getData();
List<String> segmentList = uri.getPathSegments();
String accountId = segmentList.get(0);
Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts();
for (Account account : accounts) {
if (String.valueOf(account.getAccountNumber()).equals(accountId)) {
String folderName = segmentList.get(1);
String messageUid = segmentList.get(2);
mMessageReference = new MessageReference(account.getUuid(), folderName, messageUid, null);
break;
}
}
} else if (ACTION_SHORTCUT.equals(action)) {
// Handle shortcut intents
String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER);
if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) {
mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch();
} else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) {
mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch();
}
} else if (intent.getStringExtra(SearchManager.QUERY) != null) {
// check if this intent comes from the system search ( remote )
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//Query was received from Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY).trim();
mSearch = new LocalSearch(getString(R.string.search_results));
mSearch.setManualSearch(true);
mNoThreading = true;
mSearch.or(new SearchCondition(SearchField.SENDER, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(SearchField.SUBJECT, Attribute.CONTAINS, query));
// TODO re-enable search in message contents
// mSearch.or(new SearchCondition(SearchField.MESSAGE_CONTENTS, Attribute.CONTAINS, query));
// Toast.makeText(this, R.string.warn_search_disabled, Toast.LENGTH_LONG).show();
Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
// searches started from a folder list activity will provide an account, but no folder
if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
}
} else {
mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
} else {
// regular LocalSearch object was passed
mSearch = intent.getParcelableExtra(EXTRA_SEARCH);
mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
}
if (mMessageReference == null) {
mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE);
}
if (mMessageReference != null) {
mSearch = new LocalSearch();
mSearch.addAccountUuid(mMessageReference.getAccountUuid());
mSearch.addAllowedFolder(mMessageReference.getFolderName());
}
if (mSearch == null) {
// We've most likely been started by an old unread widget
String accountUuid = intent.getStringExtra("account");
String folderName = intent.getStringExtra("folder");
mSearch = new LocalSearch(folderName);
mSearch.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid);
if (folderName != null) {
mSearch.addAllowedFolder(folderName);
}
}
Preferences prefs = Preferences.getPreferences(getApplicationContext());
String[] accountUuids = mSearch.getAccountUuids();
if (mSearch.searchAllAccounts()) {
List<Account> accounts = prefs.getAccounts();
mSingleAccountMode = (accounts.size() == 1);
if (mSingleAccountMode) {
mAccount = accounts.get(0);
}
} else {
mSingleAccountMode = (accountUuids.length == 1);
if (mSingleAccountMode) {
mAccount = prefs.getAccount(accountUuids[0]);
}
}
mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1);
if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) {
Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account");
onAccountUnavailable();
return false;
}
if (mSingleFolderMode) {
mFolderName = mSearch.getFolderNames().get(0);
}
// now we know if we are in single account mode and need a subtitle
// mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE);
return true;
}
@Override
public void onPause() {
super.onPause();
StorageManager.getInstance(getApplication()).removeListener(mStorageListener);
}
@Override
public void onResume() {
super.onResume();
if (!(this instanceof Search)) {
//necessary b/c no guarantee Search.onStop will be called before MessageList.onResume
//when returning from search results
Search.setActive(false);
}
if (mAccount != null && !mAccount.isAvailable(this)) {
onAccountUnavailable();
return;
}
StorageManager.getInstance(getApplication()).addListener(mStorageListener);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_DISPLAY_MODE, mDisplayMode);
outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, mMessageListWasDisplayed);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
mMessageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED);
}
@Nullable
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return super.onCreateView(name, context, attrs);
}
private void initializeActionBar() {
mActionBar = getActionBar();
if(mActionBar == null) return;
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setCustomView(R.layout.actionbar_custom);
mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);
View customView = mActionBar.getCustomView();
mActionBarMessageList = customView.findViewById(R.id.actionbar_message_list);
mActionBarMessageView = customView.findViewById(R.id.actionbar_message_view);
mActionBarSubject = (MessageTitleView) customView.findViewById(R.id.message_title_view);
mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first);
mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub);
mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count);
mActionBarProgress = (ProgressBar) customView.findViewById(R.id.actionbar_progress);
mActionButtonIndeterminateProgress =
getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null);
mActionBar.setDisplayHomeAsUpEnabled(false);
mActionBar.setDisplayShowHomeEnabled(false);
/*邮件列表MessageListFragment*/
/*UI左侧菜单*/
customView.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(MessageList.this, "menu", Toast.LENGTH_SHORT).show();
goBack();
}
});
/*UI搜索邮件*/
customView.findViewById(R.id.search_mail).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMessageListFragment.onSearchRequested();
}
});
/*UI写邮件*/
customView.findViewById(R.id.new_mail).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMessageListFragment.onCompose();
}
});
/*阅读邮件MessageViewFragment*/
/*UI返回*/
customView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MessageList.this, "back", Toast.LENGTH_SHORT).show();
goBack();
}
});
/*UI上一封*/
customView.findViewById(R.id.before).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPreviousMessage();
}
});
/*UI下一封*/
customView.findViewById(R.id.after).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showNextMessage();
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean ret = false;
if (KeyEvent.ACTION_DOWN == event.getAction()) {
ret = onCustomKeyDown(event.getKeyCode(), event);
}
if (!ret) {
ret = super.dispatchKeyEvent(event);
}
return ret;
}
@Override
public void onBackPressed() {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW && mMessageListWasDisplayed) {
showMessageList();
} else {
super.onBackPressed();
}
}
/**
* Handle hotkeys
*
* <p>
* This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance
* to consume this key event.
* </p>
*
* @param keyCode
* The value in {@code event.getKeyCode()}.
* @param event
* Description of the key event.
*
* @return {@code true} if this event was consumed.
*/
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showPreviousMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveUp();
return true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showNextMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveDown();
return true;
}
break;
}
case KeyEvent.KEYCODE_C: {
mMessageListFragment.onCompose();
return true;
}
case KeyEvent.KEYCODE_Q: {
if (mMessageListFragment != null && mMessageListFragment.isSingleAccountMode()) {
onShowFolderList();
}
return true;
}
case KeyEvent.KEYCODE_O: {
mMessageListFragment.onCycleSort();
return true;
}
case KeyEvent.KEYCODE_I: {
mMessageListFragment.onReverseSort();
return true;
}
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_D: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onDelete();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onDelete();
}
return true;
}
case KeyEvent.KEYCODE_S: {
mMessageListFragment.toggleMessageSelect();
return true;
}
case KeyEvent.KEYCODE_G: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleFlagged();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleFlagged();
}
return true;
}
case KeyEvent.KEYCODE_M: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onMove();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onMove();
}
return true;
}
case KeyEvent.KEYCODE_V: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onArchive();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onArchive();
}
return true;
}
case KeyEvent.KEYCODE_Y: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onCopy();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onCopy();
}
return true;
}
case KeyEvent.KEYCODE_Z: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleRead();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleRead();
}
return true;
}
case KeyEvent.KEYCODE_F: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onForward();
}
return true;
}
case KeyEvent.KEYCODE_A: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReplyAll();
}
return true;
}
case KeyEvent.KEYCODE_R: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReply();
}
return true;
}
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_P: {
if (mMessageViewFragment != null) {
showPreviousMessage();
}
return true;
}
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_K: {
if (mMessageViewFragment != null) {
showNextMessage();
}
return true;
}
/* FIXME
case KeyEvent.KEYCODE_Z: {
mMessageViewFragment.zoom(event);
return true;
}*/
case KeyEvent.KEYCODE_H: {
Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
toast.show();
return true;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Swallow these events too to avoid the audible notification of a volume change
if (K9.useVolumeKeysForListNavigationEnabled()) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Swallowed key up.");
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void onAccounts() {
Accounts.listAccounts(this);
finish();
}
private void onShowFolderList() {
FolderList.actionHandleAccount(this, mAccount);
finish();
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccount);
}
@Override
public boolean onSearchRequested() {
return mMessageListFragment.onSearchRequested();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
goBack();
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.toggle_message_view_theme: {
onToggleTheme();
return true;
}
// MessageList
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
case R.id.set_sort_sender: {
mMessageListFragment.changeSort(SortType.SORT_SENDER);
return true;
}
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
case R.id.mark_all_as_read: {
mMessageListFragment.markAllAsRead();
return true;
}
case R.id.show_folder_list: {
onShowFolderList();
return true;
}
// MessageView
case R.id.next_message: {
showNextMessage();
return true;
}
case R.id.previous_message: {
showPreviousMessage();
return true;
}
case R.id.delete: {
mMessageViewFragment.onDelete();
return true;
}
case R.id.reply: {
mMessageViewFragment.onReply();
return true;
}
case R.id.reply_all: {
mMessageViewFragment.onReplyAll();
return true;
}
case R.id.forward: {
mMessageViewFragment.onForward();
return true;
}
case R.id.share: {
mMessageViewFragment.onSendAlternate();
return true;
}
case R.id.toggle_unread: {
mMessageViewFragment.onToggleRead();
return true;
}
case R.id.archive:
case R.id.refile_archive: {
mMessageViewFragment.onArchive();
return true;
}
case R.id.spam:
case R.id.refile_spam: {
mMessageViewFragment.onSpam();
return true;
}
case R.id.move:
case R.id.refile_move: {
mMessageViewFragment.onMove();
return true;
}
case R.id.copy:
case R.id.refile_copy: {
mMessageViewFragment.onCopy();
return true;
}
case R.id.select_text: {
mMessageViewFragment.onSelectText();
return true;
}
case R.id.show_headers:
case R.id.hide_headers: {
mMessageViewFragment.onToggleAllHeadersView();
updateMenu();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.message_list_option, menu);
mMenu = menu;
mMenuButtonCheckMail= menu.findItem(R.id.check_mail);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
configureMenu(menu);
return true;
}
/**
* Hide menu items not appropriate for the current context.
*
* <p><strong>Note:</strong>
* Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the
* visibility of a menu item in this method.
* </p>
*
* @param menu
* The {@link Menu} instance that should be modified. May be {@code null}; in that case
* the method does nothing and immediately returns.
*/
private void configureMenu(Menu menu) {
if (menu == null) {
return;
}
// Set visibility of account/folder settings menu items
if (mMessageListFragment == null) {
menu.findItem(R.id.account_settings).setVisible(false);
menu.findItem(R.id.folder_settings).setVisible(false);
} else {
menu.findItem(R.id.account_settings).setVisible(
mMessageListFragment.isSingleAccountMode());
menu.findItem(R.id.folder_settings).setVisible(
mMessageListFragment.isSingleFolderMode());
}
/*
* Set visibility of menu items related to the message view
*/
if (mDisplayMode == DisplayMode.MESSAGE_LIST
|| mMessageViewFragment == null
|| !mMessageViewFragment.isInitialized()) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
menu.findItem(R.id.single_message_options).setVisible(false);
menu.findItem(R.id.delete).setVisible(false);
menu.findItem(R.id.compose).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
menu.findItem(R.id.toggle_unread).setVisible(false);
menu.findItem(R.id.select_text).setVisible(false);
menu.findItem(R.id.toggle_message_view_theme).setVisible(false);
menu.findItem(R.id.show_headers).setVisible(false);
menu.findItem(R.id.hide_headers).setVisible(false);
} else {
// hide prev/next buttons in split mode
if (mDisplayMode != DisplayMode.MESSAGE_VIEW) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
} else {
MessageReference ref = mMessageViewFragment.getMessageReference();
boolean initialized = (mMessageListFragment != null &&
mMessageListFragment.isLoadFinished());
boolean canDoPrev = (initialized && !mMessageListFragment.isFirst(ref));
boolean canDoNext = (initialized && !mMessageListFragment.isLast(ref));
MenuItem prev = menu.findItem(R.id.previous_message);
prev.setEnabled(canDoPrev);
prev.getIcon().setAlpha(canDoPrev ? 255 : 127);
MenuItem next = menu.findItem(R.id.next_message);
next.setEnabled(canDoNext);
next.getIcon().setAlpha(canDoNext ? 255 : 127);
}
MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme);
if (K9.useFixedMessageViewTheme()) {
toggleTheme.setVisible(false);
} else {
// Set title of menu item to switch to dark/light theme
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
toggleTheme.setTitle(R.string.message_view_theme_action_light);
} else {
toggleTheme.setTitle(R.string.message_view_theme_action_dark);
}
toggleTheme.setVisible(true);
}
// Set title of menu item to toggle the read state of the currently displayed message
if (mMessageViewFragment.isMessageRead()) {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action);
} else {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action);
}
// Jellybean has built-in long press selection support
menu.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16);
menu.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible());
/*
* Set visibility of copy, move, archive, spam in action bar and refile submenu
*/
if (mMessageViewFragment.isCopyCapable()) {
menu.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible());
menu.findItem(R.id.refile_copy).setVisible(true);
} else {
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.refile_copy).setVisible(false);
}
if (mMessageViewFragment.isMoveCapable()) {
boolean canMessageBeArchived = mMessageViewFragment.canMessageBeArchived();
boolean canMessageBeMovedToSpam = mMessageViewFragment.canMessageBeMovedToSpam();
menu.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible());
menu.findItem(R.id.archive).setVisible(canMessageBeArchived &&
K9.isMessageViewArchiveActionVisible());
menu.findItem(R.id.spam).setVisible(canMessageBeMovedToSpam &&
K9.isMessageViewSpamActionVisible());
menu.findItem(R.id.refile_move).setVisible(true);
menu.findItem(R.id.refile_archive).setVisible(canMessageBeArchived);
menu.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam);
} else {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
}
if (mMessageViewFragment.allHeadersVisible()) {
menu.findItem(R.id.show_headers).setVisible(false);
} else {
menu.findItem(R.id.hide_headers).setVisible(false);
}
}
/*
* Set visibility of menu items related to the message list
*/
// Hide both search menu items by default and enable one when appropriate
menu.findItem(R.id.search).setVisible(false);
menu.findItem(R.id.search_remote).setVisible(false);
if (mDisplayMode == DisplayMode.MESSAGE_VIEW || mMessageListFragment == null ||
!mMessageListFragment.isInitialized()) {
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.set_sort).setVisible(false);
menu.findItem(R.id.select_all).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.mark_all_as_read).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.set_sort).setVisible(true);
menu.findItem(R.id.select_all).setVisible(true);
menu.findItem(R.id.compose).setVisible(true);
menu.findItem(R.id.mark_all_as_read).setVisible(
mMessageListFragment.isMarkAllAsReadSupported());
if (!mMessageListFragment.isSingleAccountMode()) {
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.send_messages).setVisible(mMessageListFragment.isOutbox());
menu.findItem(R.id.expunge).setVisible(mMessageListFragment.isRemoteFolder() &&
mMessageListFragment.isAccountExpungeCapable());
menu.findItem(R.id.show_folder_list).setVisible(true);
}
menu.findItem(R.id.check_mail).setVisible(mMessageListFragment.isCheckMailSupported());
// If this is an explicit local search, show the option to search on the server
if (!mMessageListFragment.isRemoteSearch() &&
mMessageListFragment.isRemoteSearchAllowed()) {
menu.findItem(R.id.search_remote).setVisible(true);
} else if (!mMessageListFragment.isManualSearch()) {
menu.findItem(R.id.search).setVisible(true);
}
}
}
protected void onAccountUnavailable() {
finish();
// TODO inform user about account unavailability using Toast
Accounts.listAccounts(this);
}
public void setActionBarTitle(String title) {
mActionBarTitle.setText(title);
}
public void setActionBarSubTitle(String subTitle) {
mActionBarSubTitle.setText(subTitle);
}
public void setActionBarUnread(int unread) {
if (unread == 0) {
mActionBarUnread.setVisibility(View.GONE);
} else {
mActionBarUnread.setVisibility(View.VISIBLE);
mActionBarUnread.setText(Integer.toString(unread));
}
}
@Override
public void setMessageListTitle(String title) {
setActionBarTitle(title);
}
@Override
public void setMessageListSubTitle(String subTitle) {
setActionBarSubTitle(subTitle);
}
@Override
public void setUnreadCount(int unread) {
setActionBarUnread(unread);
}
@Override
public void setMessageListProgress(int progress) {
setProgress(progress);
}
@Override
public void openMessage(MessageReference messageReference) {
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.getAccountUuid());
String folderName = messageReference.getFolderName();
if (folderName.equals(account.getDraftsFolderName())) {
MessageCompose.actionEditDraft(this, messageReference);
} else {
mMessageViewContainer.removeView(mMessageViewPlaceHolder);
if (mMessageListFragment != null) {
mMessageListFragment.setActiveMessage(messageReference);
}
MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_view_container, fragment);
mMessageViewFragment = fragment;
ft.commit();
if (mDisplayMode != DisplayMode.SPLIT_VIEW) {
showMessageView();
}
}
}
@Override
public void onResendMessage(LocalMessage message) {
MessageCompose.actionEditDraft(this, message.makeMessageReference());
}
@Override
public void onForward(LocalMessage message) {
MessageCompose.actionForward(this, message, null);
}
@Override
public void onReply(LocalMessage message) {
MessageCompose.actionReply(this, message, false, null);
}
@Override
public void onReplyAll(LocalMessage message) {
MessageCompose.actionReply(this, message, true, null);
}
@Override
public void onCompose(Account account) {
MessageCompose.actionCompose(this, account);
}
@Override
public void showMoreFromSameSender(String senderAddress) {
LocalSearch tmpSearch = new LocalSearch("From " + senderAddress);
tmpSearch.addAccountUuids(mSearch.getAccountUuids());
tmpSearch.and(SearchField.SENDER, senderAddress, Attribute.CONTAINS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false);
addMessageListFragment(fragment, true);
}
@Override
public void onBackStackChanged() {
findFragments();
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
}
configureMenu(mMenu);
}
@Override
public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeRightToLeft(e1, e2);
}
}
@Override
public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeLeftToRight(e1, e2);
}
}
private final class StorageListenerImplementation implements StorageManager.StorageListener {
@Override
public void onUnmount(String providerId) {
if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onAccountUnavailable();
}
});
}
}
@Override
public void onMount(String providerId) {
// no-op
}
}
private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_list_container, fragment);
if (addToBackStack)
ft.addToBackStack(null);
mMessageListFragment = fragment;
int transactionId = ft.commit();
if (transactionId >= 0 && mFirstBackStackId < 0) {
mFirstBackStackId = transactionId;
}
}
@Override
public boolean startSearch(Account account, String folderName) {
// If this search was started from a MessageList of a single folder, pass along that folder info
// so that we can enable remote search.
if (account != null && folderName != null) {
final Bundle appData = new Bundle();
appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid());
appData.putString(EXTRA_SEARCH_FOLDER, folderName);
startSearch(null, false, appData, false);
} else {
// TODO Handle the case where we're searching from within a search result.
startSearch(null, false, null, false);
}
return true;
}
@Override
public void showThread(Account account, String folderName, long threadRootId) {
showMessageViewPlaceHolder();
LocalSearch tmpSearch = new LocalSearch();
tmpSearch.addAccountUuid(account.getUuid());
tmpSearch.and(SearchField.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false);
addMessageListFragment(fragment, true);
}
private void showMessageViewPlaceHolder() {
removeMessageViewFragment();
// Add placeholder view if necessary
if (mMessageViewPlaceHolder.getParent() == null) {
mMessageViewContainer.addView(mMessageViewPlaceHolder);
}
mMessageListFragment.setActiveMessage(null);
}
/**
* Remove MessageViewFragment if necessary.
*/
private void removeMessageViewFragment() {
if (mMessageViewFragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageViewFragment);
mMessageViewFragment = null;
ft.commit();
showDefaultTitleView();
}
}
private void removeMessageListFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageListFragment);
mMessageListFragment = null;
ft.commit();
}
@Override
public void remoteSearchStarted() {
// Remove action button for remote search
configureMenu(mMenu);
}
@Override
public void goBack() {
FragmentManager fragmentManager = getFragmentManager();
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
showMessageList();
} else if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (mMessageListFragment.isManualSearch()) {
finish();
} else if (!mSingleFolderMode) {
onAccounts();
} else {
onShowFolderList();
}
}
@Override
public void enableActionBarProgress(boolean enable) {
if (mMenuButtonCheckMail != null && mMenuButtonCheckMail.isVisible()) {
mActionBarProgress.setVisibility(ProgressBar.GONE);
if (enable) {
mMenuButtonCheckMail
.setActionView(mActionButtonIndeterminateProgress);
} else {
mMenuButtonCheckMail.setActionView(null);
}
} else {
if (mMenuButtonCheckMail != null)
mMenuButtonCheckMail.setActionView(null);
if (enable) {
mActionBarProgress.setVisibility(ProgressBar.GONE);
} else {
mActionBarProgress.setVisibility(ProgressBar.GONE);
}
}
}
@Override
public void displayMessageSubject(String subject) {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
mActionBarSubject.setText(subject);
}
}
@Override
public void onReply(LocalMessage message, PgpData pgpData) {
MessageCompose.actionReply(this, message, false, pgpData.getDecryptedData());
}
@Override
public void onReplyAll(LocalMessage message, PgpData pgpData) {
MessageCompose.actionReply(this, message, true, pgpData.getDecryptedData());
}
@Override
public void onForward(LocalMessage mMessage, PgpData mPgpData) {
MessageCompose.actionForward(this, mMessage, mPgpData.getDecryptedData());
}
@Override
public void showNextMessageOrReturn() {
if (K9.messageViewReturnToList() || !showLogicalNextMessage()) {
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
} else {
showMessageList();
}
}
}
/**
* Shows the next message in the direction the user was displaying messages.
*
* @return {@code true}
*/
private boolean showLogicalNextMessage() {
boolean result = false;
if (mLastDirection == NEXT) {
result = showNextMessage();
} else if (mLastDirection == PREVIOUS) {
result = showPreviousMessage();
}
if (!result) {
result = showNextMessage() || showPreviousMessage();
}
return result;
}
@Override
public void setProgress(boolean enable) {
setProgressBarIndeterminateVisibility(enable);
}
@Override
public void messageHeaderViewAvailable(MessageHeader header) {
mActionBarSubject.setMessageHeader(header);
}
private boolean showNextMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openNext(ref)) {
mLastDirection = NEXT;
return true;
}
}
return false;
}
private boolean showPreviousMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openPrevious(ref)) {
mLastDirection = PREVIOUS;
return true;
}
}
return false;
}
private void showMessageList() {
mMessageListWasDisplayed = true;
mDisplayMode = DisplayMode.MESSAGE_LIST;
mViewSwitcher.showFirstView();
mMessageListFragment.setActiveMessage(null);
showDefaultTitleView();
configureMenu(mMenu);
}
private void showMessageView() {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
if (!mMessageListWasDisplayed) {
mViewSwitcher.setAnimateFirstView(false);
}
mViewSwitcher.showSecondView();
showMessageTitleView();
configureMenu(mMenu);
}
@Override
public void updateMenu() {
invalidateOptionsMenu();
}
@Override
public void disableDeleteAction() {
mMenu.findItem(R.id.delete).setEnabled(false);
}
private void onToggleTheme() {
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
K9.setK9MessageViewThemeSetting(K9.Theme.LIGHT);
} else {
K9.setK9MessageViewThemeSetting(K9.Theme.DARK);
}
new Thread(new Runnable() {
@Override
public void run() {
Context appContext = getApplicationContext();
Preferences prefs = Preferences.getPreferences(appContext);
Editor editor = prefs.getPreferences().edit();
K9.save(editor);
editor.commit();
}
}).start();
recreate();
}
private void showDefaultTitleView() {
mActionBarMessageView.setVisibility(View.GONE);
mActionBarMessageList.setVisibility(View.VISIBLE);
if (mMessageListFragment != null) {
mMessageListFragment.updateTitle();
}
mActionBarSubject.setMessageHeader(null);
}
private void showMessageTitleView() {
mActionBarMessageList.setVisibility(View.GONE);
mActionBarMessageView.setVisibility(View.VISIBLE);
if (mMessageViewFragment != null) {
displayMessageSubject(null);
mMessageViewFragment.updateTitle();
}
}
@Override
public void onSwitchComplete(int displayedChild) {
if (displayedChild == 0) {
removeMessageViewFragment();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mMessageViewFragment != null) {
mMessageViewFragment.handleCryptoResult(requestCode, resultCode, data);
}
}
/*隐藏ActionBar overflow button*/
private void setOverflowShowingAlways() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Log.e("K9mail", " " + config.hasPermanentMenuKey());
if(config.hasPermanentMenuKey()) return;
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, true);
Log.e("K9mail", " " + config.hasPermanentMenuKey());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
{
"content_hash": "f0db8d7deaecc58a9c4111005eaf3a92",
"timestamp": "",
"source": "github",
"line_count": 1656,
"max_line_length": 110,
"avg_line_length": 36.30072463768116,
"alnum_prop": 0.5994111188741391,
"repo_name": "github201407/k-9",
"id": "1804dca1e5269e4cf00001ce52530781262bf2ba",
"size": "60172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "k9mail/src/main/java/com/fsck/k9/activity/MessageList.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "292"
},
{
"name": "Java",
"bytes": "3695982"
},
{
"name": "Shell",
"bytes": "875"
}
],
"symlink_target": ""
}
|
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Tap.Sdk
{
using System;
using System.Collections;
using System.Collections.Generic;
public sealed class TestSet : IEnumerable<ITestCase>
{
private readonly HashSet<ITestCase> _set = new HashSet<ITestCase>();
private int _failuresCount;
public TestSet() { }
public TestSet(int size)
{
Size = size;
}
public static TestSet Empty { get; } = new TestSet(0);
public int TestsCount => _set.Count;
public int FailuresCount => _failuresCount;
public int? Size { get; }
public bool BailedOut { get; private set; }
public string BailOutReason { get; private set; }
public bool Passed
=> !BailedOut && FailuresCount == 0 && (!Size.HasValue || TestsCount == Size.Value);
public void BailOut()
{
BailedOut = true;
}
public void BailOut(string reason)
{
BailedOut = true;
BailOutReason = reason ?? String.Empty;
}
public void Add(TestCase testCase)
{
Require.NotNull(testCase, nameof(testCase));
ThrowIfBailedOut();
if (!testCase.Passed) { _failuresCount++; }
_set.Add(testCase);
}
// NB: A skipped test is never counted as failure.
public void Add(SkippedTestCase testCase)
{
Require.NotNull(testCase, nameof(testCase));
ThrowIfBailedOut();
_set.Add(testCase);
}
// NB: A To-do test is never counted as failure.
public void Add(TodoTestCase testCase)
{
Require.NotNull(testCase, nameof(testCase));
ThrowIfBailedOut();
_set.Add(testCase);
}
public IEnumerator<ITestCase> GetEnumerator() => _set.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private void ThrowIfBailedOut()
{
if (BailedOut)
{
throw new InvalidOperationException();
}
}
}
}
|
{
"content_hash": "024512a3e9e0b5bda4b731ff77d5c569",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 112,
"avg_line_length": 24.725274725274726,
"alnum_prop": 0.56,
"repo_name": "chtoucas/Archives",
"id": "6de0dec405ac4c88ddea5d79c9d80047c3ae463b",
"size": "2252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tap/src/Sdk/TestSet.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3548"
},
{
"name": "C#",
"bytes": "320439"
},
{
"name": "F#",
"bytes": "599"
},
{
"name": "PowerShell",
"bytes": "75111"
}
],
"symlink_target": ""
}
|
Yii2 Content Manager
|
{
"content_hash": "daf762e3dca4510a9195f4b31b69c6bc",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 20,
"avg_line_length": 21,
"alnum_prop": 0.8571428571428571,
"repo_name": "RichWeber/yii2-content-manager",
"id": "3e0f1cc936667f3fdbbc2b04813392651c776507",
"size": "44",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "26139"
}
],
"symlink_target": ""
}
|
<?php
/**
* Doctrine_Export_Mysql
*
* @package Doctrine
* @subpackage Export
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.phpdoctrine.org
* @since 1.0
* @version $Revision: 5456 $
*/
class Doctrine_Export_Mysql extends Doctrine_Export
{
/**
* drop existing constraint
*
* @param string $table name of table that should be used in method
* @param string $name name of the constraint to be dropped
* @param string $primary hint if the constraint is primary
* @return void
*/
public function dropConstraint($table, $name, $primary = false)
{
$table = $this->conn->quoteIdentifier($table);
if ( ! $primary) {
$name = 'CONSTRAINT ' . $this->conn->quoteIdentifier($name);
} else {
$name = 'PRIMARY KEY';
}
return $this->conn->exec('ALTER TABLE ' . $table . ' DROP ' . $name);
}
/**
* createDatabaseSql
*
* @param string $name
* @return void
*/
public function createDatabaseSql($name)
{
return 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name, true);
}
/**
* drop an existing database
*
* @param string $name name of the database that should be dropped
* @return string
*/
public function dropDatabaseSql($name)
{
return 'DROP DATABASE ' . $this->conn->quoteIdentifier($name);
}
/**
* create a new table
*
* @param string $name Name of the database that should be created
* @param array $fields Associative array that contains the definition of each field of the new table
* The indexes of the array entries are the names of the fields of the table an
* the array entry values are associative arrays like those that are meant to be
* passed with the field definitions to get[Type]Declaration() functions.
* array(
* 'id' => array(
* 'type' => 'integer',
* 'unsigned' => 1
* 'notnull' => 1
* 'default' => 0
* ),
* 'name' => array(
* 'type' => 'text',
* 'length' => 12
* ),
* 'password' => array(
* 'type' => 'text',
* 'length' => 12
* )
* );
* @param array $options An associative array of table options:
* array(
* 'comment' => 'Foo',
* 'charset' => 'utf8',
* 'collate' => 'utf8_unicode_ci',
* 'type' => 'innodb',
* );
*
* @return void
*/
public function createTableSql($name, array $fields, array $options = array())
{
if ( ! $name)
throw new Doctrine_Export_Exception('no valid table name specified');
if (empty($fields)) {
throw new Doctrine_Export_Exception('no fields specified for table "'.$name.'"');
}
$queryFields = $this->getFieldDeclarationList($fields);
// build indexes for all foreign key fields (needed in MySQL!!)
if (isset($options['foreignKeys'])) {
foreach ($options['foreignKeys'] as $fk) {
$local = $fk['local'];
$found = false;
if (isset($options['indexes'])) {
foreach ($options['indexes'] as $definition) {
if (is_string($definition['fields'])) {
// Check if index already exists on the column
$found = ($local == $definition['fields']);
} else if (in_array($local, $definition['fields']) && count($definition['fields']) === 1) {
// Index already exists on the column
$found = true;
}
}
}
if (isset($options['primary']) && !empty($options['primary']) &&
in_array($local, $options['primary'])) {
// field is part of the PK and therefore already indexed
$found = true;
}
if ( ! $found) {
if (is_array($local)) {
foreach($local as $localidx) {
$options['indexes'][$localidx] = array('fields' => array($localidx => array()));
}
} else {
$options['indexes'][$local] = array('fields' => array($local => array()));
}
}
}
}
// add all indexes
if (isset($options['indexes']) && ! empty($options['indexes'])) {
foreach($options['indexes'] as $index => $definition) {
$queryFields .= ', ' . $this->getIndexDeclaration($index, $definition);
}
}
// attach all primary keys
if (isset($options['primary']) && ! empty($options['primary'])) {
$keyColumns = array_values($options['primary']);
$keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns);
$queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
}
$query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields . ')';
$optionStrings = array();
if (isset($options['comment'])) {
$optionStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'text');
}
if (isset($options['charset'])) {
$optionStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset'];
}
if (isset($options['collate'])) {
$optionStrings['collate'] = 'COLLATE ' . $options['collate'];
}
$type = false;
// get the type of the table
if (isset($options['type'])) {
$type = $options['type'];
} else {
$type = $this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TABLE_TYPE);
}
if ($type) {
$optionStrings[] = 'ENGINE = ' . $type;
}
if ( ! empty($optionStrings)) {
$query.= ' '.implode(' ', $optionStrings);
}
$sql[] = $query;
if (isset($options['foreignKeys'])) {
foreach ((array) $options['foreignKeys'] as $k => $definition) {
if (is_array($definition)) {
$sql[] = $this->createForeignKeySql($name, $definition);
}
}
}
return $sql;
}
/**
* Obtain DBMS specific SQL code portion needed to declare a generic type
* field to be used in statements like CREATE TABLE.
*
* @param string $name name the field to be declared.
* @param array $field associative array with the name of the properties
* of the field being declared as array indexes. Currently, the types
* of supported field properties are as follows:
*
* length
* Integer value that determines the maximum length of the text
* field. If this argument is missing the field should be
* declared to have the longest length allowed by the DBMS.
*
* default
* Text value to be used as default for this field.
*
* notnull
* Boolean flag that indicates whether this field is constrained
* to not be set to null.
* charset
* Text value with the default CHARACTER SET for this field.
* collation
* Text value with the default COLLATION for this field.
* unique
* unique constraint
* check
* column check constraint
*
* @return string DBMS specific SQL code portion that should be used to
* declare the specified field.
*/
public function getDeclaration($name, array $field)
{
$default = $this->getDefaultFieldDeclaration($field);
$charset = (isset($field['charset']) && $field['charset']) ?
' ' . $this->getCharsetFieldDeclaration($field['charset']) : '';
$collation = (isset($field['collation']) && $field['collation']) ?
' ' . $this->getCollationFieldDeclaration($field['collation']) : '';
$notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : '';
$unique = (isset($field['unique']) && $field['unique']) ?
' ' . $this->getUniqueFieldDeclaration() : '';
$check = (isset($field['check']) && $field['check']) ?
' ' . $field['check'] : '';
$comment = (isset($field['comment']) && $field['comment']) ?
" COMMENT '" . $field['comment'] . "'" : '';
$method = 'get' . $field['type'] . 'Declaration';
try {
if (method_exists($this->conn->dataDict, $method)) {
return $this->conn->dataDict->$method($name, $field);
} else {
$dec = $this->conn->dataDict->getNativeDeclaration($field);
}
return $this->conn->quoteIdentifier($name, true)
. ' ' . $dec . $charset . $default . $notnull . $comment . $unique . $check . $collation;
} catch (Exception $e) {
throw new Doctrine_Exception('Around field ' . $name . ': ' . $e->getMessage());
}
}
/**
* alter an existing table
*
* @param string $name name of the table that is intended to be changed.
* @param array $changes associative array that contains the details of each type
* of change that is intended to be performed. The types of
* changes that are currently supported are defined as follows:
*
* name
*
* New name for the table.
*
* add
*
* Associative array with the names of fields to be added as
* indexes of the array. The value of each entry of the array
* should be set to another associative array with the properties
* of the fields to be added. The properties of the fields should
* be the same as defined by the Metabase parser.
*
*
* remove
*
* Associative array with the names of fields to be removed as indexes
* of the array. Currently the values assigned to each entry are ignored.
* An empty array should be used for future compatibility.
*
* rename
*
* Associative array with the names of fields to be renamed as indexes
* of the array. The value of each entry of the array should be set to
* another associative array with the entry named name with the new
* field name and the entry named Declaration that is expected to contain
* the portion of the field declaration already in DBMS specific SQL code
* as it is used in the CREATE TABLE statement.
*
* change
*
* Associative array with the names of the fields to be changed as indexes
* of the array. Keep in mind that if it is intended to change either the
* name of a field and any other properties, the change array entries
* should have the new names of the fields as array indexes.
*
* The value of each entry of the array should be set to another associative
* array with the properties of the fields to that are meant to be changed as
* array entries. These entries should be assigned to the new values of the
* respective properties. The properties of the fields should be the same
* as defined by the Metabase parser.
*
* Example
* array(
* 'name' => 'userlist',
* 'add' => array(
* 'quota' => array(
* 'type' => 'integer',
* 'unsigned' => 1
* )
* ),
* 'remove' => array(
* 'file_limit' => array(),
* 'time_limit' => array()
* ),
* 'change' => array(
* 'name' => array(
* 'length' => '20',
* 'definition' => array(
* 'type' => 'text',
* 'length' => 20,
* ),
* )
* ),
* 'rename' => array(
* 'sex' => array(
* 'name' => 'gender',
* 'definition' => array(
* 'type' => 'text',
* 'length' => 1,
* 'default' => 'M',
* ),
* )
* )
* )
*
* @param boolean $check indicates whether the function should just check if the DBMS driver
* can perform the requested table alterations if the value is true or
* actually perform them otherwise.
* @return boolean
*/
public function alterTableSql($name, array $changes, $check = false)
{
if ( ! $name) {
throw new Doctrine_Export_Exception('no valid table name specified');
}
foreach ($changes as $changeName => $change) {
switch ($changeName) {
case 'add':
case 'remove':
case 'change':
case 'rename':
case 'name':
break;
default:
throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported');
}
}
if ($check) {
return true;
}
$query = '';
if ( ! empty($changes['name'])) {
$change_name = $this->conn->quoteIdentifier($changes['name']);
$query .= 'RENAME TO ' . $change_name;
}
if ( ! empty($changes['add']) && is_array($changes['add'])) {
foreach ($changes['add'] as $fieldName => $field) {
if ($query) {
$query.= ', ';
}
$query.= 'ADD ' . $this->getDeclaration($fieldName, $field);
}
}
if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
foreach ($changes['remove'] as $fieldName => $field) {
if ($query) {
$query .= ', ';
}
$fieldName = $this->conn->quoteIdentifier($fieldName);
$query .= 'DROP ' . $fieldName;
}
}
$rename = array();
if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
foreach ($changes['rename'] as $fieldName => $field) {
$rename[$field['name']] = $fieldName;
}
}
if ( ! empty($changes['change']) && is_array($changes['change'])) {
foreach ($changes['change'] as $fieldName => $field) {
if ($query) {
$query.= ', ';
}
if (isset($rename[$fieldName])) {
$oldFieldName = $rename[$fieldName];
unset($rename[$fieldName]);
} else {
$oldFieldName = $fieldName;
}
$oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true);
$query .= 'CHANGE ' . $oldFieldName . ' '
. $this->getDeclaration($fieldName, $field['definition']);
}
}
if ( ! empty($rename) && is_array($rename)) {
foreach ($rename as $renameName => $renamedField) {
if ($query) {
$query.= ', ';
}
$field = $changes['rename'][$renamedField];
$renamedField = $this->conn->quoteIdentifier($renamedField, true);
$query .= 'CHANGE ' . $renamedField . ' '
. $this->getDeclaration($field['name'], $field['definition']);
}
}
if ( ! $query) {
return false;
}
$name = $this->conn->quoteIdentifier($name, true);
return 'ALTER TABLE ' . $name . ' ' . $query;
}
/**
* create sequence
*
* @param string $sequenceName name of the sequence to be created
* @param string $start start value of the sequence; default is 1
* @param array $options An associative array of table options:
* array(
* 'comment' => 'Foo',
* 'charset' => 'utf8',
* 'collate' => 'utf8_unicode_ci',
* 'type' => 'innodb',
* );
* @return boolean
*/
public function createSequence($sequenceName, $start = 1, array $options = array())
{
$sequenceName = $this->conn->quoteIdentifier($sequenceName, true);
$seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine::ATTR_SEQCOL_NAME), true);
$optionsStrings = array();
if (isset($options['comment']) && ! empty($options['comment'])) {
$optionsStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'string');
}
if (isset($options['charset']) && ! empty($options['charset'])) {
$optionsStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset'];
if (isset($options['collate'])) {
$optionsStrings['charset'] .= ' COLLATE ' . $options['collate'];
}
}
$type = false;
if (isset($options['type'])) {
$type = $options['type'];
} else {
$type = $this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TABLE_TYPE);
}
if ($type) {
$optionsStrings[] = 'ENGINE = ' . $type;
}
try {
$query = 'CREATE TABLE ' . $sequenceName
. ' (' . $seqcolName . ' BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY ('
. $seqcolName . ')) ' . implode($optionsStrings, ' ');
$res = $this->conn->exec($query);
} catch(Doctrine_Connection_Exception $e) {
throw new Doctrine_Export_Exception('could not create sequence table');
}
if ($start == 1 && $res == 1)
return true;
$query = 'INSERT INTO ' . $sequenceName
. ' (' . $seqcolName . ') VALUES (' . ($start - 1) . ')';
$res = $this->conn->exec($query);
if ($res == 1)
return true;
// Handle error
try {
$result = $this->conn->exec('DROP TABLE ' . $sequenceName);
} catch(Doctrine_Connection_Exception $e) {
throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
}
}
/**
* Get the stucture of a field into an array
*
* @author Leoncx
* @param string $table name of the table on which the index is to be created
* @param string $name name of the index to be created
* @param array $definition associative array that defines properties of the index to be created.
* Currently, only one property named FIELDS is supported. This property
* is also an associative with the names of the index fields as array
* indexes. Each entry of this array is set to another type of associative
* array that specifies properties of the index that are specific to
* each field.
*
* Currently, only the sorting property is supported. It should be used
* to define the sorting direction of the index. It may be set to either
* ascending or descending.
*
* Not all DBMS support index sorting direction configuration. The DBMS
* drivers of those that do not support it ignore this property. Use the
* function supports() to determine whether the DBMS driver can manage indexes.
*
* Example
* array(
* 'fields' => array(
* 'user_name' => array(
* 'sorting' => 'ASC'
* 'length' => 10
* ),
* 'last_login' => array()
* )
* )
* @throws PDOException
* @return void
*/
public function createIndexSql($table, $name, array $definition)
{
$table = $table;
$name = $this->conn->formatter->getIndexName($name);
$name = $this->conn->quoteIdentifier($name);
$type = '';
if (isset($definition['type'])) {
switch (strtolower($definition['type'])) {
case 'fulltext':
case 'unique':
$type = strtoupper($definition['type']) . ' ';
break;
default:
throw new Doctrine_Export_Exception(
'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table
);
}
}
$query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table;
$query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
return $query;
}
/**
* getDefaultDeclaration
* Obtain DBMS specific SQL code portion needed to set a default value
* declaration to be used in statements like CREATE TABLE.
*
* @param array $field field definition array
* @return string DBMS specific SQL code portion needed to set a default value
*/
public function getDefaultFieldDeclaration($field)
{
$default = '';
if (isset($field['default']) && ( ! isset($field['length']) || $field['length'] <= 255)) {
if ($field['default'] === '') {
$field['default'] = empty($field['notnull'])
? null : $this->valid_default_values[$field['type']];
if ($field['default'] === ''
&& ($this->conn->getAttribute(Doctrine::ATTR_PORTABILITY) & Doctrine::PORTABILITY_EMPTY_TO_NULL)
) {
$field['default'] = ' ';
}
}
// Proposed patch:
if ($field['type'] == 'enum' && $this->conn->getAttribute(Doctrine::ATTR_USE_NATIVE_ENUM)) {
$fieldType = 'varchar';
} else {
$fieldType = $field['type'];
}
$default = ' DEFAULT ' . (is_null($field['default'])
? 'NULL'
: $this->conn->quote($field['default'], $fieldType));
//$default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']);
}
return $default;
}
/**
* Obtain DBMS specific SQL code portion needed to set an index
* declaration to be used in statements like CREATE TABLE.
*
* @param string $charset name of the index
* @param array $definition index definition
* @return string DBMS specific SQL code portion needed to set an index
*/
public function getIndexDeclaration($name, array $definition)
{
$name = $this->conn->formatter->getIndexName($name);
$type = '';
if (isset($definition['type'])) {
switch (strtolower($definition['type'])) {
case 'fulltext':
case 'unique':
$type = strtoupper($definition['type']) . ' ';
break;
default:
throw new Doctrine_Export_Exception(
'Unknown type ' . $definition['type'] . ' for index ' . $name
);
}
}
if ( ! isset($definition['fields'])) {
throw new Doctrine_Export_Exception('No columns given for index ' . $name);
}
if ( ! is_array($definition['fields'])) {
$definition['fields'] = array($definition['fields']);
}
$query = $type . 'INDEX ' . $this->conn->quoteIdentifier($name);
$query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
return $query;
}
/**
* getIndexFieldDeclarationList
* Obtain DBMS specific SQL code portion needed to set an index
* declaration to be used in statements like CREATE TABLE.
*
* @return string
*/
public function getIndexFieldDeclarationList(array $fields)
{
$declFields = array();
foreach ($fields as $fieldName => $field) {
$fieldString = $this->conn->quoteIdentifier($fieldName);
if (is_array($field)) {
if (isset($field['length'])) {
$fieldString .= '(' . $field['length'] . ')';
}
if (isset($field['sorting'])) {
$sort = strtoupper($field['sorting']);
switch ($sort) {
case 'ASC':
case 'DESC':
$fieldString .= ' ' . $sort;
break;
default:
throw new Doctrine_Export_Exception('Unknown index sorting option given.');
}
}
} else {
$fieldString = $this->conn->quoteIdentifier($field);
}
$declFields[] = $fieldString;
}
return implode(', ', $declFields);
}
/**
* getAdvancedForeignKeyOptions
* Return the FOREIGN KEY query section dealing with non-standard options
* as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
*
* @param array $definition
* @return string
*/
public function getAdvancedForeignKeyOptions(array $definition)
{
$query = '';
if ( ! empty($definition['match'])) {
$query .= ' MATCH ' . $definition['match'];
}
if ( ! empty($definition['onUpdate'])) {
$query .= ' ON UPDATE ' . $this->getForeignKeyReferentialAction($definition['onUpdate']);
}
if ( ! empty($definition['onDelete'])) {
$query .= ' ON DELETE ' . $this->getForeignKeyReferentialAction($definition['onDelete']);
}
return $query;
}
/**
* drop existing index
*
* @param string $table name of table that should be used in method
* @param string $name name of the index to be dropped
* @return void
*/
public function dropIndexSql($table, $name)
{
$table = $this->conn->quoteIdentifier($table, true);
$name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name), true);
return 'DROP INDEX ' . $name . ' ON ' . $table;
}
/**
* dropTable
*
* @param string $table name of table that should be dropped from the database
* @throws PDOException
* @return void
*/
public function dropTableSql($table)
{
$table = $this->conn->quoteIdentifier($table, true);
return 'DROP TABLE ' . $table;
}
/**
* drop existing foreign key
*
* @param string $table name of table that should be used in method
* @param string $name name of the foreign key to be dropped
* @return void
*/
public function dropForeignKey($table, $name)
{
$table = $this->conn->quoteIdentifier($table);
$name = $this->conn->quoteIdentifier($name);
return $this->conn->exec('ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $name);
}
}
|
{
"content_hash": "4356fa72798cddac4d6b633972ebcb2a",
"timestamp": "",
"source": "github",
"line_count": 760,
"max_line_length": 118,
"avg_line_length": 41.03947368421053,
"alnum_prop": 0.446457197819814,
"repo_name": "doubleukay/speedjournal",
"id": "9182578e9eefc2cf62593064d45c2a7b01f49d66",
"size": "32215",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "lib/symfony/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Export/Mysql.php",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
}
|
project-pal.vim
===============
IMPORTANT: This project is still in an Alpha stage, and is likely to undergo significant API changes.
# Overview
Project-Pal.vim is a *lightweight* project management system for the Vim editor. Heavy-weigth IDEs like Eclipse or Visual Studio rely on verbose files to manage settings such as code paths and compiler options. While project settings can be useful, there are several major headaches that can arise when dealing with these files. Specifically, it can be challenging to share project files acrooss different computers. In the worst case, if the file is lost, or becomes corrupted (say from a merge conflict) you may not even be able to open your project anymore.
Vim has no innate concept of projects, so the purpose of Project-Pal.vim is simply to run a custom script when a particular project loads. A project definition is simply a folder with a .vim file that is run when the project is loaded. Beyond that, other "meta" information about the project may be included as you see fit (e.g.: tags,
In the spirit of Vim, Project-Pal.vim does not force you into into a paricular workflow. It's goal is to give you the basic tools so you can set up your projects however you want them.
# Features
Project-Pal.vim currently
* Initializes a project by changing the current directory and running other customs commands in a settings.vim file
* Builds a project by running a custom build command
* Generates tags for a project
These tasks are performed asynchronously, and the status bar is updated when they complete.
# Setup
I use [Vundle](https://github.com/gmarik/Vundle.vim) to manage my VIM plugins. Put this line in your .vimrc:
````
Bundle 'adampasz/project-pal.vim'
````
Project.Pal.vim also has a dependency on the indispensible [AsyncCommand](https://github.com/vim-scripts/AsyncCommand) plugin.
````
Bundle 'AsyncCommand'
````
Start VIM, and then run:
````
BundleInstall
````
In your .vimrc, you should define a global variable that points to your "project settings" folder. e.g.:
````
let g:proj='~/.vim/proj/'
````
For now, you need to manually create a sub-folder for each project, and provide a settings.vim file. e.g.:
````
~/.vim/proj/myProject1/settings.vim
~/.vim/proj/myProject2/settings.vim
etc.
````
The settings.vim file should define the project root. You may also want to specify a command to build the project.
````
let g:proot=fnameescape('/Users/adampasz/path/to/my/project/')
let g:buildProjectCommand = 'run_build.sh'
````
If you want to use tags, include an array of relative paths in settings.vim, as follows:
````
let g:ptags = [
\ 'path/to/js/src/',
\ 'path/to/coffeescript/src/',
\ 'path/to/some/other/code/'
\]
````
# Usage
:InitProject - Enter the name of project (i.e. the name of the proejct sub-folder) to run the settings.vim script.
:GenerateTags - Runs ctags on paths specified in g:ptags. Note, this replaces all previous tags for your Vim session.
:call BuildProject(...) - Calls your custom build command, with optional arguments
|
{
"content_hash": "565665aa5ce644b5d3885141b806fcc3",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 561,
"avg_line_length": 46.66153846153846,
"alnum_prop": 0.7523903725684141,
"repo_name": "adampasz/project-pal.vim",
"id": "4e379639a66eb0c2c2d4183d9ae50e621c78955c",
"size": "3033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "VimL",
"bytes": "3049"
}
],
"symlink_target": ""
}
|
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.AssetModels;
using TTC2017.SmartGrids.CIM.IEC61968.Assets;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.WiresExt;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssetModels;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfTypeAsset;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;
namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets
{
[TypeConverterAttribute(typeof(MediumKindConverter))]
[ModelRepresentationClassAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/InfAssets/MediumK" +
"ind")]
public enum MediumKind
{
Liquid = 0,
Gas = 1,
Solid = 2,
}
}
|
{
"content_hash": "e7d0fc75dfb88343bea2050d497f1d64",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 124,
"avg_line_length": 32,
"alnum_prop": 0.7904411764705882,
"repo_name": "georghinkel/ttc2017smartGrids",
"id": "39be87420318bc6f6139e0292019c068b4a8f1f1",
"size": "2067",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "generator/Schema/IEC61970/Informative/InfAssets/MediumKind.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "79261108"
},
{
"name": "Java",
"bytes": "38407170"
},
{
"name": "Python",
"bytes": "6055"
},
{
"name": "R",
"bytes": "15405"
},
{
"name": "Rebol",
"bytes": "287"
}
],
"symlink_target": ""
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.4.4.22-8-b-iii-1-10
description: >
Array.prototype.reduceRight - element to be retrieved is own
accessor property on an Array
---*/
var testResult = false;
function callbackfn(prevVal, curVal, idx, obj) {
if (idx === 2) {
testResult = (curVal === 2);
}
}
var arr = [0, 1, , 3];
Object.defineProperty(arr, "2", {
get: function () {
return 2;
},
configurable: true
});
arr.reduceRight(callbackfn);
assert(testResult, 'testResult !== true');
|
{
"content_hash": "320652eaeee77c3b144860c334c3e4a0",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 70,
"avg_line_length": 25.93103448275862,
"alnum_prop": 0.5398936170212766,
"repo_name": "baslr/ArangoDB",
"id": "5a7966fb0043cfad23c152c06b01b70d14c4d8b6",
"size": "752",
"binary": false,
"copies": "3",
"ref": "refs/heads/3.1-silent",
"path": "3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-10.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "391227"
},
{
"name": "Awk",
"bytes": "4272"
},
{
"name": "Batchfile",
"bytes": "62892"
},
{
"name": "C",
"bytes": "7932707"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "284363933"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "681903"
},
{
"name": "CSS",
"bytes": "1036656"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "259402"
},
{
"name": "Emacs Lisp",
"bytes": "14637"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "2318016"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "67878359"
},
{
"name": "LLVM",
"bytes": "24129"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "600550"
},
{
"name": "Makefile",
"bytes": "509612"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "19321"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "98503"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "720157"
},
{
"name": "Perl 6",
"bytes": "9918"
},
{
"name": "Python",
"bytes": "5859911"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "1010686"
},
{
"name": "Ruby",
"bytes": "922159"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "511077"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "Visual Basic",
"bytes": "11568"
},
{
"name": "XSLT",
"bytes": "551977"
},
{
"name": "Yacc",
"bytes": "53005"
}
],
"symlink_target": ""
}
|
package com.QuickStartFrame.management.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.log4j.Logger;
public class DateUtil {
private static final Logger logger = Logger.getLogger(DateUtil.class);
private static final String[] WEEKDAYS_CN = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
private static final String[] WEEKDAYS_EN = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"};
public static String getENWeekDay() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return WEEKDAYS_EN[w];
}
public static String getCNWeekDay() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return WEEKDAYS_CN[w];
}
public static String getCurrentHour() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
}
public static String getBeforeOneHour() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return String.valueOf(cal.get(Calendar.HOUR_OF_DAY) == 0
? 23 : cal.get(Calendar.HOUR_OF_DAY) - 1);
}
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String format = sdf.format(date);
return format;
}
public static int computeElapsetime(String departureTime, String arrivalTime) {
int elapsetime = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date departureDate = sdf.parse(departureTime);
Date arrivalDate = sdf.parse(arrivalTime);
elapsetime = (int)(arrivalDate.getTime() - departureDate.getTime()) / (1000 * 60);
} catch (Exception e) {
logger.warn("时间转换异常", e);
}
return elapsetime;
}
public static void main(String[] args) {
String departureTime = "2016-03-27 12:00:00:00";
String arrivalTime = "2016-03-27 15:10:00:12";
System.out.println(computeElapsetime(departureTime, arrivalTime));
}
}
|
{
"content_hash": "854fd882ca293770d52d7f95e24bd375",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 124,
"avg_line_length": 28.050632911392405,
"alnum_prop": 0.6615523465703971,
"repo_name": "fyg0424/quickStartFrame",
"id": "f86b4b8cc94b6eedcda5f1a4e9d1fa431b242d36",
"size": "2270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/QuickStartFrame/management/util/DateUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "73917"
},
{
"name": "Java",
"bytes": "48142"
},
{
"name": "JavaScript",
"bytes": "1010839"
}
],
"symlink_target": ""
}
|
"""
Global Configuration for Application
"""
import os
import json
import logging
# Get configuration from environment
DATABASE_URI = os.getenv(
"DATABASE_URI",
"postgresql://postgres:postgres@localhost:5432/postgres"
)
# override if we are running in Cloud Foundry
if 'VCAP_SERVICES' in os.environ:
vcap = json.loads(os.environ['VCAP_SERVICES'])
DATABASE_URI = vcap['user-provided'][0]['credentials']['url']
# Configure SQLAlchemy
SQLALCHEMY_DATABASE_URI = DATABASE_URI
SQLALCHEMY_TRACK_MODIFICATIONS = False
# SQLALCHEMY_POOL_SIZE = 2
# Secret for session management
SECRET_KEY = os.getenv("SECRET_KEY", "sup3r-s3cr3t")
LOGGING_LEVEL = logging.INFO
|
{
"content_hash": "64a9500a2769c6e7c06cec459f9e156c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 65,
"avg_line_length": 25.807692307692307,
"alnum_prop": 0.7421758569299552,
"repo_name": "nyu-devops/lab-flask-tdd",
"id": "cc843a4127c4de2d9daeed9ca419102204c18e1f",
"size": "671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "service/config.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1013"
},
{
"name": "Makefile",
"bytes": "961"
},
{
"name": "Procfile",
"bytes": "64"
},
{
"name": "Python",
"bytes": "48147"
},
{
"name": "Shell",
"bytes": "20"
}
],
"symlink_target": ""
}
|
if __name__ == '__main__':
raise NotImplementedError("""
CoNLL 2003 Shared Task on NER is not implemented yet.
See:
http://www.cnts.ua.ac.be/conll2003/ner/
""")
|
{
"content_hash": "a0537e4b77a97a1573d54ead62b576ce",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 61,
"avg_line_length": 28.857142857142858,
"alnum_prop": 0.5396039603960396,
"repo_name": "JonathanRaiman/Dali",
"id": "5f0199c11f5f2ceedab350880de6e447aee6092a",
"size": "202",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "data/CoNLL_NER/generate.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1792"
},
{
"name": "C++",
"bytes": "914686"
},
{
"name": "CMake",
"bytes": "32660"
},
{
"name": "Cuda",
"bytes": "1482"
},
{
"name": "Protocol Buffer",
"bytes": "255"
},
{
"name": "Python",
"bytes": "96350"
},
{
"name": "Shell",
"bytes": "22692"
}
],
"symlink_target": ""
}
|
jQuery(document).ready(function() {
/*
Fullscreen background
*/
$.backstretch("/img/backgrounds/1.jpg");
/*
Form validation
*/
$('.login-form input[type="text"], .login-form input[type="password"], .login-form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('.login-form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], textarea').each(function(){
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
|
{
"content_hash": "a0a2ff5d61f35f35c35ed66a21ce94a8",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 122,
"avg_line_length": 22.677419354838708,
"alnum_prop": 0.5035561877667141,
"repo_name": "andremoreei/lafrench",
"id": "fc189514f3be64b7f51a31ae4fe39582a7e16675",
"size": "703",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/js/scripts.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "68041"
},
{
"name": "JavaScript",
"bytes": "165602"
},
{
"name": "PHP",
"bytes": "252730"
}
],
"symlink_target": ""
}
|
using GameOfLife.Abstraction;
using GameOfLife.Rules;
using GameOfLife.WPF.MVVM.Commands;
using GameOfLife.WPF.MVVM.Models;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Windows.Input;
namespace GameOfLife.WPF.MVVM.ViewModels
{
public class BoardViewModel : ViewModelBase
{
public const int Rows = 20;
public const int Columns = 20;
public IBoard Board { get; }
public IList<IRule> Rules { get; }
public ICommand ClearCommand { get; set; }
public ICommand StartCommand { get; set; }
public ICommand StopCommand { get; set; }
public ICommand SetCellStateCommand { get; set; }
private bool isRunning;
public bool IsRunning
{
get
{
return this.isRunning;
}
set
{
if (this.isRunning != value)
{
this.isRunning = value;
this.NotifyPropertyChanged(nameof(IsRunning));
this.NotifyPropertyChanged(nameof(IsStopped));
}
}
}
public bool IsStopped { get { return !this.IsRunning; } }
public int Ticks { get; set; } = 1000;
private BackgroundWorker backgroundWorker;
public BoardViewModel()
{
this.Board = new PeriodicBoundaryConditionsBoardModel(Rows, Columns);
this.Rules = new List<IRule>();
this.Rules.Add(new Underpopulation());
this.Rules.Add(new Overpopulation());
this.Rules.Add(new Reproduction());
this.backgroundWorker = new BackgroundWorker();
this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorker.DoWork += BackgroundWorkerDoWork;
this.ClearCommand = new DelegateCommand(this.Clear);
this.StartCommand = new DelegateCommand(this.Start);
this.StopCommand = new DelegateCommand(this.Stop);
this.SetCellStateCommand = new DelegateCommand(this.SetCellState);
}
private void NextGeneration()
{
while (true)
{
Thread.Sleep(this.Ticks);
if (this.IsRunning)
{
this.Board.NextGeneration(this.Rules);
}
else
{
break;
}
}
}
private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
this.NextGeneration();
}
public void Start(object param)
{
if (this.IsRunning)
{
return;
}
this.IsRunning = true;
this.backgroundWorker.RunWorkerAsync();
}
public void Clear(object param)
{
this.IsRunning = false;
foreach (var cell in this.Board.Cells.Values)
{
cell.IsAlive = false;
}
}
public void Stop(object param)
{
this.IsRunning = false;
this.backgroundWorker.CancelAsync();
}
public void SetCellState(object param)
{
if (this.IsRunning)
{
return;
}
var cell = (CellModel)param;
cell.IsAlive = !cell.IsAlive;
}
}
}
|
{
"content_hash": "40316b6e1fc67a7c9787f3ad84a8e832",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 81,
"avg_line_length": 26.270676691729324,
"alnum_prop": 0.5274756725815684,
"repo_name": "hieudole/GameOfLife",
"id": "afe4cda400b1d9790671cfbd077716095ac8fffe",
"size": "3496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GameOfLife.WPF.MVVM/ViewModels/BoardViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "36466"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Nimbus.Configuration.PoorMansIocContainer;
using Nimbus.Configuration.Settings;
using Nimbus.Infrastructure.Filtering;
using Nimbus.InfrastructureContracts;
using Nimbus.InfrastructureContracts.Handlers;
using Nimbus.InfrastructureContracts.Routing;
namespace Nimbus.Infrastructure.Events
{
internal class MulticastEventMessagePumpsFactory : MessagePumpFactory
{
private readonly ApplicationNameSetting _applicationName;
private readonly InstanceNameSetting _instanceName;
private readonly ILogger _logger;
private readonly IMessageDispatcherFactory _messageDispatcherFactory;
private readonly IHandlerMapper _handlerMapper;
private readonly ITypeProvider _typeProvider;
private readonly PoorMansIoC _container;
private readonly INimbusTransport _transport;
private readonly IRouter _router;
private readonly IFilterConditionProvider _filterConditionProvider;
private readonly IPathFactory _pathFactory;
internal MulticastEventMessagePumpsFactory(ApplicationNameSetting applicationName,
InstanceNameSetting instanceName,
IFilterConditionProvider filterConditionProvider,
IHandlerMapper handlerMapper,
ILogger logger,
IMessageDispatcherFactory messageDispatcherFactory,
INimbusTransport transport,
IPathFactory pathFactory,
IRouter router,
ITypeProvider typeProvider,
PoorMansIoC container)
{
_applicationName = applicationName;
_instanceName = instanceName;
_handlerMapper = handlerMapper;
_logger = logger;
_messageDispatcherFactory = messageDispatcherFactory;
_transport = transport;
_router = router;
_typeProvider = typeProvider;
_container = container;
_pathFactory = pathFactory;
_filterConditionProvider = filterConditionProvider;
}
public IEnumerable<IMessagePump> CreateAll()
{
var openGenericHandlerType = typeof(IHandleMulticastEvent<>);
var handlerTypes = _typeProvider.MulticastEventHandlerTypes.ToArray();
// Events are routed to Topics and we'll create a subscription per instance of the logical endpoint to enable multicast behaviour
var allMessageTypesHandledByThisEndpoint = _handlerMapper.GetMessageTypesHandledBy(openGenericHandlerType, handlerTypes);
var bindings = allMessageTypesHandledByThisEndpoint
.Select(m => new {MessageType = m, TopicPath = _router.Route(m, QueueOrTopic.Topic, _pathFactory)})
.GroupBy(b => b.TopicPath)
.Select(g => new
{
TopicPath = g.Key,
MessageTypes = g.Select(x => x.MessageType),
HandlerTypes = g.SelectMany(x => _handlerMapper.GetHandlerTypesFor(openGenericHandlerType, x.MessageType))
})
.ToArray();
if (bindings.Any(b => b.MessageTypes.Count() > 1))
throw new NotSupportedException("Routing multiple message types through a single Topic is not supported.");
foreach (var binding in bindings)
{
foreach (var handlerType in binding.HandlerTypes)
{
var messageType = binding.MessageTypes.Single();
var subscriptionName = _pathFactory.SubscriptionNameFor(_applicationName, _instanceName, handlerType);
var filterCondition = _filterConditionProvider.GetFilterConditionFor(handlerType);
_logger.Debug("Creating message pump for multicast event subscription '{0}/{1}' handling {2} with filter {3}",
binding.TopicPath,
subscriptionName,
messageType,
filterCondition);
var messageReceiver = _transport.GetTopicReceiver(binding.TopicPath, subscriptionName, filterCondition);
var handlerMap = new Dictionary<Type, Type[]> {{messageType, new[] {handlerType}}};
var messageDispatcher = _messageDispatcherFactory.Create(openGenericHandlerType, handlerMap);
var pump = _container.ResolveWithOverrides<MessagePump>(messageReceiver, messageDispatcher);
GarbageMan.Add(pump);
yield return pump;
}
}
}
}
}
|
{
"content_hash": "32ab05eb6b574c71c067cbe21b8a0dd2",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 141,
"avg_line_length": 52.5,
"alnum_prop": 0.5852283770651118,
"repo_name": "NimbusAPI/Nimbus",
"id": "6a9f0e58d4a7f5b008d600da419e9eb24d4a84c6",
"size": "5147",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Nimbus/Infrastructure/Events/MulticastEventMessagePumpsFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "891511"
},
{
"name": "Dockerfile",
"bytes": "868"
},
{
"name": "PowerShell",
"bytes": "6089"
},
{
"name": "Shell",
"bytes": "2082"
}
],
"symlink_target": ""
}
|
require 'rubygems'
require 'bundler/setup'
Bundler.require(:test, :development)
require 'casmall'
module CaSmall::Test
RESULTS = File.dirname(__FILE__) + '/../test/results'
end
# Open the logger.
Jinx::Log.instance.open(CaSmall::Test::RESULTS + '/log/casmall.log', :debug => true)
Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |f| require f }
|
{
"content_hash": "fdd881e8a91e82cb599d2dd6fbd19f19",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 84,
"avg_line_length": 25.714285714285715,
"alnum_prop": 0.6722222222222223,
"repo_name": "caruby/small",
"id": "6f7b0359c5c94e435319e057c95f1d98c759e354",
"size": "360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "14496"
}
],
"symlink_target": ""
}
|
'use strict'
var normalize = require('./normalize')
var DefinedInfo = require('./lib/util/defined-info')
var Info = require('./lib/util/info')
var data = 'data'
module.exports = find
var valid = /^data[-a-z0-9.:_]+$/i
var dash = /-[a-z]/g
var cap = /[A-Z]/g
function find(schema, value) {
var normal = normalize(value)
var prop = value
var Type = Info
if (normal in schema.normal) {
return schema.property[schema.normal[normal]]
}
if (normal.length > 4 && normal.slice(0, 4) === data && valid.test(value)) {
// Attribute or property.
if (value.charAt(4) === '-') {
prop = datasetToProperty(value)
} else {
value = datasetToAttribute(value)
}
Type = DefinedInfo
}
return new Type(prop, value)
}
function datasetToProperty(attribute) {
var value = attribute.slice(5).replace(dash, camelcase)
return data + value.charAt(0).toUpperCase() + value.slice(1)
}
function datasetToAttribute(property) {
var value = property.slice(4)
if (dash.test(value)) {
return property
}
value = value.replace(cap, kebab)
if (value.charAt(0) !== '-') {
value = '-' + value
}
return data + value
}
function kebab($0) {
return '-' + $0.toLowerCase()
}
function camelcase($0) {
return $0.charAt(1).toUpperCase()
}
|
{
"content_hash": "54022d97c84f563a89abba95abd668ff",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 78,
"avg_line_length": 19.8,
"alnum_prop": 0.6317016317016317,
"repo_name": "jpoeng/jpoeng.github.io",
"id": "ae600a4df14993f6b3d8e3e94232d81a973c085b",
"size": "1287",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "node_modules/property-information/find.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5765"
},
{
"name": "HTML",
"bytes": "53947"
},
{
"name": "JavaScript",
"bytes": "1885"
},
{
"name": "PHP",
"bytes": "9773"
}
],
"symlink_target": ""
}
|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "3b63530fe69c00ae075dbd148068e6de",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "525f7f4e1d62fade119d649f3883ca27290e34e5",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Opuntia/Opuntia soederstromiana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
}
|
/* global app:true */
'use strict';
app.controller('TvShowViewCtrl', ['$scope', '$routeParams', 'TvShow', function($scope, $routeParams, TvShow) {
TvShow.find($routeParams.tvshowId).then(function(data) {
$scope.tvshow = data;
});
}]);
|
{
"content_hash": "505b88709c0492a3d93339f9b5bc5e32",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 110,
"avg_line_length": 27.22222222222222,
"alnum_prop": 0.6571428571428571,
"repo_name": "gabriel-detassigny/kodi-angular",
"id": "1cd0f8752119c8b5d41c7d21151988da402543b6",
"size": "245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/scripts/controllers/tvshows/tvshowview.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "1698"
},
{
"name": "HTML",
"bytes": "22493"
},
{
"name": "JavaScript",
"bytes": "45776"
}
],
"symlink_target": ""
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem 01. Decimal to binary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem 01. Decimal to binary")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a0c6a8c4-b03f-47fe-9149-ce261addcee5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
{
"content_hash": "ffa28bdb3f7ed8dfdcb258bf0b5b7455",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 40.75,
"alnum_prop": 0.7259713701431493,
"repo_name": "MarinMarinov/C-Sharp-Part-2",
"id": "e9c5aeb6b6121eb985af8a098ae74179b6937ca3",
"size": "1470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Homework 04-Numeral Systems/Problem 01. Decimal to binary/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "269821"
}
],
"symlink_target": ""
}
|
/*
* Modified by Sergio Martinez. Copyright 2011 Vodafone Group Services Ltd.
*
*/
package com.phonegap.calendar.android.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
* @author Sergio Martinez Rodriguez
*/
public class Link {
/**
* href string corresponding to href tag in Link
*/
@Key("@href")
public String href;
/**
* type string corresponding to type tag in Link
*/
@Key("@type")
public String type;
/**
* rel string corresponding to rel tag in Link
*/
@Key("@rel")
public String rel;
/**
* Finds the href url for the given links that matches given rel string
* @param links List of Links objects
* @param rel string with rel type
* @return href string
*/
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
|
{
"content_hash": "daf3d9ce48c59823ca3a053b6e77db9c",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 76,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6200396825396826,
"repo_name": "dcheng/PhoneGap-Calendar-Plugin",
"id": "35f79532b7b6deb885f2e2b0d92e2268e06ef56a",
"size": "1596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "phoneGapCalendarAPI/CalendarLib/src/main/java/com/phonegap/calendar/android/model/Link.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "180652"
},
{
"name": "JavaScript",
"bytes": "139887"
}
],
"symlink_target": ""
}
|
<?php
namespace Bugsnag\Silex\Tests\Request;
use Bugsnag\Client;
use Bugsnag\Report;
use Bugsnag\Silex\Silex1ServiceProvider;
use Bugsnag\Silex\Silex2ServiceProvider;
use Exception;
use GrahamCampbell\TestBenchCore\MockeryTrait;
use Mockery;
use Pimple\ServiceProviderInterface;
use PHPUnit_Framework_TestCase as TestCase;
use Silex\Application;
class AutoNotifyTest extends TestCase
{
use MockeryTrait;
public function testAutoNotify()
{
// Create mocks
$report = Mockery::namedMock(Report::class, RequestStub::class);
$client = Mockery::mock(Client::class);
$app = Mockery::mock(Application::class);
// Create test objects
$exception = new Exception("Test");
$app->shouldReceive('offsetSet')->with(Mockery::any(), Mockery::any())->andReturnUsing(
function($key, $value) use ($app, $exception) {
if ($key == 'bugsnag.notifier') {
$notifyFunc = call_user_func($value, $app);
call_user_func($notifyFunc, $exception);
}
}
);
$app->shouldReceive('share');
$app->shouldReceive('before');
$app->shouldReceive('offsetGet')->andReturnUsing(
function($key) use ($client) {
if ($key == 'bugsnag') {
return $client;
}
}
);
$report->shouldReceive('fromPHPThrowable')
->with('config', $exception)
->once()
->andReturn($report);
$report->shouldReceive('setUnhandled')->once()->with(true);
$report->shouldReceive('setSeverityReason')->once()->with([
'type' => 'unhandledExceptionMiddleware',
'attributes' => ['framework' => 'Silex'],
]);
$client->shouldReceive('getConfig')->once()->andReturn('config');
$client->shouldReceive('notify')->once()->with($report, Mockery::any());
// Initiate test
$serviceProvider = self::getSilexServiceProvider();
$serviceProvider->register($app);
}
private static function getSilexServiceProvider()
{
if (interface_exists(ServiceProviderInterface::class)) {
return new Silex2ServiceProvider();
}
return new Silex1ServiceProvider();
}
}
class RequestStub
{
const MIDDLEWARE_HANDLER = "middleware_handler";
}
|
{
"content_hash": "fcb98edcd04b2afa3532f72115201a08",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 95,
"avg_line_length": 30.833333333333332,
"alnum_prop": 0.5937629937629938,
"repo_name": "bugsnag/bugsnag-silex",
"id": "27f7dcaf3a026eb2b09882b960f4f4258984afaf",
"size": "2405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/AutoNotifyTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2880"
},
{
"name": "Makefile",
"bytes": "673"
},
{
"name": "PHP",
"bytes": "24785"
}
],
"symlink_target": ""
}
|
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int griffy_height;
cin >> griffy_height;
unsigned int plushies;
cin >> plushies;
unsigned int plushies_in_the_way {0};
for (unsigned int i {0}; i < plushies; ++i)
{
unsigned int height;
cin >> height;
if (height >= griffy_height)
{
++plushies_in_the_way;
}
}
cout << plushies_in_the_way << '\n';
return 0;
}
|
{
"content_hash": "86fb8b1d52aa009b548bbaa4200eb753",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 47,
"avg_line_length": 16.083333333333332,
"alnum_prop": 0.5526770293609672,
"repo_name": "M4573R/competitive-programming-archive",
"id": "9026ebe55cca1287481a40623db51be55b8f8d08",
"size": "600",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dmoj/gfsso/contest-1/flying_plushies.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1079327"
},
{
"name": "Python",
"bytes": "21"
}
],
"symlink_target": ""
}
|
module Segments.Common.Env where
import Data.Maybe (maybeToList)
import System.Environment (lookupEnv)
import System.Posix.User (getEffectiveUserName, getEffectiveUserID)
import Segments.Base
-- powerline.segments.common.env.environment
envSegment :: SegmentHandler
envSegment args _ = do
let var = argLookup args "variable" ""
let hlGroup = HighlightGroup "background" Nothing
value <- lookupEnv var
return $ maybeToList (Segment hlGroup <$> value)
-- powerline.segments.common.env.user
userSegment :: SegmentHandler
userSegment args _ = do
let hideUser = argLookup args "hide_user" ""
let hideDomain = argLookup args "hide_domain" False
user <- getEffectiveUserName
isRoot <- (== 0) <$> getEffectiveUserID
let hlGroup = flip HighlightGroup Nothing $
if isRoot
then "superuser"
else "user"
let dropDomain = if hideDomain
then takeWhile (/= '@')
else id
let user' = if user == hideUser
then Nothing
else Just $ dropDomain user
return $ Segment hlGroup <$> maybeToList user'
|
{
"content_hash": "8d20ec65f2bb353469043813f3527053",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 67,
"avg_line_length": 28.75609756097561,
"alnum_prop": 0.6378286683630195,
"repo_name": "rdnetto/powerline-hs",
"id": "271e9de8a9f40f35aa5a55a614ffe69931c450e0",
"size": "1179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Segments/Common/Env.hs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Haskell",
"bytes": "80952"
},
{
"name": "Shell",
"bytes": "382"
}
],
"symlink_target": ""
}
|
import pdb;pdb.set_trace()
def sqlQuery_oldimage_newpo_duplimerge(oldpo, newpo):
import sqlalchemy,sys
orcl_engine = sqlalchemy.create_engine('oracle+cx_oracle://prod_team_ro:9thfl00r@borac101-vip.l3.bluefly.com:1521/bfyprd11')
connection = orcl_engine.connect()
query_image_duplimerge = "WITH data AS ( SELECT POMGR.PO_LINE.PO_HDR_ID AS ponumber, POMGR.PRODUCT_COLOR.ID AS colorstyle, POMGR.PRODUCT_COLOR.VENDOR_STYLE AS vendor_style, sum( case when POMGR.PRODUCT_COLOR.IMAGE_READY_DT is not null then 1 else null end ) is_ready FROM POMGR.PO_LINE JOIN POMGR.PRODUCT_COLOR ON POMGR.PRODUCT_COLOR.ID = POMGR.PO_LINE.PRODUCT_COLOR_ID WHERE POMGR.PO_LINE.PO_HDR_ID IN ('{0}', '{1}') GROUP BY POMGR.PO_LINE.PO_HDR_ID, POMGR.PRODUCT_COLOR.ID, POMGR.PRODUCT_COLOR.VENDOR_STYLE ORDER BY 3, 4 asc nulls last, 2 DESC ) SELECT COUNT(DISTINCT data.colorstyle), data.vendor_style, MIN(data.colorstyle) as oldstyle, MAX(data.colorstyle) as newstyle, data.is_ready FROM data GROUP BY data.vendor_style, data.is_ready HAVING COUNT(data.vendor_style) = 2 AND MIN(data.colorstyle) <> MAX(data.colorstyle) order by data.is_ready nulls last".format(oldpo, newpo)
result = connection.execute(query_image_duplimerge)
merge_styles = []
total_count_rem = result.rowcount
total_count_incr = 0
for row in result:
styles = {}
styles['oldstyle'] = str(row['oldstyle'])
styles['newstyle'] = str(row['newstyle'])
total_count_incr += 1
total_count_rem -= 1
print "Styles Total: {}\vRemaining: {}".format(total_count_incr, total_count_rem)
merge_styles.append(styles)
connection.close()
return merge_styles
def url_download_file(url,dest_filepath):
import urllib
try:
resp = urllib.urlretrieve(url, dest_filepath)
if resp:
print "Retrieved: " + url + " ---> " + dest_filepath
return dest_filepath
else:
return
except IOError:
print 'IOERROR 30'
# def url_download_file(url,dest_filepath):
# import requests
# resp = requests.get(url, dest_filepath)
# if resp:
# print "Retrieved: " + url + " ---> " + dest_filepath
# with open(dest_filepath, 'wb+') as f:
# f.write(resp.content)
# return dest_filepath
# else:
# return
def main():
#### Run ###
import sys, urllib
from os import chdir,curdir,path
args = sys.argv[1:]
print 'Moving images from PO: {} to PO --> {}'.format(*args)
try:
if len(args) == 2:
merge_styles = sqlQuery_oldimage_newpo_duplimerge(*args)
else:
print "You neew to provide both the original po number and the po number to move images to.\nPo numbers are 6 digits each separated by a space."
pass
except IndexError:
print "Enter at least PO Number as 1st Arg or Nothing will Happen"
for item in merge_styles:
netsrv101_url = 'ftp://imagedrop:imagedrop0@netsrv101.l3.bluefly.com//mnt/images/images/'
old_colorstyle = item['oldstyle']
new_colorstyle = item['newstyle']
ext_PNG = '.png'
ext_JPG = '.jpg'
netsrv101_url_file = path.join(netsrv101_url, old_colorstyle[:4], old_colorstyle + ext_PNG)
renamed_from_newpo_toload = path.join(path.abspath(path.expanduser('~')), 'Pictures', new_colorstyle + ext_PNG)
url_download_file(netsrv101_url_file, renamed_from_newpo_toload)
alt = 0
for x in range(1,6):
alt = x
ext_ALT = '_alt0{0}{1}'.format(str(alt),ext_PNG)
colorstyleoldalt = old_colorstyle + ext_ALT
netsrv101_url_filealt = path.join(netsrv101_url, old_colorstyle[:4], colorstyleoldalt)
colorstylenewalt = new_colorstyle + ext_ALT
renamed_from_newpo_toloadalt = path.join(path.abspath(path.expanduser('~')), 'Pictures', colorstylenewalt)
if url_download_file(netsrv101_url_filealt, renamed_from_newpo_toloadalt):
url_download_file(netsrv101_url_filealt, renamed_from_newpo_toloadalt)
if __name__ == '__main__':
main()
|
{
"content_hash": "f851c64b26c4654bdb7aa10561925af7",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 892,
"avg_line_length": 47.666666666666664,
"alnum_prop": 0.6445623342175066,
"repo_name": "relic7/prodimages",
"id": "730283f5dd11cfdb0a36878713e9ea8c7e788898",
"size": "4170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/download_bfly_rename_imgs_FromPOtoNewPO.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16783"
},
{
"name": "HTML",
"bytes": "88323"
},
{
"name": "JavaScript",
"bytes": "158855"
},
{
"name": "PHP",
"bytes": "70412"
},
{
"name": "PLSQL",
"bytes": "72767"
},
{
"name": "Perl",
"bytes": "7143"
},
{
"name": "Python",
"bytes": "4922301"
},
{
"name": "Shell",
"bytes": "423422"
},
{
"name": "Smarty",
"bytes": "571"
},
{
"name": "VimL",
"bytes": "6045"
}
],
"symlink_target": ""
}
|
A simple converter from HTML to Markdown in Java.
I created this project for importing notes on Capsa Notes.
Currently it hasn't any options. I plan to add different markdown styles (Headers using # instead of underline =, for example).
## How to use it:
It's pretty simple, first add jSoup to the classpath. Then:
String markdownText = HTML2Md.convert(html, baseURL);
Where html is a String containing the html code you want to convert, and baseURL is the url you will use as a reference for converting relative links.
You can use directly an URL too, like this:
URL url = new URL("http://www.example.com/");
HTML2Md.convert(url, 30000);
The 30000 is the timeout for requesting the page in milliseconds.
Enjoy!
# RoadMap
* Add options for different markdown styles
* Jekyll & Hexo markdown styles has already been added, to use them, simply invoke
HTML2Md.htmlToJekyllMd(htmlPath, mdPath, charset);
HTML2Md.htmlToHexoMd(htmlPath, mdPath, charset);
* Some refactoring, currently the code is quite ugly
|
{
"content_hash": "3c9e0856882ef68bb4ccd57b97fefa1c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 150,
"avg_line_length": 33.38709677419355,
"alnum_prop": 0.7545893719806763,
"repo_name": "pnikosis/jHTML2Md",
"id": "847343e787a3cffb38920f8e0b096144b9a5310c",
"size": "1046",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "53892"
},
{
"name": "Shell",
"bytes": "657"
}
],
"symlink_target": ""
}
|
.class Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;
.super Ljava/lang/Object;
.source "KeyguardUpdateMonitor.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x8
name = "BatteryStatus"
.end annotation
# instance fields
.field public final health:I
.field public final level:I
.field public final plugged:I
.field public final status:I
# direct methods
.method public constructor <init>(IIII)V
.locals 0
.parameter "status"
.parameter "level"
.parameter "plugged"
.parameter "health"
.prologue
.line 249
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 250
iput p1, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->status:I
.line 251
iput p2, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->level:I
.line 252
iput p3, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->plugged:I
.line 253
iput p4, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->health:I
.line 254
return-void
.end method
# virtual methods
.method public isBatteryLow()Z
.locals 2
.prologue
.line 281
iget v0, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->level:I
const/16 v1, 0x14
if-ge v0, v1, :cond_0
const/4 v0, 0x1
:goto_0
return v0
:cond_0
const/4 v0, 0x0
goto :goto_0
.end method
.method public isCharged()Z
.locals 2
.prologue
.line 273
iget v0, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->status:I
const/4 v1, 0x5
if-eq v0, v1, :cond_0
iget v0, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->level:I
const/16 v1, 0x64
if-lt v0, v1, :cond_1
:cond_0
const/4 v0, 0x1
:goto_0
return v0
:cond_1
const/4 v0, 0x0
goto :goto_0
.end method
.method isPluggedIn()Z
.locals 3
.prologue
const/4 v0, 0x1
.line 261
iget v1, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->plugged:I
if-eq v1, v0, :cond_0
iget v1, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->plugged:I
const/4 v2, 0x2
if-eq v1, v2, :cond_0
iget v1, p0, Lcom/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus;->plugged:I
const/4 v2, 0x4
if-ne v1, v2, :cond_1
:cond_0
:goto_0
return v0
:cond_1
const/4 v0, 0x0
goto :goto_0
.end method
|
{
"content_hash": "b5112bead48c686f2cd11ef9f0c74bd0",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 116,
"avg_line_length": 21.35251798561151,
"alnum_prop": 0.7048517520215634,
"repo_name": "baidurom/devices-base_cm",
"id": "28cb7b197a364dad8823413f489a76bdcdbbd3c3",
"size": "2968",
"binary": false,
"copies": "3",
"ref": "refs/heads/coron-4.2",
"path": "android.policy.jar.out/smali/com/android/internal/policy/impl/keyguard_obsolete/KeyguardUpdateMonitor$BatteryStatus.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12555"
}
],
"symlink_target": ""
}
|
________________________________________________________________________
This file is part of Logtalk <https://logtalk.org/>
Copyright 1998-2022 Paulo Moura <pmoura@logtalk.org>
SPDX-License-Identifier: Apache-2.0
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.
________________________________________________________________________
To load this example and for sample queries, please see the `SCRIPT.txt` file.
This example illustrates the use of assignable variables and parametric
objects as alternative implementation to dynamic object predicates for
storing (backtrackable) object state. For more information on assignable
variables please consult the URL:
http://www.kprolog.com/en/logical_assignment/
The objects in this example make use of the library category `assignvars`.
This category contains an adaptation of the pure logical subset implementation
of assignable variables by Nobukuni Kino, which can be found on the URL above.
|
{
"content_hash": "bc13b58569bcb9a5e5e49b9c1d95f39c",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 78,
"avg_line_length": 44.78125,
"alnum_prop": 0.7166782972784368,
"repo_name": "LogtalkDotOrg/logtalk3",
"id": "058ba4cd48c086471527c8c4a90016d169b41e85",
"size": "1433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/assign_parameters/NOTES.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1466"
},
{
"name": "CSS",
"bytes": "20149"
},
{
"name": "CodeQL",
"bytes": "1295"
},
{
"name": "Common Lisp",
"bytes": "258800"
},
{
"name": "Dockerfile",
"bytes": "1948"
},
{
"name": "Emacs Lisp",
"bytes": "11861"
},
{
"name": "HTML",
"bytes": "1958537"
},
{
"name": "Inno Setup",
"bytes": "50865"
},
{
"name": "JavaScript",
"bytes": "153065"
},
{
"name": "Logtalk",
"bytes": "4960912"
},
{
"name": "Lua",
"bytes": "23902"
},
{
"name": "Makefile",
"bytes": "604"
},
{
"name": "PDDL",
"bytes": "6555764"
},
{
"name": "PHP",
"bytes": "26584"
},
{
"name": "PLSQL",
"bytes": "362"
},
{
"name": "PowerShell",
"bytes": "296191"
},
{
"name": "Prolog",
"bytes": "10156468"
},
{
"name": "Python",
"bytes": "16672"
},
{
"name": "Ruby",
"bytes": "10762"
},
{
"name": "Shell",
"bytes": "360508"
},
{
"name": "Starlark",
"bytes": "913"
},
{
"name": "Tcl",
"bytes": "5409"
},
{
"name": "TeX",
"bytes": "12936"
},
{
"name": "Vim Script",
"bytes": "19406"
},
{
"name": "Vim Snippet",
"bytes": "1921"
},
{
"name": "XSLT",
"bytes": "148349"
},
{
"name": "YASnippet",
"bytes": "8069"
}
],
"symlink_target": ""
}
|
import java.util.Scanner;
import java.lang.Math;
public class Mathical{
public static void main(String[] args){
System.out.println("This is Mathical, where we explore Java's mathamatical operations");
Scanner sc = new Scanner(System.in);
//+1
System.out.println("Java can do addition using the '+' operator.");
System.out.println("For example, type a whole number and I'll add it by one.");
int num1 = sc.nextInt();//Don't forget to use nextInt for ints!
int sum = num1 + 1;
System.out.println(num1 + "+1 is equal to " + sum);
//Kelvins to Celcius
System.out.println("Java can also do subtraction using the '-' operator.");
System.out.println("In this example, type a temprature in Kelvin and I will convert it into Celcius.");
double kelvins = sc.nextDouble();
//A final prevents the variable from being changed once it has been declared
//They are declared using visibility, datatypeand variable name in capital as convension
final double TEMPCONVERSION = 273.15;
double celcius = kelvins - TEMPCONVERSION;
System.out.println(kelvins +"K is " + celcius + " degrees Celcius.");//It looks kinda funny
//Miles to Kilometers
System.out.println("Java can do multiplication using the '*' operator.");
System.out.println("For example, type a number in Miles and we will turn it into Kilometers");
double miles = sc.nextDouble();
final double MILECONVERSION = 1.609344;
double kilometers = miles * MILECONVERSION;
System.out.println(miles + " miles is equal to " + kilometers +" kilometers");
//Pounds to Kilograms
System.out.println("Java can also do division using the '/' operator.");
System.out.println("For example, type a number in pounds and we'll turn it into kilograms");
double pounds = sc.nextDouble();
final double KILOCONVERSION = 0.45359237;
double kilograms = pounds * KILOCONVERSION;
System.out.println(pounds + "lbs is equal to " + kilograms + "kgs");
//Other Java Math operations
System.out.println("Java also has the Math library, java.lang.Math, that does other stuff");
System.out.println("Type two whole numbers and a decimal number, separated by spaces");
int basenum = sc.nextInt();
int secnum = sc.nextInt();
double decimecy = sc.nextDouble();
double power = Math.pow(basenum, 2);//pow raises the first argument to the second power
double sqrt = Math.sqrt(basenum); //sqrt returns the square root of a number
double logb10 = Math.log10(basenum);//log10 returns the base10 log of a number
int maxinum = Math.max(basenum, secnum); //max returns the largest of two numbers
int mininum = Math.min(basenum, secnum);//min returns the smallest of two numbers
double sin = Math.sin(decimecy);
System.out.println(basenum + " to the power of 2 is " + power);
System.out.println("The Square Root of " + basenum + " is " + sqrt);
System.out.println(basenum + "to the log base 10 is " + logb10);
System.out.println(maxinum +" is bigger than " + mininum);
System.out.println(sin + " is the sin of " + decimecy);
sc.close();
}
}
|
{
"content_hash": "a136986d6c0f4cd65ebe3d7e5d060736",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 107,
"avg_line_length": 43.63513513513514,
"alnum_prop": 0.672963765871787,
"repo_name": "fgandiya/SoJava",
"id": "1b0046b52e11b8681bdac3ca8337566de4d97f57",
"size": "3229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Class 3 - Math/Mathical.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "19617"
}
],
"symlink_target": ""
}
|
using Xunit;
namespace NLog.Extensions.AzureTableStorage.Tests
{
public class AzureStorageTableNameValidatorTests
{
[Fact]
public void IsValidReturnFalseIfTableNameIsReservedWord()
{
var validator = new AzureStorageTableNameValidator("tables"); //reserved (invalid)
Assert.False(validator.IsValid());
}
[Fact]
public void IsValidReturnFalseIfTableNameVaiolatesRules_number()
{
var validator = new AzureStorageTableNameValidator("5");//invalid
Assert.False(validator.IsValid());
}
[Fact]
public void IsValidReturnFalseIfTableNameVaiolatesRules_startsWithNumber()
{
var validator = new AzureStorageTableNameValidator("5products");//invalid
Assert.False(validator.IsValid());
}
[Fact]
public void IsValidReturnFalseIfTableNameVaiolatesRules_containSpaces()
{
var validator = new AzureStorageTableNameValidator("products and customers");//invalid
Assert.False(validator.IsValid());
}
[Fact]
public void IsValidReturnTrueIfTableNameIsValid()
{
var validator = new AzureStorageTableNameValidator("myTable");//valid name
Assert.True(validator.IsValid());
}
}
}
|
{
"content_hash": "416e8fe16ea1e1261eab0450804e8a13",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 98,
"avg_line_length": 28.872340425531913,
"alnum_prop": 0.6337509211495947,
"repo_name": "harouny/NLog.Extensions.AzureTableStorage",
"id": "7fed7bbe2c268e266531c1bdcd4fb4f2b35d19bf",
"size": "1359",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "NLog.Extensions.AzureTableStorage.Tests/AzureStorageTableNameValidatorTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "20940"
}
],
"symlink_target": ""
}
|
import {Component} from '@angular/core';
@Component({
moduleId: module.id,
selector: 'radio-e2e',
templateUrl: 'radio-e2e.html',
})
export class SimpleRadioButtons {
isGroupDisabled: boolean = false;
}
|
{
"content_hash": "5f1c531fb38e0978cb10c083fbd3347f",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 40,
"avg_line_length": 21.1,
"alnum_prop": 0.7109004739336493,
"repo_name": "badjilounes/material2",
"id": "5df27b942fcca2a909fb26226cc7c0cec40f9998",
"size": "211",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/e2e-app/radio/radio-e2e.ts",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "144635"
},
{
"name": "HTML",
"bytes": "95075"
},
{
"name": "JavaScript",
"bytes": "16943"
},
{
"name": "Shell",
"bytes": "10734"
},
{
"name": "TypeScript",
"bytes": "1080740"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>event-tracer</artifactId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.event.tracer.ui</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Event Tracer UI</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ui</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.tracer.stub</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Carbon-Component>UIBundle</Carbon-Component>
<Export-Package>
org.wso2.carbon.event.tracer.ui.*
</Export-Package>
<Import-Package>
org.wso2.carbon.event.tracer.stub.*; version="${carbon.analytics.common.version}",
org.wso2.carbon.event.tracer.stub.client.*; version="${carbon.analytics.common.version}"
</Import-Package>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
{
"content_hash": "d2668a056c1495b1fcd73dfe66b29aa4",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 201,
"avg_line_length": 41.15384615384615,
"alnum_prop": 0.5897196261682243,
"repo_name": "chanakaudaya/carbon-analytics-common",
"id": "f82bc2a8782e2a9bfc6fc09036f7917f1c014380",
"size": "3210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/event-monitor/event-tracer/org.wso2.carbon.event.tracer.ui/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20552"
},
{
"name": "HTML",
"bytes": "35860"
},
{
"name": "Java",
"bytes": "3392772"
},
{
"name": "JavaScript",
"bytes": "182430"
},
{
"name": "Thrift",
"bytes": "6297"
}
],
"symlink_target": ""
}
|
import { isTreeItemInnerPropKey } from '../types';
export const partitionTreeProps = props => {
const treeItemInnerProps = {};
const accordionInnerProps = {};
Object.entries(props).forEach(prop => {
const [propKey, propValue] = prop;
if (props && isTreeItemInnerPropKey(propKey)) {
treeItemInnerProps[propKey] = propValue;
} else {
accordionInnerProps[propKey] = propValue;
}
});
return [treeItemInnerProps, accordionInnerProps];
};
//# sourceMappingURL=partitionTreeProps.js.map
|
{
"content_hash": "245d915d65871d44f5de52515c5774a6",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 51,
"avg_line_length": 32.375,
"alnum_prop": 0.7007722007722008,
"repo_name": "looker-open-source/components",
"id": "d14dfca78b11e2f6ad50b38b3b0a839914170871",
"size": "518",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/components/lib/Tree/utils/partitionTreeProps.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10788"
},
{
"name": "HTML",
"bytes": "10602733"
},
{
"name": "JavaScript",
"bytes": "125821"
},
{
"name": "Shell",
"bytes": "5731"
},
{
"name": "TypeScript",
"bytes": "6564851"
}
],
"symlink_target": ""
}
|
use option::Option;
use option::Option::None;
use kinds::Send;
use string::String;
/// Base functionality for all errors in Rust.
pub trait Error: Send {
/// A short description of the error; usually a static string.
fn description(&self) -> &str;
/// A detailed description of the error, usually including dynamic information.
fn detail(&self) -> Option<String> { None }
/// The lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> { None }
}
/// A trait for types that can be converted from a given error type `E`.
pub trait FromError<E> {
/// Perform the conversion.
fn from_error(err: E) -> Self;
}
// Any type is convertable from itself
impl<E> FromError<E> for E {
fn from_error(err: E) -> E {
err
}
}
|
{
"content_hash": "23ab713a4d9c44db3ae2463a0a9c894d",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 83,
"avg_line_length": 27,
"alnum_prop": 0.6500638569604087,
"repo_name": "emk/rust",
"id": "9ad2655f6e9dbd30e08b5b64cb49839754e767d2",
"size": "3436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/libstd/error.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3093"
},
{
"name": "Assembly",
"bytes": "25901"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "C",
"bytes": "676528"
},
{
"name": "C++",
"bytes": "62321"
},
{
"name": "CSS",
"bytes": "21483"
},
{
"name": "Emacs Lisp",
"bytes": "43099"
},
{
"name": "JavaScript",
"bytes": "32526"
},
{
"name": "Makefile",
"bytes": "201910"
},
{
"name": "Pascal",
"bytes": "1654"
},
{
"name": "Perl",
"bytes": "1076"
},
{
"name": "Puppet",
"bytes": "9596"
},
{
"name": "Python",
"bytes": "105676"
},
{
"name": "Rust",
"bytes": "17189000"
},
{
"name": "Shell",
"bytes": "294889"
},
{
"name": "VimL",
"bytes": "36290"
}
],
"symlink_target": ""
}
|
function module(name) {
return function(target) {
target.module = {
name
};
}
}
function log(ctor, level) {
ctor.loggable = true;
};
function immutable(param) {
return function(target, name, descriptor) {
descriptor.configurable = false;
Object.defineProperty(target, name, descriptor);
};
}
class CustomerView {
constructor() {}
get name() {
return "matias";
}
}
|
{
"content_hash": "93761ad83b91ef166dc9c867261acc6f",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 56,
"avg_line_length": 16.77777777777778,
"alnum_prop": 0.5739514348785872,
"repo_name": "mfidemraizer/jsguru2016-oct",
"id": "0d1816d4bb8564d878b68692b7f65c516456b91a",
"size": "453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/decorators.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "214"
},
{
"name": "JavaScript",
"bytes": "28332"
}
],
"symlink_target": ""
}
|
export default `
The Black Cat is a trick-taking playing card game for four players.
It is a variant of [Hearts](https://en.wikipedia.org/wiki/Hearts).
One of key differences is that it is played with only 32 cards, therefore German playing cards can be used as well as the French ones.
The goal is to have the fewest points by the end of the game.
## New game
Eight cards are dealt to each player.
Each player passes three cards from his hand to player on his left.
Any player can grill cards.
That means he can visibly put three Heart cards or Queen of Spades (The Black Cat) from his hand on table.
By doing this, penalty points of Hearts or of Queen of Spades are doubled.
If anyone else (or the player himself) grills another three Hearts cards, penalty points of Hearts are tripled.
The player can play these cards the same way as he would play a card from hand.
Random player is chosen to start the game.
## Round
The player on turn plays a card.
The player on left must play a card of the same suit as the card of the player that started the round.
If he does not have such a card, he can play any card.
Other players play a card as well in clock-wise direction.
The player whose card has the highest rank, gets the trick (the four cards on table).
He puts the trick onto his pile (reverse side visible).
Cards that are not of the same suit as the first card on table are ignored.
In the next round begins the player that got the trick.
## End of the game
After players do not have any cards to play, the game ends.
The winner is the player with the fewest penalty points.
## Scoring
Only Hearts and Queen of Spades cost penalty points.
Seven, Eight, Nine And Ten of Hearts cost 1 point.
Jack costs 2, Queen 3, King 4 and Ace 5.
Queen of Spades costs 13 penalty points.
`
|
{
"content_hash": "fca27533f061e1a1389ff36e7344727e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 134,
"avg_line_length": 38.97826086956522,
"alnum_prop": 0.7657557166759621,
"repo_name": "ErikCupal/the-black-cat-website",
"id": "9f57b733ff763c6a77c7c240e95455b279967c58",
"size": "1827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/common/components/Rules/rulesMd.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3456"
},
{
"name": "TypeScript",
"bytes": "40159"
}
],
"symlink_target": ""
}
|
if node['platform_family'] == 'rhel'
include_recipe 'yum-epel'
package 'mutt'
package 'alpine'
elsif node['platform_family'] == 'debian'
include_recipe 'apt'
package 'mutt'
end
|
{
"content_hash": "52e42fff4289316a88f6c9ec6739edc6",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 41,
"avg_line_length": 18.9,
"alnum_prop": 0.671957671957672,
"repo_name": "RallySoftware-cookbooks/mail_client",
"id": "aaab210cd4e4f552a963dc5c3a4ae5c239b60c5e",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/default.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3411"
}
],
"symlink_target": ""
}
|
#ifndef _CBTEK_COMMON_UTILITY_STRINGBUILDER_H
#define _CBTEK_COMMON_UTILITY_STRINGBUILDER_H
#include "UtilityCommon.hpp"
#include <string>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <sstream>
namespace cbtek {
namespace common {
namespace utility {
class CBTEK_UTILS_DLL StringBuilder
{
public:
//! Constructor for StringBuilder
/*!
Detailed description for StringBuilder
*/
StringBuilder(size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::vector<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::list<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::set<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::deque<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::stack<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief StringBuilder
* @param values
* @param floatingPointPrecision
*/
StringBuilder(const std::queue<std::string> & values,
size_t floatingPointPrecision = c_DEFAULT_FLOATING_PRECISION);
/**
* @brief operator <<
* @param value
* @return
*/
template <typename T>
StringBuilder & operator <<(const T & value);
/**
* @brief operator <<
* @param value
* @return
*/
StringBuilder & operator <<(double value);
/**
* @brief size
* @return
*/
size_t size() const;
/**
* @brief toList
* @return
*/
std::list<std::string> toList() const;
/**
* @brief toSet
* @return
*/
std::set<std::string> toSet() const;
/**
* @brief toVector
* @return
*/
std::vector<std::string> toVector() const;
/**
* @brief toDeque
* @return
*/
std::deque<std::string> toDeque() const;
/**
* @brief toStack
* @return
*/
std::stack<std::string> toStack() const;
/**
* @brief toQueue
* @return
*/
std::queue<std::string> toQueue() const;
/**
* @brief toList
* @param listOut
*/
void toList(std::list<std::string> & listOut) const;
/**
* @brief toVector
* @param vecOut
*/
void toVector(std::vector<std::string> &vecOut) const;
/**
* @brief toSet
* @param setOut
*/
void toSet(std::set<std::string> & setOut) const;
/**
* @brief toDeque
* @param deqOut
*/
void toDeque(std::deque<std::string> & deqOut) const;
/**
* @brief toQueue
* @param queOut
*/
void toQueue(std::queue<std::string> & queOut) const;
/**
* @brief toStack
* @param stackOut
*/
void toStack(std::stack<std::string> & stackOut) const;
/**
* @brief clear
*/
void clear();
/**
* @brief toString
* @param seperator
* @return
*/
std::string toString(const std::string & seperator="") const;
/**
* @brief toString
* @param prefixString
* @param postFixString
* @param seperator
* @return
*/
std::string toString(const std::string & prefixString,
const std::string & postFixString,
const std::string &seperator="") const;
//! Destructor
~StringBuilder();
private:
size_t m_floatingPointPrecision;
std::list<std::string> m_stringItems;
};
template <typename T>
StringBuilder & StringBuilder::operator << (const T & value)
{
std::ostringstream out;
out << value;
m_stringItems.push_back(out.str());
return (*this);
}
}}}//end namespace
#endif // _CBTEK_COMMON_UTILITY_STRINGBUILDER_H
|
{
"content_hash": "d55fce53350f4f7cbcd2a1ce992f6090",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 80,
"avg_line_length": 21.004587155963304,
"alnum_prop": 0.5756715440052413,
"repo_name": "cbtek/ClockNWork",
"id": "52438e1a611c94906f7abc80fad954e5caa04b51",
"size": "5647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/utility/inc/StringBuilder.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3139"
},
{
"name": "C++",
"bytes": "3148357"
},
{
"name": "CMake",
"bytes": "9766"
},
{
"name": "Prolog",
"bytes": "239"
},
{
"name": "QMake",
"bytes": "1196"
}
],
"symlink_target": ""
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_73a.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: w32_spawnvp
* BadSink : execute command with wspawnvp
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"-c"
#define COMMAND_ARG2 L"ls "
#define COMMAND_ARG3 data
#endif
#define ENV_VARIABLE L"ADD"
#ifdef _WIN32
#define GETENV _wgetenv
#else
#define GETENV getenv
#endif
using namespace std;
namespace CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<wchar_t *> dataList);
void bad()
{
wchar_t * data;
list<wchar_t *> dataList;
wchar_t dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
/* Append input from an environment variable to data */
size_t dataLen = wcslen(data);
wchar_t * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
wcsncat(data+dataLen, environment, 100-dataLen-1);
}
}
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<wchar_t *> dataList);
static void goodG2B()
{
wchar_t * data;
list<wchar_t *> dataList;
wchar_t dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
{
"content_hash": "6da74de70bb07b496476b44dd4df4d5c",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 124,
"avg_line_length": 25.553956834532375,
"alnum_prop": 0.6486486486486487,
"repo_name": "JianpingZeng/xcc",
"id": "693c7ee44fe19bb3897feae134e683c174d456b9",
"size": "3552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s07/CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_73a.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
Endpoint is an HTTP/HTTPS endpoint that receives HTTP/HTTPS requests from the Internet and proxies them to your app.
Endpoint consists of ALB (Application Load Balancer), ACM (Amazon Certificate Manager) certificate, and Route53 record.
### Create a new endpoint
```
$ bcn endpoint create --district=<district name> --certificate-arn=<ACM certificate ARN> --public
```
#### Options
- `--district`: District name where you want to create a new endpoint
- `--certificate-arn` ACM Certificate ARN
- If you specify this option, Barcelona automatically configures the endpoint so that it accepts HTTPS requests.
- Note that if you do not specify it, HTTPS will not be available on your endpoint.
- `--public`: If specified, Endpoint accepts requests from the Internet. If not, Endpoint is visible only from district's private network
## Heritage
In Barcelona, Your applications are called "Heritage".
### barcelona.yml
All heritage configurations are declared in a barcelona configuration file `barcelona.yml`
```
environments:
production:
name: barcelona
image_name: public.ecr.aws/degica/barcelona
services:
- name: web
service_type: web
cpu: 128
memory: 256
command: puma -C config/puma.rb
force_ssl: true
listeners:
- endpoint: barcelona
health_check_path: /health_check
- name: worker
command: rake jobs:work
cpu: 128
memory: 256
```
### Create
```
$ bcn create -e <environment> --district=<district name> --tag=<tag name>
```
### Deploy new version
```
$ bcn deploy -e <environment> --tag=<tag name>
```
## Service
## Interactive Command
Once you create your heritage, you can run interactive commands in a district environment (where your application is running)
```
$ bcn run -e <environment> --user=<username> --memory=<memory size in MB> command...
```
### Options
- `-e`: App environment
- `--user`: username in an interactive command container. Default: user specified in the docker image
- `--memory`: Memory size in MB that will be assigned to your command container. Default: 512
## Scheduled Tasks
TODO
## Environment Variables
### Set Environment Variables
You can set environment variables to your heritage.
```
$ bcn env set -e <environment> --secret KEY1=VALUE1 KEY2=VALUE2...
```
Environment variables will be applied to all containers that belong to your heritage such as services, `before_deploy` container, scheduled tasks, and interactive command container
#### Options
- `-e`: environment. `-e` and `-H` are exclusive
- `-H`: Heritage name. `-e` and `-H` are exclusive
- `--secret`: If set, variables are considered as secret. You can't see secret variables via `bcn env get`, only running containers have access to secret variables
### Get Environment Variables
```
$ bcn env get -e <environment>
```
#### Options
- `-e`: environment. `-e` and `-H` are exclusive
- `-H`: Heritage name. `-e` and `-H` are exclusive
|
{
"content_hash": "4e547c1f81c438e401f23877d7185cae",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 180,
"avg_line_length": 28.22641509433962,
"alnum_prop": 0.6998663101604278,
"repo_name": "degica/barcelona",
"id": "5ed4d3c1c1ab6257f4c113e8d13b792fdb73fc79",
"size": "3018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/user_guide.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "686"
},
{
"name": "Dockerfile",
"bytes": "3221"
},
{
"name": "Go",
"bytes": "6500"
},
{
"name": "HTML",
"bytes": "9234"
},
{
"name": "JavaScript",
"bytes": "1854"
},
{
"name": "Makefile",
"bytes": "422"
},
{
"name": "Procfile",
"bytes": "73"
},
{
"name": "Python",
"bytes": "1558"
},
{
"name": "Ruby",
"bytes": "532816"
},
{
"name": "Shell",
"bytes": "2953"
}
],
"symlink_target": ""
}
|
<?php
namespace mediasilo\share\email;
use mediasilo\model\Serializable;
class EmailShare implements Serializable {
public $audience;
public $subject;
public $message;
function __construct(array $audience, $message, $subject)
{
$this->audience = $audience;
$this->message = $message;
$this->subject = $subject;
}
public function toJson()
{
// TODO: Implement toJson() method.
}
public static function fromJson($json)
{
// TODO: Implement fromJson() method.
}
public static function fromStdClass($stdClass)
{
if($stdClass != null) {
$audience = isset($stdClass->audience) ? $stdClass->audience : null;
$message = isset($stdClass->message) ? $stdClass->message : null;
$subject = isset($stdClass->subject) ? $stdClass->subject : null;
return new EmailShare($audience, $message, $subject);
}
}
}
|
{
"content_hash": "b33d9ba4c5014be5e71381f93aec4209",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 80,
"avg_line_length": 24.125,
"alnum_prop": 0.5979274611398964,
"repo_name": "mediasilo/phoenix-php-sdk",
"id": "c0716a5ae8cd9ae23cebe30c2a681d2e57b9ebe9",
"size": "965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mediasilo/share/email/EmailShare.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "185732"
}
],
"symlink_target": ""
}
|
Portishead::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Turn off auto TLS for e-mail
ActionMailer::Base.smtp_settings[:enable_starttls_auto] = false
end
|
{
"content_hash": "1fc589980bab5dab5de51251639d9e31",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 84,
"avg_line_length": 35.78846153846154,
"alnum_prop": 0.7490596453519613,
"repo_name": "mralex/portishead",
"id": "10b16ab2564cdae335061b2784630afb0fd822eb",
"size": "1861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/environments/production.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16295"
},
{
"name": "Ruby",
"bytes": "92975"
}
],
"symlink_target": ""
}
|
package main
import (
"encoding/json"
"flag"
"log"
"net/url"
"os"
"strings"
"time"
"unicode"
maas "github.com/juju/gomaasapi"
)
const (
// defaultFilter specifies the default filter to use when none is specified
defaultFilter = `{
"hosts" : {
"include" : [ ".*" ],
"exclude" : []
},
"zones" : {
"include" : ["default"],
"exclude" : []
}
}`
defaultMapping = "{}"
)
var apiKey = flag.String("apikey", "", "key with which to access MAAS server")
var maasURL = flag.String("maas", "http://localhost/MAAS", "url over which to access MAAS")
var apiVersion = flag.String("apiVersion", "1.0", "version of the API to access")
var queryPeriod = flag.String("period", "15s", "frequency the MAAS service is polled for node states")
var preview = flag.Bool("preview", false, "displays the action that would be taken, but does not do the action, in this mode the nodes are processed only once")
var mappings = flag.String("mappings", "{}", "the mac to name mappings")
var always = flag.Bool("always-rename", true, "attempt to rename at every stage of workflow")
var verbose = flag.Bool("verbose", false, "display verbose logging")
var filterSpec = flag.String("filter", strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, defaultFilter), "constrain by hostname what will be automated")
// checkError if the given err is not nil, then fatally log the message, else
// return false.
func checkError(err error, message string, v ...interface{}) bool {
if err != nil {
log.Fatalf("[error] "+message, v)
}
return false
}
// checkWarn if the given err is not nil, then log the message as a warning and
// return true, else return false.
func checkWarn(err error, message string, v ...interface{}) bool {
if err != nil {
log.Printf("[warn] "+message, v)
return true
}
return false
}
// fetchNodes do a HTTP GET to the MAAS server to query all the nodes
func fetchNodes(client *maas.MAASObject) ([]MaasNode, error) {
nodeListing := client.GetSubObject("nodes")
listNodeObjects, err := nodeListing.CallGet("list", url.Values{})
if checkWarn(err, "unable to get the list of all nodes: %s", err) {
return nil, err
}
listNodes, err := listNodeObjects.GetArray()
if checkWarn(err, "unable to get the node objects for the list: %s", err) {
return nil, err
}
var nodes = make([]MaasNode, len(listNodes))
for index, nodeObj := range listNodes {
node, err := nodeObj.GetMAASObject()
if !checkWarn(err, "unable to retrieve object for node: %s", err) {
nodes[index] = MaasNode{node}
}
}
return nodes, nil
}
func main() {
flag.Parse()
options := ProcessingOptions{
Preview: *preview,
Verbose: *verbose,
AlwaysRename: *always,
}
// Determine the filter, this can either be specified on the the command
// line as a value or a file reference. If none is specified the default
// will be used
if len(*filterSpec) > 0 {
if (*filterSpec)[0] == '@' {
name := os.ExpandEnv((*filterSpec)[1:])
file, err := os.OpenFile(name, os.O_RDONLY, 0)
checkError(err, "[error] unable to open file '%s' to load the filter : %s", name, err)
decoder := json.NewDecoder(file)
err = decoder.Decode(&options.Filter)
checkError(err, "[error] unable to parse filter configuration from file '%s' : %s", name, err)
} else {
err := json.Unmarshal([]byte(*filterSpec), &options.Filter)
checkError(err, "[error] unable to parse filter specification: '%s' : %s", *filterSpec, err)
}
} else {
err := json.Unmarshal([]byte(defaultFilter), &options.Filter)
checkError(err, "[error] unable to parse default filter specificiation: '%s' : %s", defaultFilter, err)
}
// Determine the mac to name mapping, this can either be specified on the the command
// line as a value or a file reference. If none is specified the default
// will be used
if len(*mappings) > 0 {
if (*mappings)[0] == '@' {
name := os.ExpandEnv((*mappings)[1:])
file, err := os.OpenFile(name, os.O_RDONLY, 0)
checkError(err, "[error] unable to open file '%s' to load the mac name mapping : %s", name, err)
decoder := json.NewDecoder(file)
err = decoder.Decode(&options.Mappings)
checkError(err, "[error] unable to parse filter configuration from file '%s' : %s", name, err)
} else {
err := json.Unmarshal([]byte(*mappings), &options.Mappings)
checkError(err, "[error] unable to parse mac name mapping: '%s' : %s", *mappings, err)
}
} else {
err := json.Unmarshal([]byte(defaultMapping), &options.Mappings)
checkError(err, "[error] unable to parse default mac name mappings: '%s' : %s", defaultMapping, err)
}
// Verify the specified period for queries can be converted into a Go duration
period, err := time.ParseDuration(*queryPeriod)
checkError(err, "[error] unable to parse specified query period duration: '%s': %s", queryPeriod, err)
authClient, err := maas.NewAuthenticatedClient(*maasURL, *apiKey, *apiVersion)
if err != nil {
checkError(err, "[error] Unable to use specified client key, '%s', to authenticate to the MAAS server: %s", *apiKey, err)
}
// Create an object through which we will communicate with MAAS
client := maas.NewMAAS(*authClient)
// This utility essentially polls the MAAS server for node state and
// process the node to the next state. This is done by kicking off the
// process every specified duration. This means that the first processing of
// nodes will have "period" in the future. This is really not the behavior
// we want, we really want, do it now, and then do the next one in "period".
// So, the code does one now.
nodes, _ := fetchNodes(client)
ProcessAll(client, nodes, options)
if !(*preview) {
// Create a ticker and fetch and process the nodes every "period"
ticker := time.NewTicker(period)
for t := range ticker.C {
log.Printf("[info] query server at %s", t)
nodes, _ := fetchNodes(client)
ProcessAll(client, nodes, options)
}
}
}
|
{
"content_hash": "f42e8eaa674adf7d50cc0aeeb433ecb8",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 160,
"avg_line_length": 35.59281437125748,
"alnum_prop": 0.6795087483176312,
"repo_name": "ciena/maas-flow",
"id": "1514e32aed073ce3e7f078600143ea6e683ddefd",
"size": "5944",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "maas-flow.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "20497"
},
{
"name": "Makefile",
"bytes": "522"
}
],
"symlink_target": ""
}
|
var mongoose = require('mongoose');
var jobSchema = new mongoose.Schema({
title: String,
url: String,
email: String,
description: String,
first_seen: { type: Date, default: Date.now },
last_seen: { type: Date, default: Date.now },
company: String,
location: String,
tags: [{name: String, label: String}],
});
module.exports = mongoose.model('Job', jobSchema);
|
{
"content_hash": "ff4fb1a2c14ddcccb12d4569305ad6f5",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 50,
"avg_line_length": 25.866666666666667,
"alnum_prop": 0.654639175257732,
"repo_name": "grantrules/bikeindustryjobs",
"id": "54b4fc7655a43f8c3198f48e758f06b403e85c75",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/job.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10658"
},
{
"name": "HTML",
"bytes": "1044"
},
{
"name": "JavaScript",
"bytes": "123375"
},
{
"name": "Shell",
"bytes": "65"
}
],
"symlink_target": ""
}
|
package lib;
import lejos.hardware.lcd.LCD;
import lib.graphics.Graphics;
/**
* Loading screen to not bore the user when something is loading.
*/
public class LoadingScreen extends Thread
{
private long spinSpeed;
private int y;
private boolean text;
private String ltext = "Loading...";
public LoadingScreen(int y)
{
this.spinSpeed = 500;
this.y = y;
this.text = false;
this.start();
}
public LoadingScreen(double speed, int y)
{
this.spinSpeed = Math.round(speed * 1000);
this.y = y;
this.text = false;
this.start();
}
public LoadingScreen(int y, String text)
{
this.spinSpeed = 500;
this.y = y;
this.text = true;
this.ltext = text;
this.start();
}
public LoadingScreen(double speed, int y, String text)
{
this.spinSpeed = Math.round(speed * 1000);
this.y = y;
this.text = true;
this.ltext = text;
this.start();
}
@Override
public void run()
{
try
{
this.draw();
}
catch (Exception e){}
}
public void draw() throws Exception
{
if(text)
{
Graphics.drawCenteredString(this.ltext, y - 1);
}
byte stage = 0;
byte startx = 5;
while(true)
{
LCD.clear(y);
this.drawPointer(stage, startx);
LoadingScreen.sleep(spinSpeed);
stage++;
if(stage > 3){stage = 0;}
}
}
@Override
public void interrupt()
{
super.interrupt();
LCD.clear();
}
public void finish()
{
this.interrupt();
}
@Override
public void start()
{
super.start();
LCD.clear();
}
public void drawPointer(byte state, byte startx)
{
if(state == 0)
{
LCD.drawString("|.. |", startx, y);
}
else if(state == 1 || state == 3)
{
LCD.drawString("| ... |", startx, y);
}
else if(state == 2)
{
LCD.drawString("| ..|", startx, y);
}
}
}
|
{
"content_hash": "0ddcfb44bfcc15fe0bf79ec0159015f5",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 65,
"avg_line_length": 16.49122807017544,
"alnum_prop": 0.5707446808510638,
"repo_name": "Enginecrafter77/LeJOS_Subprogram_Framework",
"id": "f0a130c25eb91c913f95294ef472a2cbef00603f",
"size": "1880",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/LoadingScreen.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "212828"
}
],
"symlink_target": ""
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jsmpp.bean;
import org.jsmpp.SMPPConstant;
/**
* Enum represent bind type of SMPP. There are 3 bind types provided by SMPP 3.4:
*
* <ul>
* <li>receiver (BIND_RX) - receive only</li>
* <li>transmitter (BIND_TX) - transmit only</li>
* <li>transceiver (BIND_TRX) - receive and transmit</li>
* </ul>
*
* For SMPP 3.3, only BIND_TX and BIND_RX are defined.
*
* @author uudashr
* @version 1.0
* @since 1.0
*/
public enum BindType {
/**
* Bind transmitter.
*/
BIND_TX(SMPPConstant.CID_BIND_TRANSMITTER),
/**
* Bind receiver.
*/
BIND_RX(SMPPConstant.CID_BIND_RECEIVER),
/**
* Bind transceiver.
*/
BIND_TRX(SMPPConstant.CID_BIND_TRANSCEIVER);
private final int bindCommandId;
BindType(int bindCommandId) {
this.bindCommandId = bindCommandId;
}
/**
* Get the command_id of given bind type.
*
* @return the bind command_id.
*/
public int commandId() {
return bindCommandId;
}
/**
* Return the response command_id that should be given by this bind type.
*
* @return the bind response command_id.
*/
public int responseCommandId() {
return bindCommandId | SMPPConstant.MASK_CID_RESP;
}
/**
* Inform whether the bind type is transmittable.
*
* @return {@code true} if the bind type is transmittable, otherwise {@code false}.
*/
public boolean isTransmittable() {
return this == BIND_TX || this == BIND_TRX;
}
/**
* Inform whether the bind type is receivable.
*
* @return {@code true} if the bind type is receivable, otherwise {@code false}.
*/
public boolean isReceivable() {
return this == BIND_RX || this == BIND_TRX;
}
/**
* Get the {@code BindType} by specified command_id.
*
* @param bindCommandId is the command_id.
* @return the enum const associated with the specified
* {@code bindCommandId}
* @throws IllegalArgumentException if there is no {@code BindType}
* associated with specified {@code bindCommandId} found.
*/
public static BindType valueOf(int bindCommandId)
throws IllegalArgumentException {
for (BindType bindType : values()) {
if (bindType.bindCommandId == bindCommandId) {
return bindType;
}
}
throw new IllegalArgumentException(
"No enum const BindType with command id " + bindCommandId);
}
}
|
{
"content_hash": "650a3e02b9b3870211f20a644b1e20b2",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 87,
"avg_line_length": 27.732142857142858,
"alnum_prop": 0.6245975531229878,
"repo_name": "opentelecoms-org/jsmpp",
"id": "3383f48befbfc0b4fd2603f6d7110833fbdb748a",
"size": "3106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsmpp/src/main/java/org/jsmpp/bean/BindType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1813"
},
{
"name": "Java",
"bytes": "1459610"
},
{
"name": "Shell",
"bytes": "2297"
}
],
"symlink_target": ""
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TotoWin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TotoWin")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d937af6c-21f0-47d6-94aa-5ff3868676f1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
{
"content_hash": "491285fbf7d673c8a6a084db2e94aa43",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.52777777777778,
"alnum_prop": 0.7433309300648883,
"repo_name": "zachdimitrov/Learning_2017",
"id": "8c14d950a5624a85aad8bbc1229f6da3c6a4f52f",
"size": "1390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DSA/Combinatorics/TotoWin/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "309"
},
{
"name": "Batchfile",
"bytes": "517"
},
{
"name": "C#",
"bytes": "1744043"
},
{
"name": "CSS",
"bytes": "87153"
},
{
"name": "CoffeeScript",
"bytes": "8842"
},
{
"name": "HTML",
"bytes": "491299"
},
{
"name": "JavaScript",
"bytes": "5680271"
},
{
"name": "PLpgSQL",
"bytes": "13058"
},
{
"name": "SQLPL",
"bytes": "6946"
},
{
"name": "TypeScript",
"bytes": "19468"
},
{
"name": "XSLT",
"bytes": "7513"
}
],
"symlink_target": ""
}
|
#pragma once
/*
Checker for the Quality Control information of phenotypic files
*/
class QCChecker
{
public:
QCChecker() = default;
virtual void reset() = 0;
virtual bool needMore() const = 0;
virtual bool result() const = 0;
virtual void input(const bool b) = 0;
virtual void input() = 0;
};
|
{
"content_hash": "8bf7fd2f69c32447aed73a20cdef2224",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 63,
"avg_line_length": 16.88888888888889,
"alnum_prop": 0.6907894736842105,
"repo_name": "yxtj/GSDM",
"id": "bdd8e0e68f6904cd0be22c85c8f78e91e80c5035",
"size": "304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GraphConverter/QCChecker.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1213"
},
{
"name": "C++",
"bytes": "525110"
},
{
"name": "Makefile",
"bytes": "21867"
},
{
"name": "Matlab",
"bytes": "13431"
},
{
"name": "Python",
"bytes": "42277"
},
{
"name": "Shell",
"bytes": "5320"
}
],
"symlink_target": ""
}
|
package ru.job4j.tracker.start;
/**
* Created by User on 23.02.2017.
*/
public class StubInput implements Input {
/**
* new List of answers.
*/
private String[] answers;
/**
* counter for num of answers.
*/
private int count = 0;
/**
* StubInput constructor.
* @param answers List of strings
*/
public StubInput(String[] answers) {
this.answers = answers;
}
/**
* ask simulates user`s choice.
* @param question depends of implementation
* @return answers
*/
public String ask(String question) {
return this.answers[count++];
}
@Override
public int ask(String question, int[] range) {
return Integer.parseInt(this.answers[count++]);
}
}
|
{
"content_hash": "227118a04cf050b8ecfa73e7098377ae",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 55,
"avg_line_length": 20.394736842105264,
"alnum_prop": 0.5819354838709677,
"repo_name": "Yurik16/yuchuksin",
"id": "9cfd966bebff974c3ee78397e48d03e369cfcc9b",
"size": "775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_002/src/main/java/ru/job4j/tracker/start/StubInput.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "193159"
}
],
"symlink_target": ""
}
|
<?php
namespace Medology\Behat\Mink;
use Behat\Gherkin\Node\TableNode;
use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Element\NodeElement;
use Behat\Mink\Element\TraversableElement;
use Behat\Mink\Exception\DriverException;
use Behat\Mink\Exception\ElementNotFoundException;
use Behat\Mink\Exception\ElementTextException;
use Behat\Mink\Exception\ExpectationException;
use Behat\Mink\Exception\ResponseTextException;
use Behat\Mink\Exception\UnsupportedDriverActionException;
use Behat\MinkExtension\Context\MinkContext;
use Exception as GenericException;
use InvalidArgumentException;
use Medology\Behat\HasWaitProxy;
use Medology\Behat\Mink\Models\Geometry\Rectangle;
use Medology\Behat\StoreContext;
use Medology\Behat\TypeCaster;
use Medology\Behat\UsesStoreContext;
use Medology\Spinner;
use OutOfBoundsException;
use ReflectionException;
use WebDriver\Exception;
use ZipArchive;
/**
* Overwrites some MinkContext step definitions to make them more resilient to failures caused by browser/driver
* discrepancies and unpredictable load times.
*
* @property FlexibleContextWaitProxy $wait
*/
class FlexibleContext extends MinkContext
{
use HasWaitProxy;
use TypeCaster;
use UsesStoreContext;
/** @var array map of common key names to key codes */
protected static $keyCodes = [
'down arrow' => 40,
'enter' => 13,
'return' => 13,
'shift tab' => 2228233,
'tab' => 9,
];
/** @var FlexibleContextWaitProxy */
protected $wait;
public function __construct()
{
$this->wait = new FlexibleContextWaitProxy($this);
}
/**
* {@inheritdoc}
*
* Overrides the base method to support injecting stored values and matching URLs that include hostname.
*
* @param string $page the page to assert we are on
*
* @throws DriverException if the driver failed to perform the action
* @throws ExpectationException If the current page is not the expected page.
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* @throws OutOfBoundsException if a stored item was referenced in the text and the specified stored item does
* not have the specified property or key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
*/
public function assertPageAddress($page)
{
$page = $this->storeContext->injectStoredValues($page);
/* @noinspection PhpUnhandledExceptionInspection */
Spinner::waitFor(function () use ($page) {
// is the page a path, or a full URL?
if (preg_match('!^https?://!', $page) == 0) {
// it's just a path. delegate to parents implementation
parent::assertPageAddress($page);
} else {
// it's a full URL, compare manually
$actual = $this->getSession()->getCurrentUrl();
if (strpos($actual, $page) !== 0) {
throw new ExpectationException(
sprintf('Current page is "%s", but "%s" expected.', $actual, $page),
$this->getSession()
);
}
}
});
}
/**
* Checks that current url has the specified query parameters.
*
* @Then /^(?:|I )should be on "(?P<page>[^"]+)" with the following query parameters:$/
*
* @param string $page the current page path of the query parameters
* @param TableNode $parameters the values of the query parameters
*
* @throws DriverException if the driver failed to perform the action
* @throws ReflectionException if injectStoredValues incorrectly believes one or more closures were passed
* @throws ExpectationException if the current page is not the expected page
* @throws ExpectationException if the one of the current page params are not set
* @throws ExpectationException if the one of the current page param values does not match with the expected
*/
public function assertPageAddressWithQueryParameters(string $page, TableNode $parameters): void
{
$this->assertPageAddress($page);
$parts = parse_url($this->getSession()->getCurrentUrl());
parse_str($parts['query'], $params);
foreach ($parameters->getRowsHash() as $param => $value) {
if (!isset($params[$param])) {
throw new ExpectationException("Query did not contain a $param parameter", $this->getSession());
}
if ($params[$param] != $value) {
throw new ExpectationException("Expected query parameter $param to be $value, but found " . print_r($params[$param], true), $this->getSession());
}
}
}
/**
* This method overrides the MinkContext::assertPageContainsText() default behavior for assertPageContainsText to
* inject stored values into the provided text.
*
* @see StoreContext::injectStoredValues()
*
* @param string $text text to be searched in the page
*
* @throws InvalidArgumentException if the string references something that does not exist in the store
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if a stored item was referenced in the text and the specified stored item does
* not have the specified property or key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
* @throws ResponseTextException if the text is not found
*/
public function assertPageContainsText($text)
{
parent::assertPageContainsText($this->storeContext->injectStoredValues($text));
}
/**
* Asserts that the page contains a list of strings.
*
* @Then /^I should (?:|(?P<not>not ))see the following:$/
*
* @param TableNode $table the list of strings to find
* @param string $not a flag to assert not containing text
*
* @throws InvalidArgumentException if the string references something that does not exist in the store
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if the specified stored item does not have the specified property or
* key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
* @throws ResponseTextException if the text is not found
*/
public function assertPageContainsTexts(TableNode $table, string $not = ''): void
{
if (count($table->getRow(0)) > 1) {
throw new InvalidArgumentException('Arguments must be a single-column list of items');
}
foreach ($table->getRows() as $text) {
if ($not) {
$this->assertPageNotContainsText($text[0]);
} else {
$this->assertPageContainsText($text[0]);
}
}
}
/**
* This method overrides the MinkContext::assertPageNotContainsText() default behavior for assertPageNotContainsText
* to inject stored values into the provided text.
*
* @see StoreContext::injectStoredValues()
*
* @param string $text the text that should not be found on the page
*
* @throws InvalidArgumentException if the string references something that does not exist in the store
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if the specified stored item does not have the specified property or
* key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
* @throws ResponseTextException if the page does not contain the text
*/
public function assertPageNotContainsText($text)
{
parent::assertPageNotContainsText($this->storeContext->injectStoredValues($text));
}
/**
* {@inheritdoc}
*
* Overrides the parent method to support injecting values from the store into the field and value.
*
* @throws InvalidArgumentException if the string references something that does not exist in the store
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if the specified stored item does not have the specified property or
* key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
*/
public function assertFieldContains($field, $value)
{
$field = $this->storeContext->injectStoredValues($field);
$value = $this->storeContext->injectStoredValues($value);
parent::assertFieldContains($field, $value);
}
/**
* Asserts that a field is visible or not.
*
* @Then /^the field "(?P<field>[^"]+)" should(?P<not> not|) be visible$/
*
* @param string $field The field to be checked
* @param bool $not check if field should be visible or not
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if there is more than one matching field found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertFieldVisibility(string $field, bool $not): void
{
$locator = $this->fixStepArgument($field);
$fields = $this->getSession()->getPage()->findAll('named', ['field', $locator]);
if (count($fields) > 1) {
throw new ExpectationException("The field '$locator' was found more than one time", $this->getSession());
}
$shouldBeVisible = !$not;
if (($shouldBeVisible && !$fields[0]->isVisible()) || (!$shouldBeVisible && $fields[0]->isVisible())) {
throw new ExpectationException("The field '$locator' was " . (!$not ? 'not ' : '') . 'visible or not found', $this->getSession());
}
}
/**
* This method overrides the MinkContext::assertElementContainsText() default behavior for
* assertElementContainsText to inject stored values into the provided element and text.
*
* @see StoreContext::injectStoredValues()
*
* @param string $element css element selector
* @param string $text expected text
*
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if the specified stored item does not have the specified property or
* key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
* @throws ElementTextException if the element does not contain the text
*/
public function assertElementContainsText($element, $text)
{
parent::assertElementContainsText(
$this->storeContext->injectStoredValues($element),
$this->storeContext->injectStoredValues($text)
);
}
/**
* Checks, that element with specified CSS doesn't contain specified text.
*
* @see MinkContext::assertElementNotContainsText
*
* @param string $element css element selector
* @param string $text expected text that should not being found
*
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed,
* and they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws OutOfBoundsException if the specified stored item does not have the specified property or
* key
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
* @throws ElementTextException if the element contains the text
*/
public function assertElementNotContainsText($element, $text)
{
parent::assertElementNotContainsText(
$this->storeContext->injectStoredValues($element),
$this->storeContext->injectStoredValues($text)
);
}
/**
* {@inheritdoc}
*
* Overrides the base method store the resulting element in the store under "element" and return it.
*
* @param string $element the selector to find the element
* @param string $selectorType css|xpath selector type to find the element
*
* @throws ElementNotFoundException if the element was not found
*
* @return NodeElement the element found
*/
public function assertElementOnPage($element, string $selectorType = 'css')
{
$node = $this->assertSession()->elementExists($selectorType, $element);
$this->storeContext->set('element', $node);
return $node;
}
/**
* Asserts that an element with the given XPath is present in the container, and returns it.
*
* @param NodeElement $container the base element to search in
* @param string $xpath the XPath of the element to locate inside the container
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException if no element was found
*
* @return NodeElement the found element
*/
public function assertElementInsideElement(NodeElement $container, $xpath): NodeElement
{
if (!$element = $container->find('xpath', $xpath)) {
throw new ExpectationException('Nothing found inside element with xpath $xpath', $this->getSession());
}
return $element;
}
/**
* Checks that elements with specified selector exist.
*
* @param string $element the element to search for
* @param string $selectorType selector type locator
*
* @throws ExpectationException when no element is found
*
* @return NodeElement[] all elements found with by the given selector
*/
public function assertElementsExist(string $element, string $selectorType = 'css'): array
{
$session = $this->getSession();
/* @noinspection PhpUnhandledExceptionInspection */
return Spinner::waitFor(function () use ($session, $selectorType, $element) {
if (!$allElements = $session->getPage()->findAll($selectorType, $element)) {
throw new ExpectationException("No '$element' was found", $session);
}
return $allElements;
});
}
/**
* Checks that the nth element exists and returns it.
*
* @param string $element the elements to search for
* @param int $nth this is the nth amount of the element
* @param string $selectorType selector type locator
*
* @throws ExpectationException when the nth element is not found
*
* @return NodeElement the nth element found
*/
public function assertNthElement(string $element, int $nth, string $selectorType = 'css'): NodeElement
{
$allElements = $this->assertElementsExist($element, $selectorType);
if (!isset($allElements[$nth - 1])) {
throw new ExpectationException("Element $element $nth was not found", $this->getSession());
}
return $allElements[$nth - 1];
}
/**
* Clicks a visible link with specified id|title|alt|text.
* This method overrides the MinkContext::clickLink() default behavior for clickLink to ensure that only visible
* links are clicked.
*
* @see MinkContext::clickLink
*
* @param string $link the id|title|alt|text of the link to be clicked
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified link is not visible
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function clickLink($link)
{
$link = $this->storeContext->injectStoredValues($link);
Spinner::waitFor(
function () use ($link) {
$this->scrollToLink($link)->click();
}
);
}
/**
* Clicks a visible checkbox with specified id|title|alt|text.
*
* This method overrides the MinkContext::checkOption() default behavior for checkOption to ensure that only visible
* options are checked and inject stored values into the provided locator.
*
* @see StoreContext::injectStoredValues()
* @see MinkContext::checkOption
*
* @param string $locator the id|title|alt|text of the option to be clicked
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified option is not visible
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function checkOption($locator)
{
$locator = $this->storeContext->injectStoredValues($locator);
$this->wait->scrollToOption($locator)->check();
}
/**
* Clicks a visible field with specified id|title|alt|text.
*
* This method overrides the MinkContext::fillField() default behavior for fill a field to ensure that only visible
* field is filled.
*
* @see MinkContext::fillField
*
* @param string $field the id|title|alt|text of the field to be filled
* @param string $value the value to be set on the field
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified field does not exist
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function fillField($field, $value)
{
$field = $this->storeContext->injectStoredValues($field);
$value = $this->storeContext->injectStoredValues($value);
$this->wait->scrollToField($field)->setValue($value);
}
/**
* Un-checks checkbox with specified id|name|label|value.
*
* @see MinkContext::uncheckOption
*
* @param string $locator the id|title|alt|text of the option to be unchecked
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified option is not visible
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function uncheckOption($locator)
{
$locator = $this->storeContext->injectStoredValues($locator);
$this->wait->scrollToOption($locator)->uncheck();
}
/**
* Checks if the selected button is disabled.
*
* @todo fix Given used with Then (incompatible)
* @Given the :locator button is :disabled
* @Then the :locator button should be :disabled
*
* @param string $locator The button
* @param string|bool $disabled The state of the button
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if button is disabled but shouldn't be
* @throws ExpectationException if button isn't disabled but should be
* @throws ExpectationException if the button can't be found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertButtonDisabled(string $locator, $disabled = true): void
{
if (is_string($disabled)) {
$disabled = 'disabled' == $disabled;
}
$button = $this->getSession()->getPage()->findButton($locator);
if (!$button) {
throw new ExpectationException("Could not find button for $locator", $this->getSession());
}
if ($button->hasAttribute('disabled')) {
if (!$disabled) {
throw new ExpectationException("The button, $locator, was disabled, but it should not have been disabled.", $this->getSession());
}
} elseif ($disabled) {
throw new ExpectationException("The button, $locator, was not disabled, but it should have been disabled.", $this->getSession());
}
}
/**
* Asserts that the specified button exists in the DOM.
*
* @Then I should see a :locator button
*
* @param string $locator the id|name|title|alt|value of the button
*
* @throws DriverException when the operation cannot be done
* @throws ExpectationException if no button was found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the button
*/
public function assertButtonExists(string $locator): NodeElement
{
$locator = $this->fixStepArgument($locator);
if (!$button = $this->getSession()->getPage()->find('named', ['button', $locator])) {
throw new ExpectationException("No button found for '$locator'", $this->getSession());
}
return $button;
}
/**
* Finds the first matching visible button on the page.
*
* Warning: Will return the first button if the driver does not support visibility checks.
*
* @param string $locator the button name
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible button was not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the button
*/
public function assertVisibleButton(string $locator): NodeElement
{
$locator = $this->fixStepArgument($locator);
$buttons = $this->getSession()->getPage()->findAll('named', ['button', $locator]);
/** @var NodeElement $button */
foreach ($buttons as $button) {
try {
if ($button->isVisible()) {
return $button;
}
} catch (UnsupportedDriverActionException $e) {
return $button;
}
}
throw new ExpectationException("No visible button found for '$locator'", $this->getSession());
}
/**
* Finds the first matching visible button on the page, scrolling to it if necessary.
*
* @param string $locator the button name
* @param TraversableElement|null $context element on the page to which button belongs
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible button was not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the button
*/
public function scrollToButton(string $locator, TraversableElement $context = null): NodeElement
{
$locator = $this->fixStepArgument($locator);
/* @noinspection PhpUnhandledExceptionInspection */
return Spinner::waitFor(function () use ($locator, $context) {
$context = $context ? $context : $this->getSession()->getPage();
$buttons = $context->findAll('named', ['button', $locator]);
if (!($element = $this->scrollWindowToFirstVisibleElement($buttons))) {
throw new ExpectationException("No visible button found for '$locator'", $this->getSession());
}
return $element;
});
}
/**
* Finds the first matching visible link on the page.
*
* Warning: Will return the first link if the driver does not support visibility checks.
*
* @Given the :locator link is visible
* @Then the :locator link should be visible
*
* @param string $locator the link name
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible link was not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the link
*/
public function assertVisibleLink(string $locator): NodeElement
{
$links = $this->getLinks($locator);
$links = array_filter($links, function (NodeElement $link) {
return $link->isVisible();
});
if (empty($links)) {
throw new ExpectationException("No visible link found for '$locator'", $this->getSession());
}
// $links is NOT numerically indexed, so just grab the first element and send it back
return array_shift($links);
}
/**
* Finds the first matching visible link on the page, scrolling to it if necessary.
*
* @param string $locator the link name
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible link was not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the link
*/
public function scrollToLink(string $locator): NodeElement
{
/* @noinspection PhpUnhandledExceptionInspection */
return Spinner::waitFor(function () use ($locator) {
$links = $this->getLinks($locator);
if (!($element = $this->scrollWindowToFirstVisibleElement($links))) {
throw new ExpectationException("No visible link found for '$locator'", $this->getSession());
}
return $element;
});
}
/**
* Returns a set of links matching the given locator.
*
* @param string $locator the link name
*
* @return NodeElement[] the links matching the given name
*/
public function getLinks(string $locator): array
{
$locator = $this->fixStepArgument($locator);
// the link selector in Behat/Min/src/Selector/NamedSelector requires anchor tags have href
// we don't want that, because some don't, so rip out that section. Ideally we would load our own
// selector with registerNamedXpath, but I want to re-use the link named selector so we're doing it
// this way
$xpath = $this->getSession()->getSelectorsHandler()->selectorToXpath('named', ['link', $locator]);
$xpath = preg_replace('/\[\.\/@href\]/', '', $xpath);
/* @var NodeElement[] $links */
return $this->getSession()->getPage()->findAll('xpath', $xpath);
}
/**
* Finds the first matching visible option on the page, scrolling to it if necessary.
*
* @param string $locator the option name
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible option was not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the option
*/
public function scrollToOption(string $locator): NodeElement
{
$locator = $this->fixStepArgument($locator);
/* @noinspection PhpUnhandledExceptionInspection */
return Spinner::waitFor(function () use ($locator) {
$options = $this->getSession()->getPage()->findAll('named', ['field', $locator]);
if (!($element = $this->scrollWindowToFirstVisibleElement($options))) {
throw new ExpectationException("No visible option found for '$locator'", $this->getSession());
}
return $element;
});
}
/**
* Checks that the page contains a visible input field and then returns it.
*
* @param string $fieldName the input name
* @param TraversableElement|null $context the context to search in, if not provided defaults to page
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible input field is not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the found input field
*/
public function assertFieldExists(string $fieldName, TraversableElement $context = null): NodeElement
{
$context = $context ?: $this->getSession()->getPage();
/** @var NodeElement[] $fields */
$fields = ($context->findAll('named', ['field', $fieldName]) ?: $this->getInputsByLabel($fieldName, $context));
foreach ($fields as $field) {
if ($field->isVisible()) {
return $field;
}
}
throw new ExpectationException("No visible input found for '$fieldName'", $this->getSession());
}
/**
* Checks that the page contains a visible input field and then returns it, scrolling to it if necessary.
*
* @param string $fieldName the input name
* @param TraversableElement|null $context the context to search in, if not provided defaults to page
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible input field is not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement the found input field
*/
public function scrollToField(string $fieldName, TraversableElement $context = null): NodeElement
{
/* @noinspection PhpUnhandledExceptionInspection */
return Spinner::waitFor(function () use ($fieldName, $context) {
$context = $context ?: $this->getSession()->getPage();
/** @var NodeElement[] $fields */
$fields = ($context->findAll('named', ['field', $fieldName]) ?: $this->getInputsByLabel($fieldName, $context));
if (!($element = $this->scrollWindowToFirstVisibleElement($fields))) {
throw new ExpectationException("No visible input found for '$fieldName'", $this->getSession());
}
return $element;
});
}
/**
* Gets all the inputs that have the label name specified within the context specified.
*
* @param string $labelName the label text used to find the inputs for
* @param TraversableElement $context the context to search in
*
* @throws DriverException when the operation cannot be performed
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return NodeElement[]
*/
public function getInputsByLabel(string $labelName, TraversableElement $context): array
{
/** @var NodeElement[] $labels */
$labels = $context->findAll('xpath', "//label[contains(text(), '$labelName')]");
$found = [];
foreach ($labels as $label) {
$inputName = $label->getAttribute('for');
foreach ($context->findAll('named', ['field', $inputName]) as $element) {
if (!in_array($element, $found)) {
array_push($found, $element);
}
}
}
return $found;
}
/**
* Checks that the page not contain a visible input field.
*
* @param string $fieldName the name of the input field
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible input field is found
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertFieldNotExists(string $fieldName): void
{
try {
$this->assertFieldExists($fieldName);
} catch (ExpectationException $e) {
return;
}
throw new ExpectationException("Input label '$fieldName' found", $this->getSession());
}
/**
* Checks that the page contains the given lines of text in the order specified.
*
* @Then I should see the following lines in order:
*
* @param TableNode $table a list of text lines to look for
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a line is not found, or is found out of order
* @throws InvalidArgumentException if the list of lines has more than one column
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertLinesInOrder(TableNode $table): void
{
if (count($table->getRow(0)) > 1) {
throw new InvalidArgumentException('Arguments must be a single-column list of items');
}
$session = $this->getSession();
$page = $session->getPage()->getText();
$lines = $table->getColumn(0);
$lastPosition = -1;
foreach ($lines as $line) {
$line = $this->storeContext->injectStoredValues($line);
$position = strpos($page, $line);
if ($position === false) {
throw new ExpectationException("Line '$line' was not found on the page", $session);
}
if ($position < $lastPosition) {
throw new ExpectationException("Line '$line' came before its expected predecessor", $session);
}
$lastPosition = $position;
}
}
/**
* This method will check if all the fields exists and visible in the current page.
*
* @Then /^I should see the following fields:$/
*
* @param TableNode $tableNode The id|name|title|alt|value of the input field
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if any of the fields is not visible in the page
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertPageContainsFields(TableNode $tableNode): void
{
foreach ($tableNode->getRowsHash() as $field => $value) {
$this->assertFieldExists($field);
}
}
/**
* This method will check if all the fields not exists or not visible in the current page.
*
* @Then /^I should not see the following fields:$/
*
* @param TableNode $tableNode The id|name|title|alt|value of the input field
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if any of the fields is visible in the page
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertPageNotContainsFields(TableNode $tableNode): void
{
foreach ($tableNode->getRowsHash() as $field => $value) {
$this->assertFieldNotExists($field);
}
}
/**
* Assert if the option exist/not exist in the select.
*
* @Then /^the (?P<option>.*?) option(?:|(?P<existence> does not?)) exists? in the (?P<select>.*?) select$/
*
* @param string $select The name of the select
* @param string $existence The status of the option item
* @param string $option The name of the option item
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException If the option does/doesn't exist as expected
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertSelectContainsOption(string $select, string $existence, string $option): void
{
$select = $this->fixStepArgument($select);
$option = $this->fixStepArgument($option);
$selectField = $this->assertFieldExists($select);
$opt = $selectField->find('named', ['option', $option]);
if ($existence && $opt) {
throw new ExpectationException("The option '$option' exist in the select", $this->getSession());
}
if (!$existence && !$opt) {
throw new ExpectationException("The option '$option' does not exist in the select", $this->getSession());
}
}
/**
* Assert if the options in the select match given options.
*
* @Then /^the "(?P<select>[^"]*)" select should only have the following option(?:|s):$/
*
* @param string $select The name of the select
* @param TableNode $tableNode the text of the options
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException when there is no option in the select
* @throws ExpectationException when the option(s) in the select not match the option(s) listed
* @throws InvalidArgumentException when no expected options listed in the test step
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This
* method does not pass closures, so if this happens, there is a
* problem with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a
* problem with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function assertSelectContainsExactOptions(string $select, TableNode $tableNode): void
{
if (count($tableNode->getRow(0)) > 1) {
throw new InvalidArgumentException('Arguments must be a single-column list of items');
}
$expectedOptTexts = array_map([$this->storeContext, 'injectStoredValues'], $tableNode->getColumn(0));
$select = $this->fixStepArgument($select);
$select = $this->storeContext->injectStoredValues($select);
$selectField = $this->assertFieldExists($select);
$actualOpts = $selectField->findAll('xpath', '//option');
if (count($actualOpts) == 0) {
throw new ExpectationException('No option found in the select', $this->getSession());
}
$actualOptTexts = array_map(function ($actualOpt) {
/* @var NodeElement $actualOpt */
return $actualOpt->getText();
}, $actualOpts);
if (count($actualOptTexts) > count($expectedOptTexts)) {
throw new ExpectationException('Select has more option then expected', $this->getSession());
}
if (count($actualOptTexts) < count($expectedOptTexts)) {
throw new ExpectationException('Select has less option then expected', $this->getSession());
}
if ($actualOptTexts != $expectedOptTexts) {
$intersect = array_intersect($actualOptTexts, $expectedOptTexts);
if (count($intersect) < count($expectedOptTexts)) {
throw new ExpectationException('Expecting ' . count($expectedOptTexts) . ' matching option(s), found ' . count($intersect), $this->getSession());
}
throw new ExpectationException('Options in select match expected but not in expected order', $this->getSession());
}
}
/**
* @noinspection PhpDocRedundantThrowsInspection exceptions are bubbling up from the waitFor's closure
*
* Asserts that the specified option is selected.
*
* @Then the :field drop down should have the :option selected
*
* @param string $field the select field
* @param string $option the option that should be selected in the select field
*
* @throws ExpectationException if the select dropdown doesn't exist in the view even after waiting
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a
* problem with the injectStoredValues method.
* @throws ElementNotFoundException if the option is not found in the dropdown even after waiting
* @throws ExpectationException if the option is not selected from the dropdown even after waiting
*/
public function assertSelectOptionSelected(string $field, string $option): void
{
/** @var NodeElement $selectField */
/** @noinspection PhpUnhandledExceptionInspection */
$selectField = Spinner::waitFor(function () use ($field) {
return $this->assertFieldExists($field);
});
$option = $this->storeContext->injectStoredValues($option);
/* @noinspection PhpUnhandledExceptionInspection */
Spinner::waitFor(function () use ($selectField, $option, $field) {
$optionField = $selectField->find('named', ['option', $option]);
if (null === $optionField) {
throw new ElementNotFoundException($this->getSession(), 'select option field', 'id|name|label|value', $option);
}
if (!$optionField->isSelected()) {
throw new ExpectationException('Select option field with value|text "' . $option . '" is not selected in the select "' . $field . '"', $this->getSession());
}
});
}
/**
* Sets a cookie.
*
* Note: you must request a page before trying to set a cookie, in order to set the domain.
*
* @When /^(?:|I )set the cookie "(?P<key>(?:[^"]|\\")*)" with value (?P<value>.+)$/
*
* @param string $key the name of the key to set
* @param string $value the value to set the cookie to
*
* @throws DriverException when the operation cannot be performed
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function setCookie(string $key, string $value): void
{
$this->getSession()->setCookie($key, $value);
}
/**
* Returns all cookies.
*
* @throws Exception if the operation failed
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return array key/value pairs of cookie name/value
*/
public function getCookies(): array
{
$driver = $this->assertSelenium2Driver('Get all cookies');
$cookies = [];
foreach ($driver->getWebDriverSession()->getAllCookies() as $cookie) {
$cookies[$cookie['name']] = urldecode($cookie['value']);
}
return $cookies;
}
/**
* Deletes a cookie.
*
* @When /^(?:|I )delete the cookie "(?P<key>(?:[^"]|\\")*)"$/
*
* @param string $key the name of the key to delete
*
* @throws DriverException when the operation cannot be performed
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function deleteCookie(string $key): void
{
$this->getSession()->setCookie($key, null);
}
/**
* Deletes all cookies.
*
* @When /^(?:|I )delete all cookies$/
*
* @throws DriverException when the operation cannot be performed
* @throws Exception if the operation failed
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function deleteCookies(): void
{
$this->assertSelenium2Driver('Delete all cookies')->getWebDriverSession()->deleteAllCookies();
}
/**
* Attaches a local file to field with specified id|name|label|value. This is used when running behat and
* browser session in different containers.
*
* @When /^(?:|I )attach the local file "(?P<path>[^"]*)" to "(?P<field>(?:[^"]|\\")*)"$/
*
* @param string $field The file field to select the file with
* @param string $path The local path of the file
*
* @throws DriverException when the operation cannot be performed
* @throws ElementNotFoundException if the field could not be found
* @throws UnsupportedDriverActionException if getWebDriverSession() is not supported by the current driver
*/
public function addLocalFileToField(string $path, string $field): void
{
$driver = $this->assertSelenium2Driver('Add local file to field');
$field = $this->fixStepArgument($field);
if ($this->getMinkParameter('files_path')) {
$fullPath = rtrim(
realpath($this->getMinkParameter('files_path')),
DIRECTORY_SEPARATOR
) . DIRECTORY_SEPARATOR . $path;
if (is_file($fullPath)) {
$path = $fullPath;
}
}
$tempZip = tempnam('', 'WebDriverZip');
$zip = new ZipArchive();
$zip->open($tempZip, ZipArchive::CREATE);
$zip->addFile($path, basename($path));
$zip->close();
/** @noinspection PhpUndefinedMethodInspection file() method annotation is missing from WebDriver\Session */
$remotePath = $driver->getWebDriverSession()->file([
'file' => base64_encode(file_get_contents($tempZip)),
]);
$this->attachFileToField($field, $remotePath);
unlink($tempZip);
}
/**
* @noinspection PhpDocRedundantThrowsInspection Exceptions bubble up from waitFor.
*
* {@inheritdoc}
*
* @throws ExpectationException if the value of the input does not match expected after the file is
* attached
*/
public function attachFileToField($field, $path): void
{
/* @noinspection PhpUnhandledExceptionInspection */
Spinner::waitFor(function () use ($field, $path) {
parent::attachFileToField($field, $path);
$session = $this->getSession();
$value = $session->getPage()->findField($field)->getValue();
if (!is_string($value)) {
throw new ExpectationException(
"The value of input $field is not a string. Maybe you specified the wrong field?",
$this->getSession()
);
}
// Workaround for browser's fake path stuff that obscures the directory of the attached file.
$fileParts = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($fileParts); // end() cannot take inline expressions, only variables.
if (strpos($value, $filename) === false) {
throw new ExpectationException("Value of $field is '$value', expected to contain '$filename'", $session);
}
});
}
/**
* Blurs (unfocuses) selected field.
*
* @When /^(?:I |)(?:blur|unfocus) (?:the |)"(?P<locator>[^"]+)"(?: field|)$/
*
* @param string $locator The field to blur
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified field does not exist
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a
* problem with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function blurField(string $locator): void
{
$this->wait->assertFieldExists($locator)->blur();
}
/**
* Focuses and blurs (unfocuses) the selected field.
*
* @When /^(?:I |)focus and (?:blur|unfocus) (?:the |)"(?P<locator>[^"]+)"(?: field|)$/
* @When /^(?:I |)toggle focus (?:on|of) (?:the |)"(?P<locator>[^"]+)"(?: field|)$/
*
* @param string $locator The field to focus and blur
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified field does not exist
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a
* problem with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function focusBlurField(string $locator): void
{
$this->focusField($locator);
$this->blurField($locator);
}
/**
* Focuses the selected field.
*
* @When /^(?:I |)focus (?:the |)"(?P<locator>[^"]+)"(?: field|)$/
*
* @param string $locator The the field to focus
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if the specified field does not exist
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a
* problem with the injectStoredValues method.
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function focusField(string $locator): void
{
$this->wait->assertFieldExists($locator)->focus();
}
/**
* Simulates hitting a keyboard key.
*
* @When /^(?:I |)(?:hit|press) (?:the |)"(?P<key>[^"]+)" key$/
*
* @param string $key The key on the keyboard
*
* @throws DriverException when the operation cannot be performed
* @throws InvalidArgumentException if $key is not recognized as a valid key
* @throws UnsupportedDriverActionException when operation not supported by the driver
*/
public function hitKey(string $key): void
{
if (!array_key_exists($key, self::$keyCodes)) {
throw new InvalidArgumentException("The key '$key' is not defined.");
}
$script = "jQuery.event.trigger({ type : 'keypress', which : '" . self::$keyCodes[$key] . "' });";
$this->getSession()->evaluateScript($script);
}
/**
* @noinspection PhpDocRedundantThrowsInspection exceptions are bubbling up from the waitFor's closure
*
* {@inheritdoc}
*
* This method overrides the base method to ensure that only visible & enabled buttons are pressed.
*
* @param string $locator button id, inner text, value or alt
* @param TraversableElement $context element on the page to which button belongs
*
* @throws DriverException when the operation cannot be performed
* @throws ExpectationException if a visible button field is not found
* @throws UnsupportedDriverActionException when operation not supported by the driver
* @throws ExpectationException if Button is found but not visible in the viewport
*/
public function pressButton($locator, TraversableElement $context = null)
{
/* @noinspection PhpUnhandledExceptionInspection */
Spinner::waitFor(function () use ($locator, $context) {
$button = $this->scrollToButton($locator, $context);
if ($button->getAttribute('disabled') === 'disabled') {
throw new ExpectationException("Unable to press disabled button '$locator'.", $this->getSession());
}
$this->assertNodeElementVisibleInViewport($button);
$button->press();
});
}
/**
* Asserts that all nodes have the specified attribute value.
*
* @param string $locator the attribute locator of the node element
* @param array $attributes A key value paid of the attribute and value the nodes should contain
* @param string $selector the selector to use to find the node
* @param int|null $occurrences the number of time the node element should be found
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException If the nodes attributes do not match
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function assertNodesHaveAttributeValues(
string $locator,
array $attributes,
string $selector = 'named',
int $occurrences = null
) {
/** @var NodeElement[] $links */
$nodes = $this->getSession()->getPage()->findAll($selector, $locator);
if (!count($nodes)) {
throw new ExpectationException("No node elements were found on the page using '$locator'", $this->getSession());
}
if (!is_null($occurrences) && count($nodes) !== $occurrences) {
throw new ExpectationException("Expected $occurrences nodes with '$locator' but found " . count($nodes), $this->getSession());
}
foreach ($nodes as $node) {
if (!$this->elementHasAttributeValues($node, $attributes)) {
throw new ExpectationException("Expected node with '$locator' but found " . print_r($node, true), $this->getSession());
}
}
}
/**
* @noinspection PhpDocRedundantThrowsInspection exceptions bubble up from waitFor.
*
* {@inheritdoc}
*
* Overrides the base method to support injecting stored values and restricting interaction to visible options.
*
* @param TraversableElement|null $context the context to find the option within. Defaults to entire page.
*
* @throws DriverException When the operation cannot be done
* @throws ElementNotFoundException when the option is not found in the select box
* @throws ExpectationException if a visible select was not found
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem with
* the injectStoredValues method.
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function selectOption($select, $option, TraversableElement $context = null): void
{
$select = $this->storeContext->injectStoredValues($select);
$option = $this->storeContext->injectStoredValues($option);
$this->wait->assertVisibleOptionField($select, $context)->selectOption($option);
}
/**
* Finds all the matching selects, radios or checkboxes on the page.
*
* @param string $locator the id|name|label|value|placeholder of the select, radio or checkbox
* @param TraversableElement|null $context the context to find the option field within. Defaults to entire page.
*
* @throws DriverException When the operation cannot be done
* @throws UnsupportedDriverActionException When operation not supported by the driver
*
* @return NodeElement[] all the matching selects, radios or checkboxes
*/
public function getOptionFields(string $locator, TraversableElement $context = null): array
{
$context = $context ?: $this->getSession()->getPage();
return array_filter(
$context->findAll('named', ['field', $locator]),
function (NodeElement $field) {
return $field->getTagName() == 'select' ||
in_array($field->getAttribute('type'), ['radio', 'checkbox']);
}
);
}
/**
* Finds the first matching select, radio or checkbox on the page.
*
* @Then I should see a :locator select
* @Then I should see a :locator radio
*
* @param string $locator the id|name|label|value|placeholder of the select, radio or checkbox
* @param TraversableElement|null $context the context to find the option field within. Defaults to entire page.
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException if a visible select was not found
* @throws UnsupportedDriverActionException When operation not supported by the driver
*
* @return NodeElement the select, radio or checkbox
*/
public function assertVisibleOptionField(string $locator, TraversableElement $context = null): NodeElement
{
foreach ($this->getOptionFields($locator, $context) as $field) {
if ($field->isVisible()) {
return $field;
}
}
throw new ExpectationException("No visible selects or radios for '$locator' were found", $this->getSession());
}
/**
* Asserts that a visible select exists with the specified option.
*
* @Then I should see a :locator select with an :option option
*
* @param string $field the id|name|label|value|placeholder of the select
* @param string $option the label of the select's option
* @param TraversableElement|null $context the context to find the option within. Defaults to entire page
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException if a visible select was not found
* @throws UnsupportedDriverActionException When operation not supported by the driver
* @throws ElementNotFoundException if the option was not found in the select
*
* @return NodeElement the option element
*/
public function assertVisibleOption(string $field, string $option, TraversableElement $context = null): NodeElement
{
$fieldElement = $this->assertVisibleOptionField($field, $context);
$optionElement = $fieldElement->find('named', ['option', $option]);
if (null === $optionElement) {
throw new ElementNotFoundException(
$this->getSession()->getDriver(),
'select option',
'value|text',
$option
);
}
return $optionElement;
}
/**
* Scrolls the window to the top, bottom, left, right (or any valid combination thereof) of the page body.
*
* @Given /^the page is scrolled to the (?P<whereToScroll>top|bottom)(?:(?P<useSmoothScroll> smoothly)|)$/
* @When /^(?:I |)scroll to the (?P<whereToScroll>[ a-z]+) of the page(?:(?P<useSmoothScroll> smoothly)|)$/
*
* @param string $whereToScroll The direction to scroll the page. Can be any valid combination of "top",
* "bottom", "left" and "right". e.g. "top", "top right", but not "top bottom"
* @param bool $useSmoothScroll use the smooth scrolling behavior if the browser supports it
*
* @throws DriverException When the operation cannot be done
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function scrollWindowToBody(string $whereToScroll, bool $useSmoothScroll = false): void
{
// horizontal scroll
$scrollHorizontal = 'window.scrollX';
if (strpos($whereToScroll, 'left') !== false) {
$scrollHorizontal = 0;
} elseif (strpos($whereToScroll, 'right') !== false) {
$scrollHorizontal = 'document.body.scrollWidth';
}
// vertical scroll
$scrollVertical = 'window.scrollY';
if (strpos($whereToScroll, 'top') !== false) {
$scrollVertical = 0;
} elseif (strpos($whereToScroll, 'bottom') !== false) {
$scrollVertical = 'document.body.scrollHeight';
}
$supportsSmoothScroll = $this->getSession()->evaluateScript("'scrollBehavior' in document.documentElement.style");
if ($useSmoothScroll && $supportsSmoothScroll) {
$this->getSession()->executeScript("window.scrollTo({top: $scrollVertical, left: $scrollHorizontal, behavior: 'smooth'})");
} else {
$this->getSession()->executeScript("window.scrollTo($scrollHorizontal, $scrollVertical)");
}
}
/**
* This overrides MinkContext::visit() to inject stored values into the URL.
*
* @see MinkContext::visit
*
* @param string $page the page to visit
*
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed, and
* they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
*/
public function visit($page): void
{
parent::visit($this->storeContext->injectStoredValues($page));
}
/**
* This overrides MinkContext::assertCheckboxChecked() to inject stored values into the locator.
*
* @param string $checkbox The the locator of the checkbox
*
* @throws ExpectationException if the check box is not checked
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed, and
* they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
*/
public function assertCheckboxChecked($checkbox): void
{
$checkbox = $this->storeContext->injectStoredValues($checkbox);
parent::assertCheckboxChecked($checkbox);
}
/**
* This overrides MinkContext::assertCheckboxNotChecked() to inject stored values into the locator.
*
* @param string $checkbox The the locator of the checkbox
*
* @throws ExpectationException if the check box is checked
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were passed, and
* they do not conform to its requirements. This method does not pass
* closures, so if this happens, there is a problem with the
* injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were passed.
* This should never happen. If it does, there is a problem with the
* injectStoredValues method.
*/
public function assertCheckboxNotChecked($checkbox): void
{
$checkbox = $this->storeContext->injectStoredValues($checkbox);
parent::assertCheckboxNotChecked($checkbox);
}
/**
* Check the radio button.
*
* @When I check radio button :label
*
* @param string $label the label of the radio button
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException if the radio button was not found on the page
* @throws ExpectationException if the radio button was on the page, but was not visible
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function ensureRadioButtonChecked($label): void
{
$this->wait->findRadioButton($label)->click();
}
/**
* Assert the radio button is checked.
*
* @Then /^the "(?P<label>(?:[^"]|\\")*)" radio button should be checked$/
*
* @param string $label the label of the radio button
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException when the radio button is not checked
* @throws ExpectationException if the radio button was not found on the page
* @throws ExpectationException if the radio button was on the page, but was not visible
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function assertRadioButtonChecked(string $label): void
{
if (!$this->findRadioButton($label)->isChecked()) {
throw new ExpectationException("Radio button \"$label\" is not checked, but it should be.", $this->getSession());
}
}
/**
* Assert the radio button is not checked.
*
* @Then /^the "(?P<label>(?:[^"]|\\")*)" radio button should not be checked$/
*
* @param string $label the label of the radio button
*
* @throws DriverException When the operation cannot be done
* @throws ExpectationException when the radio button is checked
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function assertRadioButtonNotChecked(string $label): void
{
if ($this->findRadioButton($label)->isChecked()) {
throw new ExpectationException("Radio button \"$label\" is checked, but it should not be.", $this->getSession());
}
}
/**
* Checks if a node has the specified attribute values.
*
* @param NodeElement $node the node to check the expected attributes against
* @param array $attributes an associative array of the expected attributes
*
* @throws DriverException When the operation cannot be done
* @throws UnsupportedDriverActionException When operation not supported by the driver
*
* @return bool true if the element has the specified attribute values, false if not
*/
public function elementHasAttributeValues(NodeElement $node, array $attributes): bool
{
foreach ($attributes as $name => $value) {
if ($node->getAttribute($name) != $value) {
return false;
}
}
return true;
}
/**
* Compares two Elements and determines which is "first".
*
* This is for use with usort (and similar) functions, for sorting a list of
* NodeElements by their coordinates. The typical use case is to determine
* the order of elements on a page as a viewer would perceive them.
*
* @param NodeElement $a one of the two NodeElements to compare
* @param NodeElement $b the other NodeElement to compare
*/
public function compareElementsByCoords(NodeElement $a, NodeElement $b): int
{
$driver = $this->getSession()->getDriver();
if (!($driver instanceof Selenium2Driver) || !method_exists($driver, 'getXpathBoundingClientRect')) {
// If not supported by driver, just return -1 so the keep the original sort.
return -1;
}
$aRect = $driver->getXpathBoundingClientRect($a->getXpath());
$bRect = $driver->getXpathBoundingClientRect($b->getXpath());
if ($aRect['top'] == $bRect['top']) {
return 0;
}
return ($aRect['top'] < $bRect['top']) ? -1 : 1;
}
/**
* Provides the directory that test artifacts should be stored to.
*
* This should be overridden when FlexibleMink is used in a project.
*
* @return string the fully qualified directory, with no trailing directory separator
*/
public function getArtifactsDir(): string
{
return realpath(__DIR__ . '/../../../../artifacts');
}
/**
* Waits for the page to be loaded.
*
* This does not wait for any particular javascript frameworks to be ready, it only waits for the DOM to be
* ready. This is done by waiting for the document.readyState to be "complete".
*
* @noinspection PhpDocRedundantThrowsInspection exceptions bubble up from waitFor.
*
* @throws ExpectationException if the page did not finish loading before the timeout expired
*/
public function waitForPageLoad(): void
{
/* @noinspection PhpUnhandledExceptionInspection throws ExpectationException, not Exception. */
Spinner::waitFor(function () {
$readyState = $this->getSession()->evaluateScript('document.readyState');
if ($readyState !== 'complete') {
throw new ExpectationException("Page is not loaded. Ready state is '$readyState'", $this->getSession());
}
});
}
/**
* Checks if a node Element is fully visible in the viewport.
*
* @param NodeElement $element the NodeElement to look for in the viewport
*
* @throws UnsupportedDriverActionException if driver does not support the requested action
* @throws Exception If cannot get the Web Driver
*/
public function nodeIsFullyVisibleInViewport(NodeElement $element): bool
{
$driver = $this->assertSelenium2Driver('Checks if a node Element is fully visible in the viewport.');
if (!$driver->isDisplayed($element->getXpath()) ||
count(($parents = $this->getAncestors($element, 'html'))) < 1
) {
return false;
}
$elementViewportRectangle = $this->getElementViewportRectangle($element);
foreach ($parents as $parent) {
if (!$parent->isVisible() ||
!$elementViewportRectangle->isContainedIn($this->getElementViewportRectangle($parent))
) {
return false;
}
}
return true;
}
/**
* Asserts that the node element is visible in the viewport.
*
* @param NodeElement $element element expected to be visble in the viewport
*
* @throws ExpectationException if the element was not found visible in the viewport
* @throws GenericException if the assertion did not pass before the timeout was exceeded
*/
public function assertNodeElementVisibleInViewport(NodeElement $element): void
{
if (!$this->nodeIsVisibleInViewport($element)) {
throw new ExpectationException('The following element was expected to be visible in viewport, but was not: ' . $element->getHtml(), $this->getSession());
}
}
/**
* Checks if a node Element is visible in the viewport.
*
* @param NodeElement $element The NodeElement to check for in the viewport
*
* @throws UnsupportedDriverActionException if driver does not support the requested action
* @throws Exception If cannot get the Web Driver
*/
public function nodeIsVisibleInViewport(NodeElement $element): bool
{
$driver = $this->assertSelenium2Driver('Checks if a node Element is visible in the viewport.');
$parents = $this->getAncestors($element, 'body');
// if the element is displayed, or it is detached from the DOM, it is not visible
if (!$driver->isDisplayed($element->getXpath()) || !$element->getParent()) {
return false;
}
$elementViewportRectangle = $this->getElementViewportRectangle($element);
foreach ($parents as $parent) {
if (!$elementViewportRectangle->overlaps($this->getElementViewportRectangle($parent))) {
return false;
}
}
return true;
}
/**
* Checks if a node Element is visible in the document.
*
* @param NodeElement $element NodeElement to to check for in the document
*
* @throws Exception If cannot get the Web Driver
* @throws UnsupportedDriverActionException If driver is not the selenium 2 driver
*/
public function nodeIsVisibleInDocument(NodeElement $element): bool
{
return $this->assertSelenium2Driver('Check if element is displayed')->isDisplayed($element->getXpath());
}
/**
* Get a rectangle that represents the location of a NodeElements viewport.
*
* @param NodeElement $element nodeElement to get the viewport of
*
* @throws UnsupportedDriverActionException when operation not supported by the driver
*
* @return Rectangle representing the viewport
*/
public function getElementViewportRectangle(NodeElement $element): Rectangle
{
$driver = $this->assertSelenium2Driver('Get XPath Element Dimensions');
$dimensions = $driver->getXpathElementDimensions($element->getXpath());
$YScrollBarWidth = $dimensions['clientWidth'] > 0 ? $dimensions['width'] - $dimensions['clientWidth'] : 0;
$XScrollBarHeight = $dimensions['clientHeight'] > 0 ? $dimensions['height'] - $dimensions['clientHeight'] : 0;
return new Rectangle(
$dimensions['left'],
$dimensions['top'],
$dimensions['right'] - $YScrollBarWidth,
$dimensions['bottom'] - $XScrollBarHeight
);
}
/**
* Step to assert that the specified element is not covered.
*
* @param string $identifier element Id to find the element used in the assertion
*
* @throws ExpectationException if element is found to be covered by another
*
* @Then the :identifier element should not be covered by another
*/
public function assertElementIsNotCoveredByIdStep(string $identifier): void
{
/** @var NodeElement $element */
$element = $this->getSession()->getPage()->find('css', "#$identifier");
$this->assertElementIsNotCovered($element);
}
/**
* Asserts that the specified element is not covered by another element.
*
* Keep in mind that at the moment, this method performs a check in a square area so this may not work
* correctly with elements of different shapes.
*
* @param NodeElement $element the element to assert that is not covered by something else
* @param int $leniency percent of leniency when performing each pixel check
*
* @throws ExpectationException if element is found to be covered by another
* @throws InvalidArgumentException the threshold provided is outside of the 0-100 range accepted
*/
public function assertElementIsNotCovered(NodeElement $element, int $leniency = 20): void
{
if ($leniency < 0 || $leniency > 99) {
throw new InvalidArgumentException('The leniency provided is outside of the 0-50 range accepted.');
}
$xpath = $element->getXpath();
/** @var array $coordinates */
$coordinates = $this->getSession()->evaluateScript(
<<<JS
return document.evaluate("$xpath", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
.singleNodeValue.getBoundingClientRect();
JS
);
$width = $coordinates['width'] - 1;
$height = $coordinates['height'] - 1;
$right = $coordinates['right'];
$bottom = $coordinates['bottom'];
// X and Y are the starting points.
$x = $coordinates['left'];
$y = $coordinates['top'];
$xSpacing = ($width * ($leniency / 100)) ?: 1;
$ySpacing = ($height * ($leniency / 100)) ?: 1;
$expected = $element->getOuterHtml();
/**
* Asserts that each point checked on the row isn't covered by an element that doesn't match the expected.
*
* @param int $x starting X position
* @param int $y starting Y position
* @param int $xLimit width of element
*
* @throws ExpectationException if element is found to be covered by another in the row specified
*/
$assertRow = function ($x, $y, $xLimit) use ($expected, $xSpacing) {
while ($x < $xLimit) {
$found = $this->getSession()->evaluateScript("return document.elementFromPoint($x, $y).outerHTML;");
if (strpos($expected, $found) === false) {
throw new ExpectationException('An element is above an interacting element.', $this->getSession());
}
$x += $xSpacing;
}
};
// Go through each row in the square area found.
while ($y < $bottom) {
$assertRow($x, $y, $right);
$y += $ySpacing;
}
}
/**
* Asserts that the current driver is Selenium 2 in preparation for performing an action that requires it.
*
* @param string $operation the operation that you will attempt to perform that requires
* the Selenium 2 driver
*
* @throws UnsupportedDriverActionException if the current driver is not Selenium 2
*/
public function assertSelenium2Driver(string $operation): Selenium2Driver
{
$driver = $this->getSession()->getDriver();
if (!($driver instanceof Selenium2Driver)) {
throw new UnsupportedDriverActionException($operation . ' is not supported by %s', $driver);
}
return $driver;
}
/**
* Finds the first visible element in the given set, prioritizing elements in the viewport but scrolling to one if
* necessary.
*
* @param NodeElement[] $elements the elements to look for
*
* @return NodeElement|null the first visible element
*/
public function scrollWindowToFirstVisibleElement(array $elements): ?NodeElement
{
foreach ($elements as $field) {
if ($field->isVisible()) {
return $field;
}
}
// No fields are visible on the page, so try scrolling to each field and see if they become visible that way.
foreach ($elements as $field) {
$this->scrollWindowToElement($field);
if ($field->isVisible()) {
$ret = $field;
break;
}
}
return isset($ret) ? $ret : null;
}
/**
* Scrolls the window to the given element.
*
* @param NodeElement $element the element to scroll to
*/
public function scrollWindowToElement(NodeElement $element): void
{
$xpath = json_encode($element->getXpath());
$this->getSession()->evaluateScript(
<<<JS
document.evaluate($xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
.singleNodeValue
.scrollIntoView(false)
JS
);
}
/**
* Locate the radio button by label.
*
* @param string $label the Label of the radio button
*
* @throws ExpectationException if the radio button was not found on the page
* @throws ExpectationException if the radio button was on the page, but was not visible
* @throws DriverException When the operation cannot be done
* @throws InvalidArgumentException If injectStoredValues incorrectly believes one or more closures were
* passed, and they do not conform to its requirements. This method
* does not pass closures, so if this happens, there is a problem
* with the injectStoredValues method.
* @throws ReflectionException If injectStoredValues incorrectly believes one or more closures were
* passed. This should never happen. If it does, there is a problem
* with the injectStoredValues method.
* @throws UnsupportedDriverActionException When operation not supported by the driver
*/
public function findRadioButton(string $label): NodeElement
{
$label = $this->storeContext->injectStoredValues($label);
$this->fixStepArgument($label);
$radioButtons = $this->getSession()->getPage()->findAll('named', ['radio', $label]);
if (!$radioButtons) {
throw new ExpectationException('Radio Button was not found on the page', $this->getSession());
}
usort($radioButtons, [$this, 'compareElementsByCoords']);
$radioButton = $this->scrollWindowToFirstVisibleElement($radioButtons);
if (!$radioButton) {
throw new ExpectationException('No Visible Radio Button was found on the page', $this->getSession());
}
return $radioButton;
}
/**
* Returns all ancestors of the specified node element.
*
* @param NodeElement $node the node element to fetch ancestors for
* @param string|null $stopAt html tag to stop at. This node will NOT be included in the returned list.
*
* @return NodeElement[]
*/
private function getAncestors(NodeElement $node, string $stopAt = null): array
{
$nodes = [];
while (($node = $node->getParent()) instanceof NodeElement) {
if (strcasecmp($node->getTagName(), $stopAt) === 0) {
break;
}
$nodes[] = $node;
}
return $nodes;
}
}
|
{
"content_hash": "0aa2fe15452ce5388f6afea414a3bba5",
"timestamp": "",
"source": "github",
"line_count": 2053,
"max_line_length": 172,
"avg_line_length": 44.904042864101314,
"alnum_prop": 0.6054584110730247,
"repo_name": "Medology/FlexibleMink",
"id": "42e7ecf467326921e3ef5a19cbc186f58969eae2",
"size": "92188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Medology/Behat/Mink/FlexibleContext.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "51571"
},
{
"name": "HTML",
"bytes": "29416"
},
{
"name": "PHP",
"bytes": "266452"
},
{
"name": "Shell",
"bytes": "2977"
}
],
"symlink_target": ""
}
|
namespace Svetsoft.Nmea
{
/// <summary>
/// Represents a sentence of the NMEA specification for depth below keel.
/// </summary>
public class DbkSentence : NmeaSentence
{
/// <summary>
/// Creates a new instance of the <see cref="DbkSentence" /> class.
/// </summary>
/// <param name="sentence">The sentence to create the instance from.</param>
public DbkSentence(string sentence)
: base(sentence)
{
Parse();
}
/// <summary>
/// Returns the depth in feet.
/// </summary>
public Distance FeetDepth { get; internal set; }
/// <summary>
/// Returns the depth in meters.
/// </summary>
public Distance MetersDepth { get; internal set; }
/// <summary>
/// Returns the depth in fathoms.
/// </summary>
public Distance FathomsDepth { get; internal set; }
/// <summary>
/// Parses the fields of this sentence to its <see cref="DbkSentence" /> equivalent.
/// </summary>
private void Parse()
{
FeetDepth = GetDistance(0);
MetersDepth = GetDistance(2);
FathomsDepth = GetDistance(4);
}
}
}
|
{
"content_hash": "622fdfb1171480c271e5f15cbadcac8f",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 96,
"avg_line_length": 30.046511627906977,
"alnum_prop": 0.5247678018575851,
"repo_name": "Svetsoft/Svetsoft.Nmea",
"id": "85d6bed59352070417de0734ffd680b96bc8ffbd",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Svetsoft.Nmea.Shared/Sentences/DbkSentence.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "206141"
}
],
"symlink_target": ""
}
|
// This file was generated using Parlex's cpp_generator
#include "THIS_FUNC.hpp"
#include "plange_grammar.hpp"
#include "parlex/detail/document.hpp"
#include "EXPRESSION.hpp"
#include "IC.hpp"
plc::THIS_FUNC::field_1_t_1_t plc::THIS_FUNC::field_1_t_1_t::build(parlex::detail::node const * b, parlex::detail::document::walk & w) {
auto const & children = b->children;
auto v0 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<parlex::detail::document::text<literal_0x5B_t>>::build(&*children[1], w);
auto v2 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[2], w);
auto v3 = parlex::detail::document::element<erased<EXPRESSION>>::build(&*children[3], w);
auto v4 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[4], w);
auto v5 = parlex::detail::document::element<parlex::detail::document::text<literal_0x5D_t>>::build(&*children[5], w);
return field_1_t_1_t(std::move(v0), std::move(v1), std::move(v2), std::move(v3), std::move(v4), std::move(v5));
}
plc::THIS_FUNC plc::THIS_FUNC::build(parlex::detail::ast_node const & n) {
static auto const * b = state_machine().behavior;
parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() };
auto const & children = b->children;
auto v0 = parlex::detail::document::element<parlex::detail::document::text<literal_this_func_t>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<std::optional<field_1_t_1_t>>::build(&*children[1], w);
return THIS_FUNC(std::move(v0), std::move(v1));
}
parlex::detail::state_machine const & plc::THIS_FUNC::state_machine() {
static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().THIS_FUNC));
return result;
}
|
{
"content_hash": "e3ff7696319dc94b3c4809ad029993b9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 154,
"avg_line_length": 53.42857142857143,
"alnum_prop": 0.6914438502673796,
"repo_name": "dlin172/Plange",
"id": "47fa0f50178c34f52f74ae69283385bd698bd4c0",
"size": "1872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/plc/src/document/THIS_FUNC.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "302"
},
{
"name": "C++",
"bytes": "1357953"
},
{
"name": "CMake",
"bytes": "27256"
},
{
"name": "CSS",
"bytes": "3771"
},
{
"name": "Makefile",
"bytes": "203"
},
{
"name": "PHP",
"bytes": "48923"
},
{
"name": "Python",
"bytes": "5829"
},
{
"name": "Shell",
"bytes": "230"
},
{
"name": "SourcePawn",
"bytes": "97692"
}
],
"symlink_target": ""
}
|
<!doctype html>
<html>
<head>
<style>
* {
box-sizing: border-box;
}
html,
body,
<ngw-root></ngw-root> {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
font-family: 'Helvetica', 'Verdana', sans-serif;
font-weight: 400;
font-display: optional;
color: #444;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-box-align: stretch;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
background: #ececec;
}
.header {
width: 100%;
height: 56px;
color: #FFF;
background: #3F51B5;
position: fixed;
font-size: 20px;
box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 2px 9px 1px rgba(0, 0, 0, 0.12), 0 4px 2px -2px rgba(0, 0, 0, 0.2);
padding: 16px 16px 0 16px;
will-change: transform;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-box-align: stretch;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
-webkit-align-content: center;
-ms-flex-line-pack: center;
align-content: center;
-webkit-transition: -webkit-transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s;
transition: -webkit-transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s;
transition: transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s;
transition: transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s, -webkit-transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s;
z-index: 1000;
}
.header .headerButton {
width: 24px;
height: 24px;
margin-right: 16px;
text-indent: -30000px;
overflow: hidden;
opacity: 0.54;
-webkit-transition: opacity 0.333s cubic-bezier(0, 0, 0.21, 1);
transition: opacity 0.333s cubic-bezier(0, 0, 0.21, 1);
border: none;
outline: none;
cursor: pointer;
}
.header #butRefresh {
background: url(/images/ic_refresh_white_24px.svg) center center no-repeat;
}
.header #butAdd {
background: url(/images/ic_add_white_24px.svg) center center no-repeat;
}
.header__title {
font-weight: 400;
font-size: 20px;
margin: 0;
-webkit-box-flex: 1;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
</style>
<script>
var module = {id: null};
</script>
<script src="/zone.js" defer></script>
<script src="/app.js" defer></script>
<script defer>
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/worker-basic.js').then(() => {
console.log('Angular service worker installed')
}, err => {
console.error('Angular service worker error:', err);
});
}
</script>
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
<ngw-root>
</ngw-root>
</body>
</html>
|
{
"content_hash": "cf2610a6b7aeee058b3b910b4189fa97",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 127,
"avg_line_length": 29.397058823529413,
"alnum_prop": 0.580040020010005,
"repo_name": "alxhub/ng2-weather-pwa",
"id": "1da85ff42c1be2610df217baece956ee4afb6540",
"size": "3998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8445"
},
{
"name": "HTML",
"bytes": "6596"
},
{
"name": "JavaScript",
"bytes": "58"
},
{
"name": "TypeScript",
"bytes": "16828"
}
],
"symlink_target": ""
}
|
import socket
import sys
# A UDP server
# Set up a UDP server
UDPSock = socket.socket(socket.AF_INET6,socket.SOCK_DGRAM)
# Listen on port 21567
# (to all IP addresses on this system)
listen_addr = ("",5000)
UDPSock.bind(listen_addr)
# Report on all data packets received and
# where they came from in each case (as this is
# UDP, each may be from a different source and it's
# up to the server to sort this out!)
while True:
data,addr = UDPSock.recvfrom(1500)
sys.stdout.write(data)
|
{
"content_hash": "9c4985298481bf9cf3e7e2e364706ff6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 58,
"avg_line_length": 25.15,
"alnum_prop": 0.7137176938369781,
"repo_name": "xpgdk/net430",
"id": "0039c7a9146ed1d1c2f63eee60df91aa829bcfd2",
"size": "522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tun-test/log-server.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "760"
},
{
"name": "C",
"bytes": "126200"
},
{
"name": "C++",
"bytes": "449"
},
{
"name": "Objective-C",
"bytes": "227"
},
{
"name": "Python",
"bytes": "522"
}
],
"symlink_target": ""
}
|
package org.spongepowered.mod.event;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.event.FMLEvent;
import org.spongepowered.api.service.event.EventManager;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.util.event.Event;
import org.spongepowered.api.util.event.Subscribe;
import org.spongepowered.mod.SpongeMod;
import org.spongepowered.mod.asm.util.ASMEventListenerFactory;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
@NonnullByDefault
public class SpongeEventManager implements EventManager {
private final Map<Object, List<PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event>>> forgePluginHandlerMap =
Maps.newHashMap();
private final SpongeEventBus eventBus = new SpongeEventBus();
@SuppressWarnings("unchecked")
@Override
public void register(Object plugin, Object o) {
if (forgePluginHandlerMap.containsKey(o)) {
return;
}
List<PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event>> localForgeListeners =
Lists.newArrayList();
Map<Method, Subscribe> annotationMap = getAnnotationMap(o);
for (Entry<Method, Subscribe> entry : annotationMap.entrySet()) {
Class<?>[] parameters = entry.getKey().getParameterTypes();
if (parameters.length != 1) {
throw new IllegalArgumentException("Handler methods may only have 1 input parameter");
}
@Nullable
Class<?> eventType = parameters[0];
@Nullable
Class<?> implementingEvent = EventRegistry.getImplementingClass(eventType);
if (implementingEvent == null) {
implementingEvent = eventType;
}
if (implementingEvent == null) {
SpongeMod.instance.getLogger().error("Null event type, registration failed");
} else if (net.minecraftforge.fml.common.eventhandler.Event.class.isAssignableFrom(implementingEvent)) {
// Forge events
EventListener<net.minecraftforge.fml.common.eventhandler.Event> listener =
ASMEventListenerFactory.getListener(EventListener.class, o, entry.getKey());
PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event> priorityListener =
new PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event>(entry.getValue().order(), listener);
eventBus.add(implementingEvent, entry.getValue(), priorityListener);
localForgeListeners.add(priorityListener);
} else if (!FMLEvent.class.isAssignableFrom(implementingEvent)) {
// ^ Events extending FMLEvent need to be handled on a per-plugin basis. Current code for that is in SpongePluginHandler.
SpongeMod.instance.getLogger().warn("Unknown event type " + eventType.getCanonicalName() + ", registration failed");
}
}
forgePluginHandlerMap.put(o, localForgeListeners);
}
@Override
public void unregister(Object o) {
@Nullable
List<PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event>> pluginForgeListeners = forgePluginHandlerMap.remove(o);
if (pluginForgeListeners == null) {
return;
}
for (PriorityEventListener<net.minecraftforge.fml.common.eventhandler.Event> listener : pluginForgeListeners) {
eventBus.remove(listener);
}
}
@Override
public boolean post(Event spongeEvent) {
if (spongeEvent instanceof net.minecraftforge.fml.common.eventhandler.Event) {
// TODO: We need to figure out if this event needs to go on FML or Forge busses
FMLCommonHandler.instance().bus().post((net.minecraftforge.fml.common.eventhandler.Event) spongeEvent);
} else {
SpongeMod.instance.getLogger().info("Event not a sub-classes of forge Event or BaseEvent");
return false;
}
return true;
}
private Map<Method, Subscribe> getAnnotationMap(Object o) {
Map<Method, Subscribe> map = new HashMap<Method, Subscribe>();
Set<? extends Class<?>> superClasses = TypeToken.of(o.getClass()).getTypes().rawTypes();
for (Method method : o.getClass().getMethods()) {
for (Class<?> clazz : superClasses) {
try {
Method localMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
if (localMethod.isAnnotationPresent(Subscribe.class)) {
Subscribe annotation = localMethod.getAnnotation(Subscribe.class);
map.put(method, annotation);
break;
}
} catch (NoSuchMethodException e) {
;
}
}
}
return map;
}
}
|
{
"content_hash": "3b0a41b5ca86fcaea37e377612111843",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 141,
"avg_line_length": 41.661417322834644,
"alnum_prop": 0.6558306558306558,
"repo_name": "SRPlatin/Sponge",
"id": "1c811970682db897df06849455d131533543c042",
"size": "6542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/spongepowered/mod/event/SpongeEventManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "377249"
},
{
"name": "Shell",
"bytes": "78"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codepath.apps.restclienttemplate"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".TwitterApp"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".LoginActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="@string/intent_host"
android:scheme="@string/intent_scheme" />
</intent-filter>
</activity>
<activity android:name=".TimelineActivity" />
<activity android:name=".ComposeActivity" />
<activity android:name=".DetailActivity" />
<activity android:name=".ProfileActivity"></activity>
</application>
</manifest>
|
{
"content_hash": "edc5bdf2fa2c1c06856862a608cc6928",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 80,
"avg_line_length": 38.785714285714285,
"alnum_prop": 0.6071209330877839,
"repo_name": "maria93101/Twitter",
"id": "12c2f4b71f652cd23ab36b273131c94f94ffc4b6",
"size": "1629",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/AndroidManifest.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "50351"
}
],
"symlink_target": ""
}
|
<?php
namespace Beech\Workflow\Domain\Repository;
/* *
* This script belongs to beechit/mrmaks. *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License, or (at your *
* option) any later version. *
* *
* This script is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- *
* TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser *
* General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with the script. *
* If not, see http://www.gnu.org/licenses/lgpl.html *
* *
* The TYPO3 project - inspiring people to share! *
* */
use Beech\Workflow\Domain\Model\Workflow;
use TYPO3\Flow\Annotations as Flow;
/**
* A repository for Workflows
* Readed from YAML files
*
* @Flow\Scope("singleton")
*/
class WorkflowRepository {
/**
* @var \TYPO3\Flow\Configuration\ConfigurationManager
* @Flow\Inject
*/
protected $configurationManager;
/**
* @var array
*/
protected $_parsed_settings;
/**
* Find all in YAML defined workflows
*
* @return array
*/
public function findAll() {
if ($this->_parsed_settings === NULL) {
$this->_parsed_settings = array();
foreach ($this->configurationManager->getConfiguration('Workflows') as $workflow => $settings) {
$this->_parsed_settings[] = new Workflow($workflow, $settings);
}
}
return $this->_parsed_settings;
}
/**
* Find Workflow by trigger
*
* @param $action
* @param $object
* @return array
*/
public function findAllByTrigger($action, $object) {
$className = get_class($object);
$workflows = array();
foreach ($this->findAll() as $workflow) {
if ($workflow->matchTriggers($action, $object)) {
$workflows[] = $workflow;
}
}
return $workflows;
}
}
?>
|
{
"content_hash": "e7e38fd0248e11734842eb01f57847c5",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 99,
"avg_line_length": 31.176470588235293,
"alnum_prop": 0.509811320754717,
"repo_name": "beechit/MisterMaks-EHRM",
"id": "19ed622ed2c5399bd36651dc3ece7cdaf65239f1",
"size": "2650",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Packages/Beech/Beech.Workflow/Classes/Beech/Workflow/Domain/Repository/WorkflowRepository.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "498009"
},
{
"name": "HTML",
"bytes": "380010"
},
{
"name": "Handlebars",
"bytes": "2682"
},
{
"name": "JavaScript",
"bytes": "2430494"
},
{
"name": "PHP",
"bytes": "1149992"
},
{
"name": "Ruby",
"bytes": "848"
},
{
"name": "Shell",
"bytes": "3933"
}
],
"symlink_target": ""
}
|
@class modsearch;
@class moditempicture;
@class moditemattributes;
@interface visearchman:UIView<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
-(void)changesearchstate:(appsearchstate)_newsearchstate;
-(void)trashresult:(modsearchresult*)_result;
@property(strong, nonatomic)modsearch *search;
@property(weak, nonatomic)UICollectionView *collection;
@property(weak, nonatomic)UIImageView *gradient;
@property(nonatomic)appsearchstate searchstate;
@end
@interface visearchmanheader:UICollectionReusableView<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
-(void)config:(visearchman*)_searchman;
@property(weak, nonatomic)visearchman *searchman;
@property(weak, nonatomic)modsearchresult *searchresult;
@property(weak, nonatomic)moditempicture *picture;
@property(weak, nonatomic)UICollectionView *collection;
@property(weak, nonatomic)UIImageView *image;
@property(weak, nonatomic)UIImageView *gradient;
@end
@interface visearchmanheaderaction:UICollectionViewCell
-(void)actiondetail;
-(void)actionlike:(BOOL)_liked;
@property(weak, nonatomic)UIImageView *image;
@end
@interface visearchmanfooter:UICollectionReusableView
@end
@interface visearchmancel:UICollectionViewCell
-(void)config:(visearchman*)_searchman index:(NSInteger)_index;
@property(weak, nonatomic)visearchman *searchman;
@property(weak, nonatomic)moditemattributes *attributes;
@property(weak, nonatomic)UIView *innerview;
@end
|
{
"content_hash": "ea2ed5940764428f6384ae3f4a32fb4a",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 143,
"avg_line_length": 29.372549019607842,
"alnum_prop": 0.8317757009345794,
"repo_name": "turingcorp/motors",
"id": "db16302146581030ae017b4cf4313521867c3ca0",
"size": "1518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Motors/sourceteq/source/vi/visearchman.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "355731"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ch.codebulb.crudfaces</groupId>
<artifactId>CrudFaces</artifactId>
<version>0.2-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<!-- attach sources for JitPack distribution -->
<!-- as in https://github.com/jitpack/maven-simple/blob/master/pom.xml -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<bottom><![CDATA[Copyright © {inceptionYear}–{currentYear}, <a href="http://www.codebulb.ch">codebulb.ch<a>. All rights reserved.]]></bottom>
<!-- copy additional javadoc folder resources -->
<docfilessubdirs>true</docfilessubdirs>
</configuration>
<!-- attach JavaDoc for JitPack distribution -->
<!-- as in https://github.com/jitpack/maven-simple/blob/master/pom.xml -->
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>
|
{
"content_hash": "61325348d5faf12e9e1119056465ebdd",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 204,
"avg_line_length": 40.77333333333333,
"alnum_prop": 0.5183126226291694,
"repo_name": "codebulb/crudfaces",
"id": "6597aa306ad1cfa924f1b6b0043f558c6306fb9c",
"size": "3058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8262"
},
{
"name": "Java",
"bytes": "159183"
},
{
"name": "JavaScript",
"bytes": "21394"
}
],
"symlink_target": ""
}
|
<?php
namespace phpDocumentor\Transformer\Writer;
use phpDocumentor\Translator\Translator;
/**
* All writers that have items that should be translated should implement this interface
*/
interface Translatable
{
/**
* Returns an instance of the object responsible for translating content.
*
* @return Translator
*/
public function getTranslator();
/**
* Sets a new object capable of translating strings on this writer.
*
* @param Translator $translator
*
* @return void
*/
public function setTranslator(Translator $translator);
}
|
{
"content_hash": "8aaf2b3de11fa6b65ed81c52f3a77a29",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 88,
"avg_line_length": 21.5,
"alnum_prop": 0.6810631229235881,
"repo_name": "PatidarWeb/phpDocumentor2",
"id": "ae072ef0e18d1e8d44253cdc29246ea922e5d545",
"size": "825",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/phpDocumentor/Transformer/Writer/Translatable.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27975"
},
{
"name": "JavaScript",
"bytes": "8222"
},
{
"name": "Makefile",
"bytes": "4917"
},
{
"name": "PHP",
"bytes": "1024009"
},
{
"name": "Python",
"bytes": "10284"
},
{
"name": "Shell",
"bytes": "1193"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using CorpusExplorer.Sdk.Action.Properties;
using CorpusExplorer.Sdk.Addon;
using CorpusExplorer.Sdk.Model;
using CorpusExplorer.Sdk.Utils.DataTableWriter.Abstract;
using CorpusExplorer.Sdk.ViewModel;
namespace CorpusExplorer.Sdk.Action
{
public class KwitSelectAction : IAction
{
public string Action => "kwit-n";
public string Description => "kwit-n [LAYER1] [LAYER2] [PRE] [POST] [WORDS] - Like kwit (but you can specificate the range [PRE] and [POST] the match - e.g. [PRE] = 3)";
public void Execute(Selection selection, string[] args, AbstractTableWriter writer)
{
if (args == null || args.Length < 5)
return;
var queries = new List<string>(args);
queries.RemoveAt(0);
queries.RemoveAt(0);
var pre = int.Parse(queries[0]);
queries.RemoveAt(0);
var post = int.Parse(queries[0]);
queries.RemoveAt(0);
var vm = new TextFlowSearchWithRangeSelectionViewModel
{
Selection = selection,
Layer1Displayname = args[0],
Layer2Displayname = args[1],
LayerQueryPhrase = queries,
AutoJoin = true,
HighlightCooccurrences = false,
Pre = pre,
Post = post
};
vm.Execute();
writer.WriteDirectThroughStream(Convert(vm.DiscoveredConnections.ToArray()));
}
private string Convert(Tuple<string, int, string>[] connections)
{
if (connections == null || connections.Length == 0)
return string.Empty;
var stb = new StringBuilder();
stb.Append("digraph G {\r\n");
var max = connections.Select(x => x.Item2).Max();
foreach (var connection in connections)
{
if (connection.Item2 == 0)
continue;
var a = Filter(connection.Item1);
var b = Filter(connection.Item3);
var p = (double)connection.Item2 / max * 25d;
if (p < 1)
p = 1;
var w = (int)p;
stb.AppendLine($"\t\"{a}\" -> \"{b}\" [ label=\"{connection.Item2}\" penwidth={p.ToString(CultureInfo.CurrentCulture).Replace(",", ".")} weight={w} ];");
}
stb.Append("\r\n}\r\n");
return stb.ToString();
}
private string Filter(object content)
{
return content.ToString().Replace("\"", "''");
}
}
}
|
{
"content_hash": "7615bb016d845cbf17e1ce8d0e160ee8",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 173,
"avg_line_length": 28.795180722891565,
"alnum_prop": 0.6179916317991632,
"repo_name": "notesjor/CorpusExplorer-Port-R",
"id": "88ce62087d5dd5646d87c4f294451c9731aef7eb",
"size": "2392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Action/CorpusExplorer.Sdk.Action/KwitSelectAction.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "26697"
}
],
"symlink_target": ""
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_01) on Thu Mar 07 20:40:24 CET 2013 -->
<title>com.tyrlib2.graphics.terrain</title>
<meta name="date" content="2013-03-07">
<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="com.tyrlib2.graphics.terrain";
}
//-->
</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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-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="../../../../com/tyrlib2/graphics/scene/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/tyrlib2/graphics/text/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/tyrlib2/graphics/terrain/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.tyrlib2.graphics.terrain</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/tyrlib2/graphics/terrain/Terrain.html" title="class in com.tyrlib2.graphics.terrain">Terrain</a></td>
<td class="colLast">
<div class="block">Takes care of rendering terrain</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/tyrlib2/graphics/terrain/TerrainTexture.html" title="class in com.tyrlib2.graphics.terrain">TerrainTexture</a></td>
<td class="colLast">
<div class="block">This class represents a texture used for rendering terrain.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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-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="../../../../com/tyrlib2/graphics/scene/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/tyrlib2/graphics/text/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/tyrlib2/graphics/terrain/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"content_hash": "5ce4086055e1adc1e7e1c75c402f051b",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 161,
"avg_line_length": 36.53191489361702,
"alnum_prop": 0.6117258784702,
"repo_name": "TyrfingX/TyrLib",
"id": "2989e940eb1f940147f3d9b8abe7718a927ba8f0",
"size": "5151",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "com.tyrfing.games.tyrlib3.android/doc/com/tyrlib2/graphics/terrain/package-summary.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34365"
},
{
"name": "HTML",
"bytes": "8978949"
},
{
"name": "Java",
"bytes": "3998822"
}
],
"symlink_target": ""
}
|
from __future__ import unicode_literals
import socket
import select
from mock import patch, MagicMock as Mock, PropertyMock, call
from soco import discover
from soco import config
from soco.discovery import any_soco, by_name
IP_ADDR = '192.168.1.101'
TIMEOUT = 5
class TestDiscover:
def test_discover(self, monkeypatch):
# Create a fake socket, whose data is always a certain string
monkeypatch.setattr('socket.socket', Mock())
sock = socket.socket.return_value
sock.recvfrom.return_value = (
b'SERVER: Linux UPnP/1.0 Sonos/26.1-76230 (ZPS3)', [IP_ADDR]
) # (data, # address)
# Each time gethostbyname is called, it gets a different value
monkeypatch.setattr('socket.gethostbyname',
Mock(side_effect=['192.168.1.15', '192.168.1.16']))
# Stop getfqdn from working, to avoud network access
monkeypatch.setattr('socket.getfqdn', Mock())
# prevent creation of soco instances
monkeypatch.setattr('soco.config.SOCO_CLASS', Mock())
# Fake return value for select
monkeypatch.setattr(
'select.select', Mock(return_value = ([sock], 1, 1)))
# set timeout
TIMEOUT = 2
discover(timeout=TIMEOUT)
# 9 packets in total should be sent (3 to default, 3 to
# 192.168.1.15 and 3 to 192.168.1.15)
assert sock.sendto.call_count == 9
# select called with the relevant timeout
select.select.assert_called_with(
[sock, sock, sock], [], [], min(TIMEOUT, 0.1))
# SoCo should be created with the IP address received
config.SOCO_CLASS.assert_called_with(IP_ADDR)
# Now test include_visible parameter. include_invisible=True should
# result in calling SoCo.all_zones etc
# Reset gethostbyname, to always return the same value
monkeypatch.setattr('socket.gethostbyname',
Mock(return_value='192.168.1.15'))
config.SOCO_CLASS.return_value = Mock(
all_zones='ALL', visible_zones='VISIBLE')
assert discover(include_invisible=True) == 'ALL'
assert discover(include_invisible=False) == 'VISIBLE'
# if select does not return within timeout SoCo should not be called
# at all
# simulate no data being returned within timeout
select.select.return_value = (0, 1, 1)
discover(timeout=1)
# Check no SoCo instance created
config.SOCO_CLASS.assert_not_called
def test_by_name():
"""Test the by_name method"""
devices = set()
for name in ("fake", "non", "Kitchen"):
mymock = Mock(player_name=name)
devices.add(mymock)
# The mock we want to find is the last one
mock_to_be_found = mymock
# Patch out discover and test
with patch("soco.discovery.discover") as discover_:
discover_.return_value = devices
# Test not found
device = by_name("Living Room")
assert device is None
discover_.assert_called_once_with()
# Test found
device = by_name("Kitchen")
assert device is mock_to_be_found
discover_.assert_has_calls([call(), call()])
|
{
"content_hash": "99a0c6cab911d1fc4f76603f1f895b68",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 76,
"avg_line_length": 36.632183908045974,
"alnum_prop": 0.631628490743646,
"repo_name": "dajobe/SoCo",
"id": "274c7745c517718203bd7ad3b4835b6f30a2db85",
"size": "3211",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/test_discovery.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "168"
},
{
"name": "Makefile",
"bytes": "368"
},
{
"name": "Python",
"bytes": "640813"
},
{
"name": "Shell",
"bytes": "342"
}
],
"symlink_target": ""
}
|
<ROOT>
<data>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2008</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2003</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2002</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2002</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2001</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2001</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2000</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">2000</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">1999</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">1999</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">1998</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Bulgaria</field>
<field name="Year">1998</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Czech Republic</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Denmark</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ecuador</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2008</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Finland</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">France</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Germany</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">18.4540741668525</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Germany</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">5.68225</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Hungary</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Hungary</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Hungary</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Hungary</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Hungary</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">6.32052532909599</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">124.272</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">3.56432892679188</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">171.948</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2003</field>
<field name="Unit">Mil. USD</field>
<field name="Value">5.9899112093875</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">India</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">152.77</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">2003</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">2002</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">2001</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">2000</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">1999</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">1998</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">1997</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">1996</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ireland</field>
<field name="Year">1995</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Kazakhstan</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Kazakhstan</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Kazakhstan</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2008</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2003</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2002</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2002</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2001</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2001</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2000</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">2000</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1999</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1999</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1998</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1998</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1997</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Lithuania</field>
<field name="Year">1997</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2008</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Mexico</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">1.7</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">1</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">108.3</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2002</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2002</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2000</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Poland</field>
<field name="Year">2000</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2003</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2002</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2002</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2001</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2001</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2000</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">2000</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1999</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1999</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1998</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1998</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1997</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1997</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1996</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1996</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1995</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Portugal</field>
<field name="Year">1995</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2004</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Spain</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2009</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2008</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2007</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2005</field>
<field name="Unit">Mil. USD</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Sweden</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2009</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2008</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2007</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2005</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2004</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">Ukraine</field>
<field name="Year">2003</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">0</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">2006</field>
<field name="Unit">Mil. USD</field>
<field name="Value">9.5144928425107</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">2006</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">3.426</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">1997</field>
<field name="Unit">Mil. USD</field>
<field name="Value">13.9153527482508</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">1997</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">5</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">1996</field>
<field name="Unit">Mil. USD</field>
<field name="Value">27.1468537369879</field>
<field name="Value Footnotes"></field>
</record>
<record>
<field name="Country or Area">United Kingdom</field>
<field name="Year">1996</field>
<field name="Unit">THOUSAND UNITS</field>
<field name="Value">5</field>
<field name="Value Footnotes"></field>
</record>
</data>
</ROOT>
|
{
"content_hash": "933f96560f2dbe486eb54cfd34a46ad7",
"timestamp": "",
"source": "github",
"line_count": 1229,
"max_line_length": 64,
"avg_line_length": 41.26118795768918,
"alnum_prop": 0.5003352395977125,
"repo_name": "danagilliann/un_data_api",
"id": "23df55d22d7a66990099b254627fbb84ebedbd6b",
"size": "50710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/un_data_xml_files/UNSD/Industrial Commodity Statistics Database/[4] Metal products, machinery and equipment/[47] Radio, television and communication equipment and apparatus/Cathode-ray tubes (excl. TV tubes, television camera tubes, image converters or intensifiers, other photo-cathode tubes).xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Cucumber",
"bytes": "6335"
},
{
"name": "HTML",
"bytes": "9812"
},
{
"name": "Ruby",
"bytes": "114838"
}
],
"symlink_target": ""
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>file-watcher-extension</groupId>
<artifactId>file-watcher-extension</artifactId>
<version>3.1.2</version>
<name>File Watcher Extension</name>
<description>Inspects and monitors configured files and directories</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
<target.dir>${project.build.directory}/FileWatcher</target.dir>
<skipITs>true</skipITs>
</properties>
<dependencies>
<dependency>
<groupId>com.appdynamics</groupId>
<artifactId>machine-agent</artifactId>
<version>3.7.11</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.appdynamics</groupId>
<artifactId>appd-exts-commons</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.appdynamics.extensions.workbench.WorkbenchServerLauncher</Main-Class>
<Implementation-Title>v${project.version} Build Date ${maven.build.timestamp}</Implementation-Title>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<configuration>
<target>
<mkdir dir="${target.dir}"/>
<copy todir="${target.dir}">
<fileset dir="src/main/resources/conf" includes="monitor.xml"/>
<fileset dir="src/main/resources/conf" includes="config.yml"/>
<fileset dir="${project.basedir}" includes="LICENSE.txt"/>
<fileset dir="${project.basedir}" includes="NOTICE.txt"/>
<fileset dir="src/main/resources/conf" includes="APMDashboard.json"/>
<fileset dir="src/main/resources/conf" includes="SIMDashboard.json"/>
</copy>
<copy todir="${target.dir}">
<fileset dir="${build.directory}" includes="${project.artifactId}.${project.packaging}"/>
</copy>
<zip destfile="${target.dir}-${project.version}.zip">
<zipfileset dir="${target.dir}" filemode="755" prefix="FileWatcher/"/>
</zip>
<delete dir="${target.dir}"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<artifactId>maven-scm-plugin</artifactId>
<version>1.8.1</version>
<configuration>
<tag>${project.artifactId}-${project.version}</tag>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-integration-test-source</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/integration-test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<skipITs>${skipITs}</skipITs>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>github-maven-repo</id>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<url>https://github.com/Appdynamics/maven-repo/raw/master/releases</url>
</repository>
</repositories>
<scm>
<connection>scm:git:https://github.com/Appdynamics/AppDynamics-File-Watcher-Extension.git</connection>
</scm>
</project>
|
{
"content_hash": "fe06d6038b7a03b88c3ce528ced0c423",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 140,
"avg_line_length": 42.93981481481482,
"alnum_prop": 0.46102425876010783,
"repo_name": "Appdynamics/FileWatcher-extension",
"id": "99313ead5945322a97a0aaa60bb55642432d50cc",
"size": "9275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "71907"
}
],
"symlink_target": ""
}
|
'''
This script outputs only unique allele of one population relative to another.
I use this approach to remove ancestral variation (named as parental below) from a population of interest.
inputfile:
CHROM POS sample1 sample2 sample3 sample4
chr_1 1 A N A A
chr_1 2 C C C T
chr_1 3 C T N N
outputfile:
CHROM POS sample3 sample4
chr_1 2 N T
command:
python find_popSpecificAlleles.py -i test.input -o test.out -s "sample3,sample4" -p "sample1,sample2"
contact Dmytro Kryvokhyzha dmytro.kryvokhyzha@evobio.eu
'''
############################# modules #############################
import calls # my custom module
import re
############################# options #############################
parser = calls.CommandLineParser()
parser.add_argument('-i', '--input', help = 'name of the input file', type=str, required=True)
parser.add_argument('-o', '--output', help = 'name of the output file', type=str, required=True)
parser.add_argument('-s', '--sample', help = 'Specify the sample group', type=str, required=True)
parser.add_argument('-p', '--parental', help = 'Specify a parental groups', type=str, required=True)
args = parser.parse_args()
# check if samples names are given and if all sample names are present in a header
sNames = calls.checkSampleNames(args.sample, args.input)
pNames = calls.checkSampleNames(args.parental, args.input)
############################# program #############################
counter = 0
print('Opening the file...')
with open(args.input) as datafile:
header_words = datafile.readline().split()
# index samples
sIndex = calls.indexSamples(sNames, header_words)
pIndex = calls.indexSamples(pNames, header_words)
# create lists for output
sNames = calls.selectSamples(sIndex, header_words)
# make output header
print('Creating the output file...')
fileoutput = open(args.output, 'w')
sampGroups = '\t'.join(str(w) for w in header_words[0:2]+sNames)
fileoutput.write("%s\n" % sampGroups)
for line in datafile:
words = line.split()
chr_pos = words[0:2]
# select samples
sGT = calls.selectSamples(sIndex, words)
pGT = calls.selectSamples(pIndex, words)
# compare genotypes
pGTset = set(pGT)
if "N" in pGTset: # remove N from parental group
pGTset.remove("N")
sGPprint = []
for sgt in sGT:
if sgt not in pGTset and sgt != "N" and pGTset:
sGPprint.append(sgt)
else:
sGPprint.append("N")
# make output
if not calls.all_missing(sGPprint):
chr_posP = '\t'.join(str(el) for el in chr_pos)
sGPprintP = '\t'.join(str(el) for el in sGPprint)
fileoutput.write('%s\t%s\n' % (chr_posP, sGPprintP))
# track progress
counter += 1
if counter % 1000000 == 0:
print str(counter), "lines processed"
datafile.close()
fileoutput.close()
print('Done!')
|
{
"content_hash": "9547426a8e71f2e5d3800eb65d87f6dc",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 106,
"avg_line_length": 29,
"alnum_prop": 0.6367119470567747,
"repo_name": "evodify/genotype-files-manipulations",
"id": "b9cfbe499735a16541f9f53280b59679da6a6cae",
"size": "2894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "find_popSpecificAlleles_in_callsTab.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "9570"
},
{
"name": "Python",
"bytes": "279298"
}
],
"symlink_target": ""
}
|
namespace v8 {
namespace internal {
namespace compiler {
class StateValuesIteratorTest : public GraphTest {
public:
StateValuesIteratorTest() : GraphTest(3) {}
Node* StateValuesFromVector(NodeVector* nodes) {
int count = static_cast<int>(nodes->size());
return graph()->NewNode(
common()->StateValues(count, SparseInputMask::Dense()), count,
count == 0 ? nullptr : &(nodes->front()));
}
};
TEST_F(StateValuesIteratorTest, SimpleIteration) {
NodeVector inputs(zone());
const int count = 10;
for (int i = 0; i < count; i++) {
inputs.push_back(Int32Constant(i));
}
Node* state_values = StateValuesFromVector(&inputs);
int i = 0;
for (StateValuesAccess::TypedNode node : StateValuesAccess(state_values)) {
EXPECT_THAT(node.node, IsInt32Constant(i));
i++;
}
EXPECT_EQ(count, i);
}
TEST_F(StateValuesIteratorTest, EmptyIteration) {
NodeVector inputs(zone());
Node* state_values = StateValuesFromVector(&inputs);
bool empty = true;
for (auto node : StateValuesAccess(state_values)) {
USE(node);
empty = false;
}
EXPECT_TRUE(empty);
}
TEST_F(StateValuesIteratorTest, NestedIteration) {
NodeVector inputs(zone());
int count = 0;
for (int i = 0; i < 8; i++) {
if (i == 2) {
// Single nested in index 2.
NodeVector nested_inputs(zone());
for (int j = 0; j < 8; j++) {
nested_inputs.push_back(Int32Constant(count++));
}
inputs.push_back(StateValuesFromVector(&nested_inputs));
} else if (i == 5) {
// Double nested at index 5.
NodeVector nested_inputs(zone());
for (int j = 0; j < 8; j++) {
if (j == 7) {
NodeVector doubly_nested_inputs(zone());
for (int k = 0; k < 2; k++) {
doubly_nested_inputs.push_back(Int32Constant(count++));
}
nested_inputs.push_back(StateValuesFromVector(&doubly_nested_inputs));
} else {
nested_inputs.push_back(Int32Constant(count++));
}
}
inputs.push_back(StateValuesFromVector(&nested_inputs));
} else {
inputs.push_back(Int32Constant(count++));
}
}
Node* state_values = StateValuesFromVector(&inputs);
int i = 0;
for (StateValuesAccess::TypedNode node : StateValuesAccess(state_values)) {
EXPECT_THAT(node.node, IsInt32Constant(i));
i++;
}
EXPECT_EQ(count, i);
}
TEST_F(StateValuesIteratorTest, TreeFromVector) {
int sizes[] = {0, 1, 2, 100, 5000, 30000};
TRACED_FOREACH(int, count, sizes) {
JSOperatorBuilder javascript(zone());
MachineOperatorBuilder machine(zone());
JSGraph jsgraph(isolate(), graph(), common(), &javascript, nullptr,
&machine);
// Generate the input vector.
NodeVector inputs(zone());
for (int i = 0; i < count; i++) {
inputs.push_back(Int32Constant(i));
}
// Build the tree.
StateValuesCache builder(&jsgraph);
Node* values_node = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
nullptr);
// Check the tree contents with vector.
int i = 0;
for (StateValuesAccess::TypedNode node : StateValuesAccess(values_node)) {
EXPECT_THAT(node.node, IsInt32Constant(i));
i++;
}
EXPECT_EQ(inputs.size(), static_cast<size_t>(i));
}
}
TEST_F(StateValuesIteratorTest, TreeFromVectorWithLiveness) {
int sizes[] = {0, 1, 2, 100, 5000, 30000};
TRACED_FOREACH(int, count, sizes) {
JSOperatorBuilder javascript(zone());
MachineOperatorBuilder machine(zone());
JSGraph jsgraph(isolate(), graph(), common(), &javascript, nullptr,
&machine);
// Generate the input vector.
NodeVector inputs(zone());
for (int i = 0; i < count; i++) {
inputs.push_back(Int32Constant(i));
}
// Generate the input liveness.
BitVector liveness(count, zone());
for (int i = 0; i < count; i++) {
if (i % 3 == 0) {
liveness.Add(i);
}
}
// Build the tree.
StateValuesCache builder(&jsgraph);
Node* values_node = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
&liveness);
// Check the tree contents with vector.
int i = 0;
for (StateValuesAccess::iterator it =
StateValuesAccess(values_node).begin();
!it.done(); ++it) {
if (liveness.Contains(i)) {
EXPECT_THAT(it.node(), IsInt32Constant(i));
} else {
EXPECT_EQ(it.node(), nullptr);
}
i++;
}
EXPECT_EQ(inputs.size(), static_cast<size_t>(i));
}
}
TEST_F(StateValuesIteratorTest, BuildTreeIdentical) {
int sizes[] = {0, 1, 2, 100, 5000, 30000};
TRACED_FOREACH(int, count, sizes) {
JSOperatorBuilder javascript(zone());
MachineOperatorBuilder machine(zone());
JSGraph jsgraph(isolate(), graph(), common(), &javascript, nullptr,
&machine);
// Generate the input vector.
NodeVector inputs(zone());
for (int i = 0; i < count; i++) {
inputs.push_back(Int32Constant(i));
}
// Build two trees from the same data.
StateValuesCache builder(&jsgraph);
Node* node1 = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
nullptr);
Node* node2 = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
nullptr);
// The trees should be equal since the data was the same.
EXPECT_EQ(node1, node2);
}
}
TEST_F(StateValuesIteratorTest, BuildTreeWithLivenessIdentical) {
int sizes[] = {0, 1, 2, 100, 5000, 30000};
TRACED_FOREACH(int, count, sizes) {
JSOperatorBuilder javascript(zone());
MachineOperatorBuilder machine(zone());
JSGraph jsgraph(isolate(), graph(), common(), &javascript, nullptr,
&machine);
// Generate the input vector.
NodeVector inputs(zone());
for (int i = 0; i < count; i++) {
inputs.push_back(Int32Constant(i));
}
// Generate the input liveness.
BitVector liveness(count, zone());
for (int i = 0; i < count; i++) {
if (i % 3 == 0) {
liveness.Add(i);
}
}
// Build two trees from the same data.
StateValuesCache builder(&jsgraph);
Node* node1 = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
&liveness);
Node* node2 = builder.GetNodeForValues(
inputs.size() == 0 ? nullptr : &(inputs.front()), inputs.size(),
&liveness);
// The trees should be equal since the data was the same.
EXPECT_EQ(node1, node2);
}
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
{
"content_hash": "5d064236c328bfb39a0ad9c94fc3c38a",
"timestamp": "",
"source": "github",
"line_count": 224,
"max_line_length": 80,
"avg_line_length": 30.008928571428573,
"alnum_prop": 0.6077060398690866,
"repo_name": "youtube/cobalt_sandbox",
"id": "c24b2f2d979a166632144de3d105b294200d4106",
"size": "7161",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "third_party/v8/test/unittests/compiler/state-values-utils-unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package org.jzy3d.bridge.awt;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import org.jzy3d.bridge.BufferedPanel;
public abstract class DoubleBufferedPanelAWT extends Panel implements BufferedPanel{
public abstract void draw(Graphics g);
/**********************************************************************/
public void paint(Graphics g){
if(mustInit())
initBuffer();
if(buffer!=null){
super.paint(buffer);
draw(buffer);
g.drawImage(offscreen,0,0,this);
}
}
public void update(Graphics g){
paint(g);
}
/**********************************************************************/
private void initBuffer(){
Dimension dim = getSize();
if(dim!=null){
offscreen = createImage(dim.width, dim.height);
buffer = offscreen.getGraphics();
}
}
private boolean mustInit(){
// case of non existing offscreen image
if(offscreen==null)
return true;
// case of image size change
if(offscreen.getHeight(null)!=getSize().height || offscreen.getWidth(null)!=getSize().width)
return true;
return false;
}
/**********************************************************************/
private Image offscreen = null;
private Graphics buffer = null;
private static final long serialVersionUID = 6735935224474752355L;
}
|
{
"content_hash": "ab53e3306d30ea6d5ef0ee0e710b98fe",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 94,
"avg_line_length": 23.051724137931036,
"alnum_prop": 0.5916230366492147,
"repo_name": "jzy3d/jzy3d-api-0.8.4",
"id": "ec088e11604b19814b2650daa870cc08c1165e80",
"size": "1337",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/bridge/org/jzy3d/bridge/awt/DoubleBufferedPanelAWT.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1407148"
}
],
"symlink_target": ""
}
|
using System.Web;
using System.Web.Mvc;
namespace Onyx.Authorization
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
|
{
"content_hash": "e4e0daff198dc355106a1c4c7d66ac13",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 80,
"avg_line_length": 20.846153846153847,
"alnum_prop": 0.6605166051660517,
"repo_name": "darocha/AuthorizationServer",
"id": "0ec9ea75090337a49e3e7f77b489cde524d6c70b",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OnyxAuthorizationServer/App_Start/FilterConfig.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "C#",
"bytes": "220960"
},
{
"name": "CSS",
"bytes": "316"
},
{
"name": "JavaScript",
"bytes": "33913"
}
],
"symlink_target": ""
}
|
<?php
namespace Arnapou\Toolbox\Mail\Swift;
class MessageText extends Message {
public function __construct($subject = null, $body = null) {
parent::__construct($subject, $body, 'text/plain', 'utf-8');
}
}
|
{
"content_hash": "e682d39846338d2b97bb6559c280904f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 62,
"avg_line_length": 16.615384615384617,
"alnum_prop": 0.6759259259259259,
"repo_name": "arnapou/toolbox",
"id": "988b6d4ee4fa1672b77a6626cd87039887c70d57",
"size": "452",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Arnapou/Toolbox/Mail/Swift/MessageText.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "665974"
}
],
"symlink_target": ""
}
|
package com.communote.server.core.external;
import java.util.Collection;
import com.communote.common.converter.Converter;
import com.communote.common.util.Pair;
import com.communote.server.api.core.blog.BlogAccessException;
import com.communote.server.api.core.blog.BlogNotFoundException;
import com.communote.server.api.core.common.NotFoundException;
import com.communote.server.api.core.security.AuthorizationException;
import com.communote.server.model.blog.Blog;
import com.communote.server.model.external.ExternalObject;
/**
* Management functions for the external objects
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public interface ExternalObjectManagement {
/**
* Assign an external object to a topic. If the external object is already assigned to the topic
* nothing will happen. If it is assigned to another topic an exception will be thrown. If it is
* not assigned it is created, the provided properties are added and it is assigned to the
* topic.
*
* @param blogId
* the ID of the blog to assign the external object to
* @param externalObject
* object describing the external object to assign
* @return the assigned external object
* @throws BlogNotFoundException
* in case the blog was not found
* @throws BlogAccessException
* in case the user is not a manager of the blog
* @throws ExternalObjectAlreadyAssignedException
* in case the external object is assigned to another blog than the provided one
* @throws ExternalSystemNotConfiguredException
* in case the externalSystemId of the external object does not belong to a
* registered or active external object source. A source is considered active if it
* provides a valid configuration.
* @throws TooManyExternalObjectsPerTopicException
* in case there are already assignments for the external source and topic and the
* configuration does not allow more assignments
*/
public ExternalObject assignExternalObject(Long blogId, ExternalObject externalObject)
throws BlogNotFoundException, BlogAccessException,
ExternalObjectAlreadyAssignedException, TooManyExternalObjectsPerTopicException,
ExternalSystemNotConfiguredException;
/**
* Assign or update a collection of external objects. If one of the provided external objects is
* already assigned to the blog it will be updated. If it is not assigned it will be added. The
* update works as {@link #updateExternalObject(Long, ExternalObject)} and the assign like
* {@link #assignExternalObject(Long, ExternalObject)}
*
* @param blogId
* the ID of the blog to assign the external objects to
* @param externalObjects
* objects describing the external objects to assign or update. To find an existing
* external object the external ID and the external system ID members are used if set
* otherwise the ID member is used.
* @throws BlogNotFoundException
* in case the blog was not found
* @throws BlogAccessException
* in case the user is not a manager of the blog
* @throws ExternalObjectAlreadyAssignedException
* in case one of the external objects is assigned to another blog than the provided
* one
* @throws ExternalSystemNotConfiguredException
* in case the externalSystemId of the external object does not belong to a
* registered or active external object source. A source is considered active if it
* provides a valid configuration.
* @throws TooManyExternalObjectsPerTopicException
* in case the configuration does not allow that many assignments
*/
public void assignOrUpdateExternalObjects(Long blogId,
Collection<ExternalObject> externalObjects) throws BlogNotFoundException,
BlogAccessException, ExternalObjectAlreadyAssignedException,
TooManyExternalObjectsPerTopicException, ExternalSystemNotConfiguredException;
/**
* Get an external object which is identified by the given ID and is assigned to the given
* topic.
*
* @param topicId
* the ID of the topic
* @param externalObjectId
* the internal ID of the external object
* @param converter
* the converter to transform the external object in the result object
* @return the converted result or null if the external object does not exist
* @throws BlogNotFoundException
* in case the topic does not exist
* @throws BlogAccessException
* in case the current user has no access to the given topic
*/
public <T> T getExternalObject(Long topicId, Long externalObjectId,
Converter<Pair<Blog, ExternalObject>, T> converter)
throws BlogNotFoundException, BlogAccessException;
/**
* <p>
* Return the external objects that are assigned to the given blog. The properties will not be
* loaded. Use the property management to get them.
* </p>
*
* @param blogId
* the ID of the blog
* @return the external objects of the topic. The collection will be empty if the blog has no
* external objects.
* @throws BlogNotFoundException
* in case the blog does not exist
* @throws BlogAccessException
* in case the current user has no read access to the blog
*/
public java.util.Collection<ExternalObject> getExternalObjects(Long blogId)
throws BlogNotFoundException, BlogAccessException;
/**
* <p>
* Return whether a given blog has external objects.
* </p>
*
* @param blogId
* the ID of the blog
* @return true if there is at least one external object, false otherwise
* @throws BlogNotFoundException
* in case the blog does not exist
* @throws BlogAccessException
* in case the current user has no read access to the blog
*/
public boolean hasExternalObjects(Long blogId) throws BlogNotFoundException,
BlogAccessException;
/**
* Check if a external object is assigned to a blog
*
* @param blogId
* the ID of the blog the external object is checked for beeing assigned to
* @param externalSystemId
* the ID of the external system
* @param externalObjectId
* the ID that identifies the external object within the external system
* @return true if the object is assigned, false otherwise
* @throws BlogAccessException
* in case the current user has no read access to the blog
* @throws BlogNotFoundException
* in case there is no blog for the given ID
*/
public boolean isExternalObjectAssigned(Long blogId, String externalSystemId,
String externalObjectId) throws BlogAccessException,
BlogNotFoundException;
/**
* Register an external object source. After registering a source external objects with the ID
* of the source can be linked to topics.
*
* @param source
* the source to register
* @throws ExternalObjectSourceAlreadyExistsException
* in case there is already a source with the same ID
*/
public void registerExternalObjectSource(ExternalObjectSource source)
throws ExternalObjectSourceAlreadyExistsException;
/**
* <p>
* Remove the external object with the given ID. If the removed external object is the last of
* the external system, the blog access rights added for that external system will be removed
* too.
* </p>
*
* @param externalObjectId
* the ID of the external object to remove
* @throws BlogAccessException
* in case the current user is not manager of the blog
* @throws NotFoundException
* in case the external object does not exist
*/
public void removeExternalObject(Long externalObjectId) throws BlogAccessException,
NotFoundException;
/**
* Remove an external object from a blog. If the removed external object is the last of the
* external system, the blog access rights added for that external system will be removed too.
*
* @param blogId
* ID of the blog
* @param externalSystemId
* identifier of the external system
* @param externalObjectId
* identifier of the external object in the external system
* @throws BlogNotFoundException
* in case the blog does not exist
* @throws BlogAccessException
* in case the current user is not manager of the blog
*/
public void removeExternalObject(Long blogId, String externalSystemId, String externalObjectId)
throws BlogNotFoundException, BlogAccessException;
/**
* <p>
* Remove the external object from the blog it is assigned to. If the removed external object is
* the last of the external system, the blog access rights added for that external system will
* be removed too.
* </p>
* <p>
* Similar to the 'trusted' methods of BlogRightsManagement this method requires that the
* current user is client manager.
* </p>
*
* @param externalObjectId
* ID of the external object
* @throws NotFoundException
* in case the external object does not exist
* @throws AuthorizationException
* in case the current user is not client manager
*/
public void removeExternalObjectTrusted(Long externalObjectId)
throws NotFoundException, AuthorizationException;
/**
* Replace the external objects assigned to a blog with the provided ones. This method works
* like {@link #assignOrUpdateExternalObjects(Long, Collection)} but additionally removes any
* assigned external object that is not in the provided external objects.
*
* @param blogId
* the ID of the blog whose external objects should be replaced
* @param externalObjects
* the new external objects to replace the existing with
* @throws BlogNotFoundException
* in case the blog does not exist
* @throws BlogAccessException
* in case the current user is not manager of the blog
* @throws ExternalObjectAlreadyAssignedException
* in case one of the external objects is assigned to another blog than the provided
* one
* @throws ExternalSystemNotConfiguredException
* @throws TooManyExternalObjectsPerTopicException
*/
public void replaceExternalObjects(Long blogId,
Collection<ExternalObject> externalObjects) throws BlogNotFoundException,
BlogAccessException, ExternalObjectAlreadyAssignedException,
TooManyExternalObjectsPerTopicException, ExternalSystemNotConfiguredException;
/**
* Remove an external object source that was registered with
* {@link #registerExternalObjectSource(ExternalObjectSource)}. If the source was not registered
* the call is ignored
*
* @param source
* the source to remove
*/
public void unregisterExternalObjectSource(ExternalObjectSource source);
/**
* <p>
* Update an existing external object. This covers modification of the name and the properties.
* The properties handling is as follows: If a property key and group combination does not
* exist, the property is created. If the property key and group combination exists, the value
* is updated. In case the value is null, the property is removed.
* </p>
*
* @param blogId
* the ID of the blog the external object is assigned to
* @param externalObject
* object with details about the external object which are used to resolve the
* assigned object and update its data. To find the existing external object the
* external ID and the external system ID members are used if set otherwise the ID
* member is used.
* @return the updated external object
* @throws BlogNotFoundException
* in case the blog does not exist
* @throws BlogAccessException
* in case the current user is not manager of the blog
* @throws NotFoundException
* in case the external object does not exist
* @throws ExternalObjectAlreadyAssignedException
* in case the external object is already assigned to another blog than the provided
* one
*/
public ExternalObject updateExternalObject(Long blogId, ExternalObject externalObject)
throws BlogNotFoundException, BlogAccessException, NotFoundException,
ExternalObjectAlreadyAssignedException;
}
|
{
"content_hash": "295f7fcae538b7ddfcc6680246630784",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 100,
"avg_line_length": 47.494773519163765,
"alnum_prop": 0.6550509867214438,
"repo_name": "Communote/communote-server",
"id": "d8e6ebcd64074b9ca782a6fd522f68852748c697",
"size": "13631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "communote/persistence/src/main/java/com/communote/server/core/external/ExternalObjectManagement.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "272"
},
{
"name": "CSS",
"bytes": "294265"
},
{
"name": "HTML",
"bytes": "26978"
},
{
"name": "Java",
"bytes": "13692073"
},
{
"name": "JavaScript",
"bytes": "2460010"
},
{
"name": "PLSQL",
"bytes": "4134"
},
{
"name": "PLpgSQL",
"bytes": "262702"
},
{
"name": "Rich Text Format",
"bytes": "30964"
},
{
"name": "Shell",
"bytes": "274"
}
],
"symlink_target": ""
}
|
class OAuth2AccessTokenFetcher;
class Profile;
namespace base {
class Time;
}
namespace policy {
class UserCloudPolicyManager;
// The UserPolicySigninService tracks when user signin/signout actions occur and
// initializes/shuts down the UserCloudPolicyManager as required. This class is
// not used on ChromeOS because UserCloudPolicyManager initialization is handled
// via LoginUtils, since it must happen before profile creation.
class UserPolicySigninService
: public ProfileKeyedService,
public OAuth2AccessTokenConsumer,
public content::NotificationObserver {
public:
// Creates a UserPolicySigninService associated with the passed |profile|.
UserPolicySigninService(Profile* profile, UserCloudPolicyManager* manager);
virtual ~UserPolicySigninService();
// content::NotificationObserver implementation.
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// OAuth2AccessTokenConsumer implementation.
virtual void OnGetTokenSuccess(const std::string& access_token,
const base::Time& expiration_time) OVERRIDE;
virtual void OnGetTokenFailure(const GoogleServiceAuthError& error) OVERRIDE;
private:
// Initializes the UserCloudPolicyManager to reflect the currently-signed-in
// user.
void ConfigureUserCloudPolicyManager();
// Fetches an OAuth token to allow the cloud policy service to register with
// the cloud policy server.
void RegisterCloudPolicyService();
// Weak pointer to the profile this service is associated with.
Profile* profile_;
content::NotificationRegistrar registrar_;
scoped_ptr<OAuth2AccessTokenFetcher> oauth2_access_token_fetcher_;
// Weak pointer to the UserCloudPolicyManager (allows dependency injection
// for tests).
UserCloudPolicyManager* manager_;
DISALLOW_COPY_AND_ASSIGN(UserPolicySigninService);
};
} // namespace policy
#endif // CHROME_BROWSER_POLICY_USER_POLICY_SIGNIN_SERVICE_H_
|
{
"content_hash": "0b4233bb951fecf6872bba0eac2f6b34",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 80,
"avg_line_length": 34.898305084745765,
"alnum_prop": 0.7620203982515784,
"repo_name": "junmin-zhu/chromium-rivertrail",
"id": "0db2a552b4786cb57aa83b1fb06ade94717063a0",
"size": "2651",
"binary": false,
"copies": "3",
"ref": "refs/heads/v8-binding",
"path": "chrome/browser/policy/user_policy_signin_service.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75806807"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "145161929"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "1546515"
},
{
"name": "JavaScript",
"bytes": "18675242"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "6981387"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "926245"
},
{
"name": "Python",
"bytes": "8088373"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3239"
},
{
"name": "Shell",
"bytes": "1513486"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
}
|
namespace ABI44_0_0reanimated {
std::weak_ptr<jsi::Value> StoreUser::getWeakRef(jsi::Runtime &rt) {
const std::lock_guard<std::recursive_mutex> lock(storeUserData->storeMutex);
if (storeUserData->store.count(identifier) == 0) {
storeUserData->store[identifier] =
std::vector<std::shared_ptr<jsi::Value>>();
}
std::shared_ptr<jsi::Value> sv =
std::make_shared<jsi::Value>(rt, jsi::Value::undefined());
storeUserData->store[identifier].push_back(sv);
return sv;
}
StoreUser::StoreUser(
std::shared_ptr<Scheduler> s,
const RuntimeManager &runtimeManager)
: scheduler(s) {
storeUserData = runtimeManager.storeUserData;
identifier = storeUserData->ctr++;
}
StoreUser::~StoreUser() {
int id = identifier;
std::shared_ptr<Scheduler> strongScheduler = scheduler.lock();
if (strongScheduler != nullptr) {
std::shared_ptr<StaticStoreUser> sud = storeUserData;
#ifdef ONANDROID
jni::ThreadScope::WithClassLoader([&] {
strongScheduler->scheduleOnUI([id, sud]() {
const std::lock_guard<std::recursive_mutex> lock(sud->storeMutex);
if (sud->store.count(id) > 0) {
sud->store.erase(id);
}
});
});
#else
strongScheduler->scheduleOnUI([id, sud]() {
const std::lock_guard<std::recursive_mutex> lock(sud->storeMutex);
if (sud->store.count(id) > 0) {
sud->store.erase(id);
}
});
#endif
}
}
} // namespace reanimated
|
{
"content_hash": "57200df7524d5d79ee0fb4d1e34331d2",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 78,
"avg_line_length": 29.53061224489796,
"alnum_prop": 0.6482377332411887,
"repo_name": "exponentjs/exponent",
"id": "90e3959e856c15b75aafdcb7267da62307e727bb",
"size": "1561",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ios/vendored/sdk44/react-native-reanimated/Common/cpp/Tools/JSIStoreValueUser.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "96902"
},
{
"name": "Batchfile",
"bytes": "382"
},
{
"name": "C",
"bytes": "896724"
},
{
"name": "C++",
"bytes": "867983"
},
{
"name": "CSS",
"bytes": "6732"
},
{
"name": "HTML",
"bytes": "152590"
},
{
"name": "IDL",
"bytes": "897"
},
{
"name": "Java",
"bytes": "4588748"
},
{
"name": "JavaScript",
"bytes": "9343259"
},
{
"name": "Makefile",
"bytes": "8790"
},
{
"name": "Objective-C",
"bytes": "10675806"
},
{
"name": "Objective-C++",
"bytes": "364286"
},
{
"name": "Perl",
"bytes": "5860"
},
{
"name": "Prolog",
"bytes": "287"
},
{
"name": "Python",
"bytes": "97564"
},
{
"name": "Ruby",
"bytes": "45432"
},
{
"name": "Shell",
"bytes": "6501"
}
],
"symlink_target": ""
}
|
if (this.importScripts) {
importScripts('../../../resources/js-test.js');
importScripts('shared.js');
}
description("Test IndexedDB keys ordering and readback from cursors.");
indexedDBTest(prepareDatabase, populateStore);
function prepareDatabase()
{
db = event.target.result;
store = evalAndLog("store = db.createObjectStore('store')");
evalAndLog("store.createIndex('index', '')");
}
function populateStore()
{
debug("");
debug("populating store...");
evalAndLog("trans = db.transaction('store', 'readwrite', {durability: 'relaxed'})");
evalAndLog("store = trans.objectStore('store');");
trans.onerror = unexpectedErrorCallback;
trans.onabort = unexpectedAbortCallback;
evalAndLog("store.put(1, 1)");
evalAndLog("store.put(2, 2)");
evalAndLog("store.put(3, 3)");
trans.oncomplete = testCursor;
}
var tests = [
{upperBound: 7, open: false, expected: 3},
{upperBound: 7, open: true, expected: 3},
{upperBound: 3, open: false, expected: 3},
{upperBound: 3, open: true, expected: 2}
];
function testCursor()
{
debug("testCursor()");
if (tests.length === 0) {
debug("No more tests.");
finishJSTest();
return;
}
test = tests.shift();
evalAndLog("trans = db.transaction('store', 'readonly', {durability: 'relaxed'})");
trans.onerror = unexpectedErrorCallback;
trans.onabort = unexpectedAbortCallback;
trans.oncomplete = testCursor;
evalAndLog("store = trans.objectStore('store');");
evalAndLog("index = store.index('index');");
var testFunction = function() {
evalAndLog("cursor = event.target.result");
if (cursor === null) {
debug("cursor should not be null");
fail();
return;
}
shouldBe("cursor.key", "test.expected");
if ("value" in cursor)
shouldBe("cursor.value", "test.expected");
shouldBe("cursor.primaryKey", "test.expected");
// Let the transaction finish.
}
debug("upperBound: " + test.upperBound + " open: " + test.open + " expected: " + test.expected);
storeReq = evalAndLog("storeReq = store.openCursor(IDBKeyRange.upperBound(test.upperBound, test.open), 'prev')");
storeReq.onsuccess = testFunction;
indexReq = evalAndLog("indexReq = index.openCursor(IDBKeyRange.upperBound(test.upperBound, test.open), 'prev')");
indexReq.onsuccess = testFunction;
indexKeyReq = evalAndLog("indexKeyReq = index.openKeyCursor(IDBKeyRange.upperBound(test.upperBound, test.open), 'prev')");
indexKeyReq.onsuccess = testFunction;
}
|
{
"content_hash": "e679cabe4ae5e916eb1f5c206f2d66ea",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 126,
"avg_line_length": 32.68292682926829,
"alnum_prop": 0.6268656716417911,
"repo_name": "chromium/chromium",
"id": "32338b90bb248474ffb0c8f6d566a4c1826a927e",
"size": "2680",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/storage/indexeddb/resources/cursor-reverse-bug.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
}
|
package de.tuebingen.uni.sfs.qta;
/**
* @author Daniil Sorokin<daniil.sorokin@uni-tuebingen.de>
*/
public class Word {
private final String lemma;
private final String pos;
public Word(String lemma, String pos) {
this.lemma = lemma;
this.pos = pos;
}
public String getLemma() {
return lemma;
}
public String getPos() {
return pos;
}
@Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + (this.lemma != null ? this.lemma.hashCode() : 0);
hash = 59 * hash + (this.pos != null ? this.pos.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Word other = (Word) obj;
if ((this.lemma == null) ? (other.lemma != null) : !this.lemma.equals(other.lemma)) {
return false;
}
if ((this.pos == null) ? (other.pos != null) : !this.pos.equals(other.pos)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Word{" + "lemma=" + lemma + ", pos=" + pos + '}';
}
}
|
{
"content_hash": "0a3eded839d24ecbb2a9d7ce198d01c2",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 93,
"avg_line_length": 24.245283018867923,
"alnum_prop": 0.5136186770428015,
"repo_name": "daniilsorokin/Quantitative-Text-Analysis--Java-App-",
"id": "ce9524ec7204d78bbe52318972a0dadde0a57177",
"size": "1285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/tuebingen/uni/sfs/qta/Word.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "25557"
}
],
"symlink_target": ""
}
|
(function(){
var _page_selector = ".credit-app ";
var _progressBar = $(_page_selector + "[data-credit-progress-bar]");
var _tab = $(_page_selector + "[data-credit-progress]");
var _tabs = _tab.find("[data-toggle='tab']");
var _pagerPrev = $(_page_selector + "[data-credit-prev]");
var _pagerNext = $(_page_selector + "[data-credit-next]");
//
// Init
UpdateProgressBar(TabProgress());
TabStyle();
//
// Click Navigation
$(_page_selector + "[data-toggle='tab']").on("shown.bs.tab", function (e) {
UpdateProgressBar(TabProgress());
TabStyle(e.target);
})
_pagerPrev.on("click", function (e) {
var activeTab = _tab.find(".active");
var prevTab = activeTab.prev().find("[data-toggle='tab']");
$(prevTab).tab('show');
})
_pagerNext.on("click", function (e) {
var activeTab = _tab.find(".active");
var nextTab = activeTab.next().find("[data-toggle='tab']");
$(nextTab).tab('show');
})
//
// Add classes to tabs based on which are inactive/next
function TabStyle(self) {
var activeTab = _tab.find(".active");
var nextTabs = activeTab.nextAll();
var prevTabs = activeTab.prevAll();
nextTabs.each(function() {
$(this).addClass("is-next");
});
prevTabs.removeClass("is-next");
$(self).parent().removeClass("is-next");
}
//
// Get tab percentage based on number of items in nav
function TabProgress() {
var activeTab = _tab.find(".active");
var totalTab = _tabs.length;
var currentTab = activeTab.prevAll().length + 1;
var progress = (currentTab / totalTab) * 100 + "%";
return progress;
};
//
// Add width to progress bar based returned from "TabProgress" funct
function UpdateProgressBar(progress) {
_progressBar.css("width", progress).attr("aria-valuenow", progress);
}
})()
|
{
"content_hash": "0ce4b7e5445d85d824d9f257fe54e651",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 76,
"avg_line_length": 29.442622950819672,
"alnum_prop": 0.6280623608017817,
"repo_name": "DealerOnClass/cmsv3",
"id": "256e68859f0770d8e5e1876199ad1315c6c68496",
"size": "1796",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "app/js/mockups/credit.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "283928"
},
{
"name": "HTML",
"bytes": "277699"
},
{
"name": "JavaScript",
"bytes": "6501"
}
],
"symlink_target": ""
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace LightySample
{
/// <summary>
/// App.xaml の相互作用ロジック
/// </summary>
public partial class App : Application
{
}
}
|
{
"content_hash": "a02355bad1be3c8cd2989434d9c8179c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 42,
"avg_line_length": 18.470588235294116,
"alnum_prop": 0.7006369426751592,
"repo_name": "sourcechord/Lighty",
"id": "4dbe240b8d2429d76396a6ac507c142f502918cc",
"size": "334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sample/LightySample/App.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "59"
},
{
"name": "C#",
"bytes": "23898"
}
],
"symlink_target": ""
}
|
package com.android.server.vr;
import android.annotation.NonNull;
import android.content.ComponentName;
/**
* Service for accessing the VR mode manager.
*
* @hide Only for use within system server.
*/
public abstract class VrManagerInternal {
/**
* The error code returned on success.
*/
public static final int NO_ERROR = 0;
/**
* Return {@code true} if the given package is the currently bound VrListenerService for the
* given user.
*
* @param packageName The package name to check.
* @param userId the user ID to check the package name for.
*
* @return {@code true} if the given package is the currently bound VrListenerService.
*/
public abstract boolean isCurrentVrListener(String packageName, int userId);
/**
* Set the current VR mode state.
* <p/>
* This may delay the mode change slightly during application transitions to avoid frequently
* tearing down VrListenerServices unless necessary.
*
* @param enabled {@code true} to enable VR mode.
* @param packageName The package name of the requested VrListenerService to bind.
* @param userId the user requesting the VrListenerService component.
* @param calling the component currently using VR mode, or null to leave unchanged.
*/
public abstract void setVrMode(boolean enabled, @NonNull ComponentName packageName,
int userId, @NonNull ComponentName calling);
/**
* Set the current VR mode state immediately.
*
* @param enabled {@code true} to enable VR mode.
* @param packageName The package name of the requested VrListenerService to bind.
* @param userId the user requesting the VrListenerService component.
* @param calling the component currently using VR mode, or null to leave unchanged.
*/
public abstract void setVrModeImmediate(boolean enabled, @NonNull ComponentName packageName,
int userId, @NonNull ComponentName calling);
/**
* Return NO_ERROR if the given package is installed on the device and enabled as a
* VrListenerService for the given current user, or a negative error code indicating a failure.
*
* @param packageName the name of the package to check, or null to select the default package.
* @return NO_ERROR if the given package is installed and is enabled, or a negative error code
* given in {@link android.service.vr.VrModeException} on failure.
*/
public abstract int hasVrPackage(@NonNull ComponentName packageName, int userId);
}
|
{
"content_hash": "a3d1be824cc78c6453c3b9109b1d95e6",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 98,
"avg_line_length": 38.89393939393939,
"alnum_prop": 0.7039345539540319,
"repo_name": "daiqiquan/framework-base",
"id": "ad87a885348e6a2695817c5d172b6ecbd4ed91de",
"size": "3187",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "services/core/java/com/android/server/vr/VrManagerInternal.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10239"
},
{
"name": "C++",
"bytes": "3841417"
},
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "196467"
},
{
"name": "Java",
"bytes": "56796292"
},
{
"name": "Makefile",
"bytes": "103735"
},
{
"name": "Shell",
"bytes": "423"
}
],
"symlink_target": ""
}
|
import {WordGenerator} from './word-generator.js';
var Game = (function () {
function Game(player, enemy) {
this.player = player;
this.enemy = enemy;
this.images = [];
this.myTurn = true;
this.points = 0;
var wordGen = new WordGenerator();
this.word = wordGen.next();
}
return Game;
}());
export {Game}
|
{
"content_hash": "c8cb5f678b86ffa9f9204123bf82a455",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 50,
"avg_line_length": 18.85,
"alnum_prop": 0.5464190981432361,
"repo_name": "JS-Applications-Team-Mai-Tai/Team-Mai-Tai",
"id": "788672eb02ea96d63e68259bd595f5a79ef74307",
"size": "377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/whereMagicHappens/game.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "101292"
},
{
"name": "HTML",
"bytes": "43817"
},
{
"name": "JavaScript",
"bytes": "567694"
}
],
"symlink_target": ""
}
|
#ifndef TARANTOOL_SIO_H_INCLUDED
#define TARANTOOL_SIO_H_INCLUDED
/**
* Exception-aware wrappers around BSD sockets.
* Provide better error logging and I/O statistics.
*/
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <tarantool_ev.h>
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
const char *
sio_strfaddr(struct sockaddr *addr, socklen_t addrlen);
int
sio_getpeername(int fd, struct sockaddr *addr, socklen_t *addrlen);
/**
* Advance write position in the iovec array
* based on its current value and the number of
* bytes written.
*
* @param[in] iov the vector being written with writev().
* @param[in] nwr number of bytes written, @pre >= 0
* @param[in,out] iov_len offset in iov[0];
*
* @return offset of iov[0] for the next write
*/
static inline int
sio_move_iov(struct iovec *iov, size_t nwr, size_t *iov_len)
{
nwr += *iov_len;
struct iovec *begin = iov;
while (nwr > 0 && nwr >= iov->iov_len) {
nwr -= iov->iov_len;
iov++;
}
*iov_len = nwr;
return iov - begin;
}
/**
* Change values of iov->iov_len and iov->iov_base
* to adjust to a partial write.
*/
static inline void
sio_add_to_iov(struct iovec *iov, size_t size)
{
iov->iov_len += size;
iov->iov_base = (char *) iov->iov_base - size;
}
#if defined(__cplusplus)
} /* extern "C" */
#include "exception.h"
enum { SERVICE_NAME_MAXLEN = 32 };
extern const struct type type_SocketError;
class SocketError: public SystemError {
public:
SocketError(const char *file, unsigned line, int fd,
const char *format, ...);
virtual void raise()
{
throw this;
}
};
/** Close a file descriptor on exception or end of scope. */
struct FDGuard {
int fd;
explicit FDGuard(int fd_arg):fd(fd_arg) {}
~FDGuard() { if (fd >= 0) close(fd); }
private:
explicit FDGuard(const FDGuard&) = delete;
FDGuard& operator=(const FDGuard&) = delete;
};
const char *sio_socketname(int fd);
int sio_socket(int domain, int type, int protocol);
int sio_shutdown(int fd, int how);
int sio_getfl(int fd);
int sio_setfl(int fd, int flag, int on);
void
sio_setsockopt(int fd, int level, int optname,
const void *optval, socklen_t optlen);
void
sio_getsockopt(int fd, int level, int optname,
void *optval, socklen_t *optlen);
int sio_connect(int fd, struct sockaddr *addr, socklen_t addrlen);
int sio_bind(int fd, struct sockaddr *addr, socklen_t addrlen);
int sio_listen(int fd);
int sio_listen_backlog();
int sio_accept(int fd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t sio_read(int fd, void *buf, size_t count);
ssize_t sio_write(int fd, const void *buf, size_t count);
ssize_t sio_writev(int fd, const struct iovec *iov, int iovcnt);
ssize_t sio_write_total(int fd, const void *buf, size_t count, size_t total);
/**
* Read at least count and up to buf_size bytes from fd.
* Throw exception on error or disconnect.
*
* @return the number of of bytes actually read.
*/
ssize_t
sio_readn_ahead(int fd, void *buf, size_t count, size_t buf_size);
/**
* Read count bytes from fd.
* Throw an exception on error or disconnect.
*
* @return count of bytes actually read.
*/
static inline ssize_t
sio_readn(int fd, void *buf, size_t count)
{
return sio_readn_ahead(fd, buf, count, count);
}
/**
* Write count bytes to fd.
* Throw an exception on error or disconnect.
*
* @return count of bytes actually written.
*/
ssize_t
sio_writen(int fd, const void *buf, size_t count);
/* Only for blocked I/O */
ssize_t
sio_writev_all(int fd, struct iovec *iov, int iovcnt);
/**
* A wrapper over sendfile.
* Throw if send file failed.
*/
ssize_t
sio_sendfile(int sock_fd, int file_fd, off_t *offset, size_t size);
/**
* Receive a file sent by sendfile
* Throw if receiving failed
*/
ssize_t
sio_recvfile(int sock_fd, int file_fd, off_t *offset, size_t size);
ssize_t sio_sendto(int fd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
ssize_t sio_recvfrom(int fd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
#endif /* defined(__cplusplus) */
#endif /* TARANTOOL_SIO_H_INCLUDED */
|
{
"content_hash": "765e8f741f981b465fed2796f17b6da4",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 77,
"avg_line_length": 24.54913294797688,
"alnum_prop": 0.6788321167883211,
"repo_name": "mejedi/tarantool",
"id": "e5ebe2e7041765c82e12cc624040470ab95a218a",
"size": "5630",
"binary": false,
"copies": "2",
"ref": "refs/heads/1.7",
"path": "src/sio.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1972858"
},
{
"name": "C++",
"bytes": "913498"
},
{
"name": "CMake",
"bytes": "94972"
},
{
"name": "GDB",
"bytes": "55"
},
{
"name": "Lua",
"bytes": "928941"
},
{
"name": "Makefile",
"bytes": "2122"
},
{
"name": "Objective-C",
"bytes": "2072"
},
{
"name": "Python",
"bytes": "63048"
},
{
"name": "Ragel",
"bytes": "7313"
},
{
"name": "Shell",
"bytes": "1938"
}
],
"symlink_target": ""
}
|
"""
AVWX REST API
"""
from avwx_api.app_config import app
from avwx_api import api, views
|
{
"content_hash": "2bc810868cf0285d10e51fd8877ac159",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 35,
"avg_line_length": 13.142857142857142,
"alnum_prop": 0.7065217391304348,
"repo_name": "flyinactor91/AVWX-API",
"id": "2ee99e9ecff85290563f90d75817c138320f4377",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "avwx_api/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "API Blueprint",
"bytes": "54804"
},
{
"name": "CSS",
"bytes": "1370"
},
{
"name": "HTML",
"bytes": "13918"
},
{
"name": "JavaScript",
"bytes": "621"
},
{
"name": "Python",
"bytes": "41358"
}
],
"symlink_target": ""
}
|
Textile
=======
- Filter name: ``textile``
- Pypi package: ``Textile``
Textile is a lightweight markup language originally developed by Dean Allen
and billed as a "humane Web text generator". Textile converts its marked-up
text input to valid, well-formed XHTML and also inserts character entity references
for apostrophes, opening and closing single and double quotation marks,
ellipses and em dashes.
(Taken from Wikipedia_)
.. _Wikipedia: http://en.wikipedia.org/wiki/Textile_(markup_language)
|
{
"content_hash": "27a8d08dc7f11182c794d34cc507cb1d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 83,
"avg_line_length": 33.333333333333336,
"alnum_prop": 0.772,
"repo_name": "bartTC/django-markup",
"id": "f3141dec9ecd7a85891f60a1c3d7056e88a2a769",
"size": "500",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "docs/bundled_filter/textile.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "136"
},
{
"name": "Python",
"bytes": "20905"
}
],
"symlink_target": ""
}
|
namespace jet {
//!
//! \brief Fractional 2-D boundary condition solver for grids.
//!
//! This class constrains the velocity field by projecting the flow to the
//! signed-distance field representation of the collider. This implementation
//! should pair up with GridFractionalSinglePhasePressureSolver2 to provide
//! sub-grid resolutional velocity projection.
//!
class GridFractionalBoundaryConditionSolver2
: public GridBoundaryConditionSolver2 {
public:
//! Default constructor.
GridFractionalBoundaryConditionSolver2();
//! Default destructor.
virtual ~GridFractionalBoundaryConditionSolver2();
//!
//! Constrains the velocity field to conform the collider boundary.
//!
//! \param velocity Input and output velocity grid.
//! \param extrapolationDepth Number of inner-collider grid cells that
//! velocity will get extrapolated.
//!
void constrainVelocity(
FaceCenteredGrid2* velocity,
unsigned int extrapolationDepth = 5) override;
//! Returns the signed distance field of the collider.
ScalarField2Ptr colliderSdf() const override;
//! Returns the velocity field of the collider.
VectorField2Ptr colliderVelocityField() const override;
protected:
//! Invoked when a new collider is set.
void onColliderUpdated(
const Size2& gridSize,
const Vector2D& gridSpacing,
const Vector2D& gridOrigin) override;
private:
CellCenteredScalarGrid2Ptr _colliderSdf;
CustomVectorField2Ptr _colliderVel;
};
//! Shared pointer type for the GridFractionalBoundaryConditionSolver2.
typedef std::shared_ptr<GridFractionalBoundaryConditionSolver2>
GridFractionalBoundaryConditionSolver2Ptr;
} // namespace jet
#endif // INCLUDE_JET_GRID_FRACTIONAL_BOUNDARY_CONDITION_SOLVER2_H_
|
{
"content_hash": "1ff09fd2e42ee6ce53a32e24b3730aca",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 77,
"avg_line_length": 32.96363636363636,
"alnum_prop": 0.7418643132928847,
"repo_name": "doyubkim/fluid-engine-dev",
"id": "b4e1ec7c08166cf9ec35cabd0255fc65511b45fc",
"size": "2313",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "include/jet/grid_fractional_boundary_condition_solver2.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "57830"
},
{
"name": "C++",
"bytes": "4338337"
},
{
"name": "CMake",
"bytes": "36550"
},
{
"name": "Dockerfile",
"bytes": "461"
},
{
"name": "Python",
"bytes": "104759"
},
{
"name": "Shell",
"bytes": "566"
}
],
"symlink_target": ""
}
|
layout: layout
section: program
photocredit: Daniel X. O'Neil
photocredit_url: https://www.flickr.com/photos/juggernautco/27262805686/
permalink: /program/
title: SRCCON 2019 — About Our Program
---
# The SRCCON Program
SRCCON is a hands-on conference with two days full of sessions—but the schedule is only where our program begins. [Every attendee is also a participant](/participation) who brings their own interests and experiences into sessions, emergent conversations, our evening activities, and gatherings during SRCCON.
## Our Sessions
SRCCON is built around peer-led conversations and hands-on workshops. Our sessions are highly collaborative, not a panel on a stage or a speaker running through slides. We look for sessions that include real interactivity and participation: design exercises, art and games, small-group work, role playing, even field trips—and we’re always interested in new ideas.
SRCCON sessions last about 75 minutes, exploring cultural questions that help journalists work together better, new tools and techniques that people are excited about, and sessions that meet in the middle. Our schedule regularly extends beyond what you might expect at a journalism conference—take a look at [previous years](/sessions/about/#previous-years), learn more about [how sessions work](/sessions/about/), or check out the [schedule for SRCCON 2019](https://schedule.srccon.org)!
Our program for SRCCON is built around key community values:
* **We experiment in the open**—by sharing our work and processes, we do the innovative work our organizations need to evolve on the web and better inform our audiences.
* **We support one another**—by offering each other our expertise and empathy, we find new collaborators, help each other learn, and make our networks and organizations more resilient.
* **We lead change**—by challenging the power structures that have failed our industry, we push for inclusive, long-lasting change in our newsrooms, led by journalists of color and the wide community of journalists outside of NYC/DC.
## Our Schedule
SRCCON is also organized around building connections between participants. We want you to be able to fully focus on taking part—not just in the sessions on the official schedule, but in all the great conversations in hallways and after hours that make an event memorable. So we build in generous breaks to let you chat or grab coffee or tea without feeling rushed getting to the next thing. We provide lots of snacks and full lunches both days, with space to chill out or make plans with new friends. Dinner and our Thursday evening program are a chance to spend time with people in more relaxed space. We also [provide free childcare](/childcare) throughout the event to make it more accessible to everyone.
SRCCON attendees tend to arrive on Wednesday and leave Friday evening or Saturday, depending on how the flight times work out. You can [check out the full schedule](/schedule) now. Plus, [our logistics page](/logistics) has information about our conference hotel and other ways we hope to make it easier for you to take part in SRCCON.
## Emergent Conversations
We love it when recent work sparks a great idea that travels with you to SRCCON, or a session sends you down just the right rabbit hole and you find yourself among kindred spirits. So we create space at SRCCON for topics beyond the ones on our schedule:
* Lunch signup boards let you choose a room and invite other attendees to bring their meals and join you for a conversation over lunch.
* Activity boards help you plan events outside SRCCON hours, from group visits to a local newsroom or museum, ballgame or concert, or just getting out for some sun and fresh air.
* Jobs boards give you a chance to connect with other attendees about career opportunities, whether you're hiring or looking.
## Our Evening Program
We know [evenings at conferences can be tough](https://opennews.org/blog/srccon-thursday/), so we close the first day of SRCCON with dinner together and an opportunity to have fun, relax, and give our brains a chance to process the amazing sessions from earlier that day. We see Thursday as an opportunity to focus on the "life" side of the work/life balance, with:
* local, guided walks
* hobby workshops & chats
* themed lightning talks
* music & conversations
* a room full of card and board games
Plus, of course, a huge spread of snacks and beverages. Our snacks are as local as we can get—we love feeling a sense of place wherever we visit. If you have partners or friends who’ll be in Minneapolis, feel free to invite them to join you for Thursday evening—[we offer special partner tickets](https://www.eventbrite.com/e/srccon-2019-tickets-61642701981?discount=partner) and are happy to welcome them for dinner and the activities afterward.
The Thursday evening program is built and run by attendees, so if you have an idea you'd like to pitch in, [we'd love to hear it](mailto:srccon@opennews.org)!
|
{
"content_hash": "552f464683d2b94b61ae4481a4eee89c",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 708,
"avg_line_length": 97.62745098039215,
"alnum_prop": 0.793733681462141,
"repo_name": "OpenNews/srccon",
"id": "9a003748086329cc70e3d41f64d8a0ead809fe4d",
"size": "5007",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging",
"path": "_archive/2019_templates/program.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "85536"
},
{
"name": "HTML",
"bytes": "47896"
},
{
"name": "JavaScript",
"bytes": "15140"
}
],
"symlink_target": ""
}
|
package org.apache.hadoop.hbase.io;
import java.util.*;
import org.apache.hadoop.classification.InterfaceAudience;
/**
* A Static Interface.
* Instead of having this code in the the HbaseMapWritable code, where it
* blocks the possibility of altering the variables and changing their types,
* it is put here in this static interface where the static final Maps are
* loaded one time. Only byte[] and Cell are supported at this time.
*/
@InterfaceAudience.Private
public interface CodeToClassAndBack {
/**
* Static map that contains mapping from code to class
*/
public static final Map<Byte, Class<?>> CODE_TO_CLASS =
new HashMap<Byte, Class<?>>();
/**
* Static map that contains mapping from class to code
*/
public static final Map<Class<?>, Byte> CLASS_TO_CODE =
new HashMap<Class<?>, Byte>();
/**
* Class list for supported classes
*/
public Class<?>[] classList = {byte[].class};
/**
* The static loader that is used instead of the static constructor in
* HbaseMapWritable.
*/
public InternalStaticLoader sl =
new InternalStaticLoader(classList, CODE_TO_CLASS, CLASS_TO_CODE);
/**
* Class that loads the static maps with their values.
*/
public class InternalStaticLoader{
InternalStaticLoader(Class<?>[] classList,
Map<Byte,Class<?>> CODE_TO_CLASS, Map<Class<?>, Byte> CLASS_TO_CODE){
byte code = 1;
for(int i=0; i<classList.length; i++){
CLASS_TO_CODE.put(classList[i], code);
CODE_TO_CLASS.put(code, classList[i]);
code++;
}
}
}
}
|
{
"content_hash": "08cc3c576f84f1340770b1cb69e26e9e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 77,
"avg_line_length": 28.196428571428573,
"alnum_prop": 0.6706776440785307,
"repo_name": "jyates/hbase",
"id": "4b8fa88bdbc52f3ae6252d87432bfe3985228467",
"size": "2388",
"binary": false,
"copies": "4",
"ref": "refs/heads/trunk",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/io/CodeToClassAndBack.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4124"
},
{
"name": "C++",
"bytes": "733760"
},
{
"name": "Java",
"bytes": "16496462"
},
{
"name": "JavaScript",
"bytes": "51399"
},
{
"name": "PHP",
"bytes": "413443"
},
{
"name": "Perl",
"bytes": "383793"
},
{
"name": "Python",
"bytes": "382260"
},
{
"name": "Ruby",
"bytes": "369465"
},
{
"name": "Shell",
"bytes": "110824"
},
{
"name": "XSLT",
"bytes": "4320"
}
],
"symlink_target": ""
}
|
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import autobind from 'autobind-decorator'
import Menu from './Menu'
export default class MenuWrapper extends PureComponent {
static propTypes = {
onSelect: PropTypes.func,
onItemSelect: PropTypes.func,
}
@autobind
handleSelection(item, index) {
const { onSelect, onItemSelect } = this.props
if (onItemSelect) onItemSelect(item, index)
if (onSelect) onSelect()
}
render() {
const {
onItemSelect,
onSelect,
...props
} = this.props
return (
<Menu
onItemSelect={this.handleSelection}
{...props}
/>
)
}
}
|
{
"content_hash": "ada39a7b5ff889a062b5a7262dd46551",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 56,
"avg_line_length": 19.485714285714284,
"alnum_prop": 0.6363636363636364,
"repo_name": "rentpath/react-ui",
"id": "3b22025e46cfc4cd3140e8895450839b9842e546",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/react-ui-core/src/Menu/MenuWrapper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "78511"
},
{
"name": "HTML",
"bytes": "907"
},
{
"name": "JavaScript",
"bytes": "70323"
},
{
"name": "SCSS",
"bytes": "1507"
},
{
"name": "Shell",
"bytes": "431"
}
],
"symlink_target": ""
}
|
<?php
if (! @include_once __DIR__.'/../vendor/autoload.php') {
exit("You must set up the project dependencies, run the following commands:\n> wget http://getcomposer.org/composer.phar\n> php composer.phar install\n");
}
|
{
"content_hash": "ce829283a4aded743fcb1528f2ae1e0e",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 158,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.6902654867256637,
"repo_name": "phpthinktank/blast-turbine",
"id": "50f931ad56d74ed96c62690167e306a71ea0198b",
"size": "471",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/bootstrap.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "347"
},
{
"name": "PHP",
"bytes": "66052"
},
{
"name": "Shell",
"bytes": "1354"
}
],
"symlink_target": ""
}
|
package bitcoincash
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"sync"
"time"
"github.com/OpenBazaar/multiwallet/util"
"golang.org/x/net/proxy"
)
type ExchangeRateProvider struct {
fetchUrl string
cache map[string]float64
client *http.Client
decoder ExchangeRateDecoder
}
type ExchangeRateDecoder interface {
decode(dat interface{}, cache map[string]float64) (err error)
}
type OpenBazaarDecoder struct{}
type BitcoinCashPriceFetcher struct {
sync.Mutex
cache map[string]float64
providers []*ExchangeRateProvider
}
func NewBitcoinCashPriceFetcher(dialer proxy.Dialer) *BitcoinCashPriceFetcher {
b := BitcoinCashPriceFetcher{
cache: make(map[string]float64),
}
var client *http.Client
if dialer != nil {
dial := dialer.Dial
tbTransport := &http.Transport{Dial: dial}
client = &http.Client{Transport: tbTransport, Timeout: time.Minute}
} else {
client = &http.Client{Timeout: time.Minute}
}
b.providers = []*ExchangeRateProvider{
{"https://ticker.openbazaar.org/api", b.cache, client, OpenBazaarDecoder{}},
}
return &b
}
func (b *BitcoinCashPriceFetcher) GetExchangeRate(currencyCode string) (float64, error) {
b.Lock()
defer b.Unlock()
currencyCode = util.NormalizeCurrencyCode(currencyCode)
price, ok := b.cache[currencyCode]
if !ok {
return 0, errors.New("Currency not tracked")
}
return price, nil
}
func (b *BitcoinCashPriceFetcher) GetLatestRate(currencyCode string) (float64, error) {
b.fetchCurrentRates()
b.Lock()
defer b.Unlock()
currencyCode = util.NormalizeCurrencyCode(currencyCode)
price, ok := b.cache[currencyCode]
if !ok {
return 0, errors.New("Currency not tracked")
}
return price, nil
}
func (b *BitcoinCashPriceFetcher) GetAllRates(cacheOK bool) (map[string]float64, error) {
if !cacheOK {
err := b.fetchCurrentRates()
if err != nil {
return nil, err
}
}
b.Lock()
defer b.Unlock()
return b.cache, nil
}
func (b *BitcoinCashPriceFetcher) UnitsPerCoin() int64 {
return 100000000
}
func (b *BitcoinCashPriceFetcher) fetchCurrentRates() error {
b.Lock()
defer b.Unlock()
for _, provider := range b.providers {
err := provider.fetch()
if err == nil {
return nil
}
fmt.Println(err)
}
return errors.New("All exchange rate API queries failed")
}
func (b *BitcoinCashPriceFetcher) Run() {
b.fetchCurrentRates()
ticker := time.NewTicker(time.Minute * 15)
for range ticker.C {
b.fetchCurrentRates()
}
}
func (provider *ExchangeRateProvider) fetch() (err error) {
if len(provider.fetchUrl) == 0 {
err = errors.New("provider has no fetchUrl")
return err
}
resp, err := provider.client.Get(provider.fetchUrl)
if err != nil {
return err
}
decoder := json.NewDecoder(resp.Body)
var dataMap interface{}
err = decoder.Decode(&dataMap)
if err != nil {
return err
}
return provider.decoder.decode(dataMap, provider.cache)
}
func (b OpenBazaarDecoder) decode(dat interface{}, cache map[string]float64) (err error) {
data, ok := dat.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed")
}
bch, ok := data["BCH"]
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed, missing 'BCH' field")
}
val, ok := bch.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed")
}
bchRate, ok := val["last"].(float64)
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed, missing 'last' (float) field")
}
for k, v := range data {
if k != "timestamp" {
val, ok := v.(map[string]interface{})
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed")
}
price, ok := val["last"].(float64)
if !ok {
return errors.New(reflect.TypeOf(b).Name() + ".decode: Type assertion failed, missing 'last' (float) field")
}
cache[k] = price * (1 / bchRate)
}
}
return nil
}
|
{
"content_hash": "d1a9fdc2f1869a17269c0e7b1ecbc2c5",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 112,
"avg_line_length": 24,
"alnum_prop": 0.6936868686868687,
"repo_name": "OpenBazaar/openbazaar-go",
"id": "bce585d9aaff559cb478343a3f8a6026cf54dd22",
"size": "3960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/OpenBazaar/multiwallet/bitcoincash/exchange_rates.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1090"
},
{
"name": "Go",
"bytes": "2010018"
},
{
"name": "Makefile",
"bytes": "2942"
},
{
"name": "Python",
"bytes": "527426"
},
{
"name": "Shell",
"bytes": "3265"
}
],
"symlink_target": ""
}
|
<?php
use osCommerce\OM\Core\OSCOM;
?>
<p align="center">osCommerce Online Merchant Copyright © 2000-2011 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a> (<a href="http://www.oscommerce.com/about/copyright" target="_blank">Copyright Policy</a>, <a href="http://www.oscommerce.com/about/trademark" target="_blank">Trademark Policy</a>)<br />osCommerce is a registered trademark of Harald Ponce de Leon</p>
<div style="text-align: center; padding: 5px;"><span class="poweredByButton"><a href="http://www.oscommerce.com" target="_blank"><span class="poweredBy">Powered By</span><span class="osCommerce"><?php echo 'osCommerce Online Merchant v' . OSCOM::getVersion(); ?></span></a></span></div>
|
{
"content_hash": "dbab1d3511f4c34678a5b30840e5bb19",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 389,
"avg_line_length": 80.22222222222223,
"alnum_prop": 0.7188365650969529,
"repo_name": "osCommerce/oscommerce",
"id": "5e51db8bac63736c10d136b2e138e2b624b8b934",
"size": "900",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "osCommerce/OM/Core/Site/Admin/templates/oscom/footer.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "82863"
},
{
"name": "PHP",
"bytes": "2667400"
}
],
"symlink_target": ""
}
|
package com.guanqing.subredditor;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
{
"content_hash": "39266514bef0210d9c1679758fdf1a9d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 93,
"avg_line_length": 27.307692307692307,
"alnum_prop": 0.752112676056338,
"repo_name": "haoguanqing/Subreddit_Reader",
"id": "c76584a84e091b9e0e310333244fb266a5a231b2",
"size": "355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/com/guanqing/subredditor/ApplicationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "253721"
}
],
"symlink_target": ""
}
|
import {
CalendarOptions, Action, CalendarContent, render, createElement, DelayedRunner, CssDimValue, applyStyleProp,
CalendarApi, CalendarRoot, isArraysEqual, CalendarDataManager, CalendarData,
CustomContentRenderContext, flushToDom, unmountComponentAtNode,
} from '@fullcalendar/common'
export class Calendar extends CalendarApi {
currentData: CalendarData
renderRunner: DelayedRunner
el: HTMLElement
isRendering = false
isRendered = false
currentClassNames: string[] = []
customContentRenderId = 0 // will affect custom generated classNames?
get view() { return this.currentData.viewApi } // for public API
constructor(el: HTMLElement, optionOverrides: CalendarOptions = {}) {
super()
this.el = el
this.renderRunner = new DelayedRunner(this.handleRenderRequest)
new CalendarDataManager({ // eslint-disable-line no-new
optionOverrides,
calendarApi: this,
onAction: this.handleAction,
onData: this.handleData,
})
}
handleAction = (action: Action) => {
// actions we know we want to render immediately
switch (action.type) {
case 'SET_EVENT_DRAG':
case 'SET_EVENT_RESIZE':
this.renderRunner.tryDrain()
}
}
handleData = (data: CalendarData) => {
this.currentData = data
this.renderRunner.request(data.calendarOptions.rerenderDelay)
}
handleRenderRequest = () => {
if (this.isRendering) {
this.isRendered = true
let { currentData } = this
render(
<CalendarRoot options={currentData.calendarOptions} theme={currentData.theme} emitter={currentData.emitter}>
{(classNames, height, isHeightAuto, forPrint) => {
this.setClassNames(classNames)
this.setHeight(height)
return (
<CustomContentRenderContext.Provider value={this.customContentRenderId}>
<CalendarContent
isHeightAuto={isHeightAuto}
forPrint={forPrint}
{...currentData}
/>
</CustomContentRenderContext.Provider>
)
}}
</CalendarRoot>,
this.el,
)
} else if (this.isRendered) {
this.isRendered = false
unmountComponentAtNode(this.el)
this.setClassNames([])
this.setHeight('')
}
flushToDom()
}
render() {
let wasRendering = this.isRendering
if (!wasRendering) {
this.isRendering = true
} else {
this.customContentRenderId += 1
}
this.renderRunner.request()
if (wasRendering) {
this.updateSize()
}
}
destroy() {
if (this.isRendering) {
this.isRendering = false
this.renderRunner.request()
}
}
updateSize() {
super.updateSize()
flushToDom()
}
batchRendering(func) {
this.renderRunner.pause('batchRendering')
func()
this.renderRunner.resume('batchRendering')
}
pauseRendering() { // available to plugins
this.renderRunner.pause('pauseRendering')
}
resumeRendering() { // available to plugins
this.renderRunner.resume('pauseRendering', true)
}
resetOptions(optionOverrides, append?) {
this.currentDataManager.resetOptions(optionOverrides, append)
}
setClassNames(classNames: string[]) {
if (!isArraysEqual(classNames, this.currentClassNames)) {
let { classList } = this.el
for (let className of this.currentClassNames) {
classList.remove(className)
}
for (let className of classNames) {
classList.add(className)
}
this.currentClassNames = classNames
}
}
setHeight(height: CssDimValue) {
applyStyleProp(this.el, 'height', height)
}
}
|
{
"content_hash": "918fb73493a0487a6f068467d65e7719",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 116,
"avg_line_length": 25.47586206896552,
"alnum_prop": 0.6467244179750947,
"repo_name": "oleg-babintsev/fullcalendar",
"id": "c31a5e8b86c0b04c560a008080d462fe21fb0a57",
"size": "3694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/core/src/Calendar.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56130"
},
{
"name": "JavaScript",
"bytes": "295952"
},
{
"name": "PHP",
"bytes": "358"
},
{
"name": "Shell",
"bytes": "78"
}
],
"symlink_target": ""
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.hive.rubix;
import com.codahale.metrics.MetricRegistry;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.Closer;
import com.qubole.rubix.bookkeeper.BookKeeper;
import com.qubole.rubix.bookkeeper.BookKeeperServer;
import com.qubole.rubix.bookkeeper.LocalDataTransferServer;
import com.qubole.rubix.core.CachingFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoAdlFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoAzureBlobFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoGoogleHadoopFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoNativeAzureFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoS3FileSystem;
import com.qubole.rubix.prestosql.CachingPrestoSecureAzureBlobFileSystem;
import com.qubole.rubix.prestosql.CachingPrestoSecureNativeAzureFileSystem;
import com.qubole.rubix.prestosql.PrestoClusterManager;
import io.airlift.log.Logger;
import io.airlift.units.Duration;
import io.prestosql.plugin.base.CatalogName;
import io.prestosql.plugin.hive.HdfsConfigurationInitializer;
import io.prestosql.plugin.hive.util.RetryDriver;
import io.prestosql.spi.HostAddress;
import io.prestosql.spi.Node;
import io.prestosql.spi.NodeManager;
import io.prestosql.spi.PrestoException;
import org.apache.hadoop.conf.Configuration;
import javax.annotation.Nullable;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.propagateIfPossible;
import static com.qubole.rubix.spi.CacheConfig.enableHeartbeat;
import static com.qubole.rubix.spi.CacheConfig.setBookKeeperServerPort;
import static com.qubole.rubix.spi.CacheConfig.setCacheDataDirPrefix;
import static com.qubole.rubix.spi.CacheConfig.setCacheDataEnabled;
import static com.qubole.rubix.spi.CacheConfig.setCacheDataExpirationAfterWrite;
import static com.qubole.rubix.spi.CacheConfig.setCacheDataFullnessPercentage;
import static com.qubole.rubix.spi.CacheConfig.setCacheDataOnMasterEnabled;
import static com.qubole.rubix.spi.CacheConfig.setClusterNodeRefreshTime;
import static com.qubole.rubix.spi.CacheConfig.setCoordinatorHostName;
import static com.qubole.rubix.spi.CacheConfig.setDataTransferServerPort;
import static com.qubole.rubix.spi.CacheConfig.setEmbeddedMode;
import static com.qubole.rubix.spi.CacheConfig.setIsParallelWarmupEnabled;
import static com.qubole.rubix.spi.CacheConfig.setOnMaster;
import static io.prestosql.plugin.hive.DynamicConfigurationProvider.setCacheKey;
import static io.prestosql.plugin.hive.util.ConfigurationUtils.getInitialConfiguration;
import static io.prestosql.plugin.hive.util.RetryDriver.DEFAULT_SCALE_FACTOR;
import static io.prestosql.plugin.hive.util.RetryDriver.retry;
import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static java.lang.Integer.MAX_VALUE;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
/*
* Responsibilities of this initializer:
* 1. Wait for master and setup RubixConfigurationInitializer with information about master when it becomes available
* 2. Start Rubix Servers.
* 3. Inject BookKeeper object into CachingFileSystem class
* 4. Update HDFS configuration
*/
public class RubixInitializer
{
private static final String RUBIX_S3_FS_CLASS_NAME = CachingPrestoS3FileSystem.class.getName();
private static final String RUBIX_NATIVE_AZURE_FS_CLASS_NAME = CachingPrestoNativeAzureFileSystem.class.getName();
private static final String RUBIX_SECURE_NATIVE_AZURE_FS_CLASS_NAME = CachingPrestoSecureNativeAzureFileSystem.class.getName();
private static final String RUBIX_AZURE_BLOB_FS_CLASS_NAME = CachingPrestoAzureBlobFileSystem.class.getName();
private static final String RUBIX_SECURE_AZURE_BLOB_FS_CLASS_NAME = CachingPrestoSecureAzureBlobFileSystem.class.getName();
private static final String RUBIX_SECURE_ADL_CLASS_NAME = CachingPrestoAdlFileSystem.class.getName();
private static final String RUBIX_GS_FS_CLASS_NAME = CachingPrestoGoogleHadoopFileSystem.class.getName();
private static final RetryDriver DEFAULT_COORDINATOR_RETRY_DRIVER = retry()
// unlimited attempts
.maxAttempts(MAX_VALUE)
.exponentialBackoff(
new Duration(1, SECONDS),
new Duration(1, SECONDS),
// wait for 10 minutes
new Duration(10, MINUTES),
DEFAULT_SCALE_FACTOR);
private static final Logger log = Logger.get(RubixInitializer.class);
private final RetryDriver coordinatorRetryDriver;
private final boolean startServerOnCoordinator;
private final boolean parallelWarmupEnabled;
private final Optional<String> cacheLocation;
private final long cacheTtlMillis;
private final int diskUsagePercentage;
private final int bookKeeperServerPort;
private final int dataTransferServerPort;
private final NodeManager nodeManager;
private final CatalogName catalogName;
private final HdfsConfigurationInitializer hdfsConfigurationInitializer;
private final RubixHdfsInitializer rubixHdfsInitializer;
private volatile boolean cacheReady;
@Nullable
private HostAddress masterAddress;
@Nullable
private BookKeeperServer bookKeeperServer;
@Inject
public RubixInitializer(
RubixConfig rubixConfig,
NodeManager nodeManager,
CatalogName catalogName,
HdfsConfigurationInitializer hdfsConfigurationInitializer,
RubixHdfsInitializer rubixHdfsInitializer)
{
this(DEFAULT_COORDINATOR_RETRY_DRIVER, rubixConfig, nodeManager, catalogName, hdfsConfigurationInitializer, rubixHdfsInitializer);
}
@VisibleForTesting
RubixInitializer(
RetryDriver coordinatorRetryDriver,
RubixConfig rubixConfig,
NodeManager nodeManager,
CatalogName catalogName,
HdfsConfigurationInitializer hdfsConfigurationInitializer,
RubixHdfsInitializer rubixHdfsInitializer)
{
this.coordinatorRetryDriver = coordinatorRetryDriver;
this.startServerOnCoordinator = rubixConfig.isStartServerOnCoordinator();
this.parallelWarmupEnabled = rubixConfig.getReadMode().isParallelWarmupEnabled();
this.cacheLocation = rubixConfig.getCacheLocation();
this.cacheTtlMillis = rubixConfig.getCacheTtl().toMillis();
this.diskUsagePercentage = rubixConfig.getDiskUsagePercentage();
this.bookKeeperServerPort = rubixConfig.getBookKeeperServerPort();
this.dataTransferServerPort = rubixConfig.getDataTransferServerPort();
this.nodeManager = nodeManager;
this.catalogName = catalogName;
this.hdfsConfigurationInitializer = hdfsConfigurationInitializer;
this.rubixHdfsInitializer = rubixHdfsInitializer;
}
void initializeRubix()
{
if (nodeManager.getCurrentNode().isCoordinator() && !startServerOnCoordinator) {
// setup JMX metrics on master (instead of starting server) so that JMX connector can be used
// TODO: remove once https://github.com/prestosql/presto/issues/3821 is fixed
setupRubixMetrics();
// enable caching on coordinator so that cached block locations can be obtained
cacheReady = true;
return;
}
if (cacheLocation.isEmpty()) {
throw new IllegalArgumentException("caching directories were not provided");
}
waitForCoordinator();
startRubix();
}
@PreDestroy
public void stopRubix()
throws IOException
{
try (Closer closer = Closer.create()) {
closer.register(() -> {
if (bookKeeperServer != null) {
// This might throw NPE if Thrift server hasn't started yet (it's initialized
// asynchronously from BookKeeperServer thread).
// TODO: improve stopping of BookKeeperServer server in Rubix
bookKeeperServer.stopServer();
bookKeeperServer = null;
}
});
closer.register(LocalDataTransferServer::stopServer);
}
}
public void enableRubix(Configuration configuration)
{
if (!cacheReady) {
disableRubix(configuration);
return;
}
updateRubixConfiguration(configuration);
setCacheKey(configuration, "rubix_enabled");
}
public void disableRubix(Configuration configuration)
{
setCacheDataEnabled(configuration, false);
setCacheKey(configuration, "rubix_disabled");
}
@VisibleForTesting
boolean isServerUp()
{
return LocalDataTransferServer.isServerUp() && bookKeeperServer != null && bookKeeperServer.isServerUp();
}
private void waitForCoordinator()
{
try {
coordinatorRetryDriver.run(
"waitForCoordinator",
() -> {
if (nodeManager.getAllNodes().stream().noneMatch(Node::isCoordinator)) {
// This exception will only be propagated when timeout is reached.
throw new PrestoException(GENERIC_INTERNAL_ERROR, "No coordinator node available");
}
return null;
});
}
catch (Exception exception) {
propagateIfPossible(exception, PrestoException.class);
throw new RuntimeException(exception);
}
}
private void startRubix()
{
Configuration configuration = getRubixServerConfiguration();
MetricRegistry metricRegistry = new MetricRegistry();
bookKeeperServer = new BookKeeperServer();
BookKeeper bookKeeper = bookKeeperServer.startServer(configuration, metricRegistry);
LocalDataTransferServer.startServer(configuration, metricRegistry, bookKeeper);
CachingFileSystem.setLocalBookKeeper(bookKeeper, "catalog=" + catalogName);
PrestoClusterManager.setNodeManager(nodeManager);
log.info("Rubix initialized successfully");
cacheReady = true;
}
private void setupRubixMetrics()
{
Configuration configuration = getRubixServerConfiguration();
new BookKeeperServer().setupServer(configuration, new MetricRegistry());
CachingFileSystem.setLocalBookKeeper(new DummyBookKeeper(), "catalog=" + catalogName);
PrestoClusterManager.setNodeManager(nodeManager);
}
private Configuration getRubixServerConfiguration()
{
Node master = nodeManager.getAllNodes().stream().filter(Node::isCoordinator).findFirst().get();
masterAddress = master.getHostAndPort();
Configuration configuration = getInitialConfiguration();
// Perform standard HDFS configuration initialization.
hdfsConfigurationInitializer.initializeConfiguration(configuration);
updateRubixConfiguration(configuration);
setCacheKey(configuration, "rubix_internal");
return configuration;
}
private void updateRubixConfiguration(Configuration config)
{
checkState(masterAddress != null, "masterAddress is not set");
setCacheDataEnabled(config, true);
setOnMaster(config, nodeManager.getCurrentNode().isCoordinator());
setCoordinatorHostName(config, masterAddress.getHostText());
setIsParallelWarmupEnabled(config, parallelWarmupEnabled);
setCacheDataExpirationAfterWrite(config, cacheTtlMillis);
setCacheDataFullnessPercentage(config, diskUsagePercentage);
setBookKeeperServerPort(config, bookKeeperServerPort);
setDataTransferServerPort(config, dataTransferServerPort);
setEmbeddedMode(config, true);
enableHeartbeat(config, false);
setClusterNodeRefreshTime(config, 10);
if (nodeManager.getCurrentNode().isCoordinator() && !startServerOnCoordinator) {
// disable initialization of cache directories on master which hasn't got cache explicitly enabled
setCacheDataOnMasterEnabled(config, false);
}
else {
setCacheDataDirPrefix(config, cacheLocation.get());
}
config.set("fs.s3.impl", RUBIX_S3_FS_CLASS_NAME);
config.set("fs.s3a.impl", RUBIX_S3_FS_CLASS_NAME);
config.set("fs.s3n.impl", RUBIX_S3_FS_CLASS_NAME);
config.set("fs.wasb.impl", RUBIX_NATIVE_AZURE_FS_CLASS_NAME);
config.set("fs.wasbs.impl", RUBIX_SECURE_NATIVE_AZURE_FS_CLASS_NAME);
config.set("fs.abfs.impl", RUBIX_AZURE_BLOB_FS_CLASS_NAME);
config.set("fs.abfss.impl", RUBIX_SECURE_AZURE_BLOB_FS_CLASS_NAME);
config.set("fs.adl.impl", RUBIX_SECURE_ADL_CLASS_NAME);
config.set("fs.gs.impl", RUBIX_GS_FS_CLASS_NAME);
rubixHdfsInitializer.initializeConfiguration(config);
}
}
|
{
"content_hash": "092b36e4fa63e6fcead557a278014839",
"timestamp": "",
"source": "github",
"line_count": 313,
"max_line_length": 138,
"avg_line_length": 43.72843450479233,
"alnum_prop": 0.7247022722291225,
"repo_name": "martint/presto",
"id": "77b98473e5e45ed04b00952e57009491cbef8766",
"size": "13687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "presto-hive/src/main/java/io/prestosql/plugin/hive/rubix/RubixInitializer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "30339"
},
{
"name": "CSS",
"bytes": "17830"
},
{
"name": "Dockerfile",
"bytes": "1419"
},
{
"name": "Groovy",
"bytes": "1547"
},
{
"name": "HTML",
"bytes": "24210"
},
{
"name": "Java",
"bytes": "41450945"
},
{
"name": "JavaScript",
"bytes": "219907"
},
{
"name": "PLSQL",
"bytes": "2990"
},
{
"name": "Python",
"bytes": "9304"
},
{
"name": "SQLPL",
"bytes": "926"
},
{
"name": "Shell",
"bytes": "42170"
},
{
"name": "TSQL",
"bytes": "169681"
},
{
"name": "Thrift",
"bytes": "12598"
}
],
"symlink_target": ""
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/artifactregistry/v1/version.proto
package com.google.devtools.artifactregistry.v1;
/**
*
*
* <pre>
* The view, which determines what version information is returned in a
* response.
* </pre>
*
* Protobuf enum {@code google.devtools.artifactregistry.v1.VersionView}
*/
public enum VersionView implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* The default / unset value.
* The API will default to the BASIC view.
* </pre>
*
* <code>VERSION_VIEW_UNSPECIFIED = 0;</code>
*/
VERSION_VIEW_UNSPECIFIED(0),
/**
*
*
* <pre>
* Includes basic information about the version, but not any related tags.
* </pre>
*
* <code>BASIC = 1;</code>
*/
BASIC(1),
/**
*
*
* <pre>
* Include everything.
* </pre>
*
* <code>FULL = 2;</code>
*/
FULL(2),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* The default / unset value.
* The API will default to the BASIC view.
* </pre>
*
* <code>VERSION_VIEW_UNSPECIFIED = 0;</code>
*/
public static final int VERSION_VIEW_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* Includes basic information about the version, but not any related tags.
* </pre>
*
* <code>BASIC = 1;</code>
*/
public static final int BASIC_VALUE = 1;
/**
*
*
* <pre>
* Include everything.
* </pre>
*
* <code>FULL = 2;</code>
*/
public static final int FULL_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static VersionView valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static VersionView forNumber(int value) {
switch (value) {
case 0:
return VERSION_VIEW_UNSPECIFIED;
case 1:
return BASIC;
case 2:
return FULL;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<VersionView> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<VersionView> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<VersionView>() {
public VersionView findValueByNumber(int number) {
return VersionView.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1.VersionProto.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final VersionView[] VALUES = values();
public static VersionView valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private VersionView(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.devtools.artifactregistry.v1.VersionView)
}
|
{
"content_hash": "fc6445d19157128dff23b625e133b308",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 96,
"avg_line_length": 24.61676646706587,
"alnum_prop": 0.647044514716614,
"repo_name": "googleapis/java-artifact-registry",
"id": "c210c72e0f632770253c00e897beb7c3fce322c0",
"size": "4705",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/VersionView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "5058549"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "20474"
}
],
"symlink_target": ""
}
|
{-# htermination readOct :: String -> [(Int,String)] #-}
|
{
"content_hash": "f121a4431f07e9b5532aeb9a8cb28c21",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 56,
"avg_line_length": 57,
"alnum_prop": 0.5964912280701754,
"repo_name": "ComputationWithBoundedResources/ara-inference",
"id": "ec2942cc83412d33e0c4d9d2ae909fa2d2b1c3b7",
"size": "57",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/tpdb_trs/Haskell/full_haskell/Prelude_readOct_1.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "352897"
},
{
"name": "Shell",
"bytes": "4012"
}
],
"symlink_target": ""
}
|
"""Fractal demo."""
from __future__ import with_statement
__author__ = 'kbrisbin@google.com (Kathryn Hurley)'
import json
import logging
import os
import time
import lib_path
import google_cloud.gce as gce
import google_cloud.gce_appengine as gce_appengine
import google_cloud.oauth as oauth
import jinja2
import oauth2client.appengine as oauth2client
import user_data
import webapp2
from google.appengine.api import urlfetch
DEMO_NAME = 'fractal'
CUSTOM_IMAGE = 'fractal-demo-image'
MACHINE_TYPE='n1-highcpu-2'
FIREWALL = 'www-fractal'
FIREWALL_DESCRIPTION = 'Fractal Demo Firewall'
GCE_SCOPE = 'https://www.googleapis.com/auth/compute'
HEALTH_CHECK_TIMEOUT = 1
VM_FILES = os.path.join(os.path.dirname(__file__), 'vm_files')
STARTUP_SCRIPT = os.path.join(VM_FILES, 'startup.sh')
GO_PROGRAM = os.path.join(VM_FILES, 'mandelbrot.go')
GO_ARGS = '--portBase=80 --numPorts=1'
GO_TILESERVER_FLAG = '--tileServers='
# TODO: Update these values with your project and LB IP/destinations.
LB_PROJECTS = {
'your-project': ['a.b.c.d'],
}
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(''))
oauth_decorator = oauth.decorator
parameters = [
user_data.DEFAULTS[user_data.GCE_PROJECT_ID],
user_data.DEFAULTS[user_data.GCE_ZONE_NAME]
]
data_handler = user_data.DataHandler(DEMO_NAME, parameters)
class ServerVarsAggregator(object):
"""Aggregate stats across multiple servers and produce a summary."""
def __init__(self):
"""Constructor for ServerVarsAggregator."""
# A map of tile-size -> count
self.tile_counts = {}
# A map of tile-size -> time
self.tile_times = {}
# The uptime of the server that has been up and running the longest.
self.max_uptime = 0
def aggregate_vars(self, instance_vars):
"""Integrate instance_vars into the running aggregates.
Args:
instance_vars A parsed JSON object returned from /debug/vars
"""
self._aggregate_map(instance_vars['tileCount'], self.tile_counts)
self._aggregate_map(instance_vars['tileTime'], self.tile_times)
self.max_uptime = max(self.max_uptime, instance_vars['uptime'])
def _aggregate_map(self, src_map, dest_map):
"""Aggregate one map from src_map into dest_map."""
for k, v in src_map.items():
dest_map[k] = dest_map.get(k, 0L) + long(v)
def get_aggregate(self):
"""Get the overall aggregate, including derived values."""
tile_time_avg = {}
result = {
'tileCount': self.tile_counts.copy(),
'tileTime': self.tile_times.copy(),
'tileTimeAvgMs': tile_time_avg,
'maxUptime': self.max_uptime,
}
for size, count in self.tile_counts.items():
time = self.tile_times.get(size, 0)
if time and count:
# Compute average tile time in milliseconds. The raw time is in
# nanoseconds.
tile_time_avg[size] = float(time / count) / float(1000*1000)
logging.debug('tile-size: %s count: %d time: %d avg: %d', size, count, time, tile_time_avg[size])
return result
class Fractal(webapp2.RequestHandler):
"""Fractal demo."""
@oauth_decorator.oauth_required
@data_handler.data_required
def get(self):
"""Show main page of Fractal demo."""
template = jinja_environment.get_template(
'demos/%s/templates/index.html' % DEMO_NAME)
gce_project_id = data_handler.stored_user_data[user_data.GCE_PROJECT_ID]
self.response.out.write(template.render({
'demo_name': DEMO_NAME,
'lb_enabled': gce_project_id in LB_PROJECTS,
}))
@oauth_decorator.oauth_required
@data_handler.data_required
def get_instances(self):
"""List instances.
Uses app engine app identity to retrieve an access token for the app
engine service account. No client OAuth required. External IP is used
to determine if the instance is actually running.
"""
gce_project = self._create_gce()
instances = gce_appengine.GceAppEngine().run_gce_request(
self,
gce_project.list_instances,
'Error listing instances: ',
filter='name eq ^%s-.*' % self.instance_prefix())
# A map of instanceName -> (ip, RPC)
health_rpcs = {}
# Convert instance info to dict and check server status.
num_running = 0
instance_dict = {}
if instances:
for instance in instances:
instance_record = {}
instance_dict[instance.name] = instance_record
if instance.status:
instance_record['status'] = instance.status
else:
instance_record['status'] = 'OTHER'
ip = None
for interface in instance.network_interfaces:
for config in interface.get('accessConfigs', []):
if 'natIP' in config:
ip = config['natIP']
instance_record['externalIp'] = ip
break
if ip: break
# Ping the instance server. Grab stats from /debug/vars.
if ip and instance.status == 'RUNNING':
num_running += 1
health_url = 'http://%s/debug/vars?t=%d' % (ip, int(time.time()))
logging.debug('Health checking %s', health_url)
rpc = urlfetch.create_rpc(deadline = HEALTH_CHECK_TIMEOUT)
urlfetch.make_fetch_call(rpc, url=health_url)
health_rpcs[instance.name] = rpc
# Ping through a LBs too. Only if we get success there do we know we are
# really serving.
loadbalancers = []
lb_rpcs = {}
if instances and len(instances) > 1:
loadbalancers = self._get_lb_servers(gce_project)
if num_running > 0 and loadbalancers:
for lb in loadbalancers:
health_url = 'http://%s/health?t=%d' % (lb, int(time.time()))
logging.debug('Health checking %s', health_url)
rpc = urlfetch.create_rpc(deadline = HEALTH_CHECK_TIMEOUT)
urlfetch.make_fetch_call(rpc, url=health_url)
lb_rpcs[lb] = rpc
# wait for RPCs to complete and update dict as necessary
vars_aggregator = ServerVarsAggregator()
# TODO: there is significant duplication here. Refactor.
for (instance_name, rpc) in health_rpcs.items():
result = None
instance_record = instance_dict[instance_name]
try:
result = rpc.get_result()
if result and "memstats" in result.content:
logging.debug('%s healthy!', instance_name)
instance_record['status'] = 'SERVING'
instance_vars = {}
try:
instance_vars = json.loads(result.content)
instance_record['vars'] = instance_vars
vars_aggregator.aggregate_vars(instance_vars)
except ValueError as error:
logging.error('Error decoding vars json for %s: %s', instance_name, error)
else:
logging.debug('%s unhealthy. Content: %s', instance_name, result.content)
except urlfetch.Error as error:
logging.debug('%s unhealthy: %s', instance_name, str(error))
# Check health status through the load balancer.
loadbalancer_healthy = bool(lb_rpcs)
for (lb, lb_rpc) in lb_rpcs.items():
result = None
try:
result = lb_rpc.get_result()
if result and "ok" in result.content:
logging.info('LB %s healthy: %s\n%s', lb, result.headers, result.content)
else:
logging.info('LB %s result not okay: %s, %s', lb, result.status_code, result.content)
loadbalancer_healthy = False
break
except urlfetch.Error as error:
logging.info('LB %s fetch error: %s', lb, str(error))
loadbalancer_healthy = False
break
response_dict = {
'instances': instance_dict,
'vars': vars_aggregator.get_aggregate(),
'loadbalancers': loadbalancers,
'loadbalancer_healthy': loadbalancer_healthy,
}
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(response_dict))
@oauth_decorator.oauth_required
@data_handler.data_required
def set_instances(self):
"""Start/stop instances so we have the requested number running."""
gce_project = self._create_gce()
self._setup_firewall(gce_project)
image = self._get_image(gce_project)
disks = self._get_disks(gce_project)
# Get the list of instances to insert.
num_instances = int(self.request.get('num_instances'))
target = self._get_instance_list(
gce_project, num_instances, image, disks)
target_set = set()
target_map = {}
for instance in target:
target_set.add(instance.name)
target_map[instance.name] = instance
# Get the list of instances running
current = gce_appengine.GceAppEngine().run_gce_request(
self,
gce_project.list_instances,
'Error listing instances: ',
filter='name eq ^%s-.*' % self.instance_prefix())
current_set = set()
current_map = {}
for instance in current:
current_set.add(instance.name)
current_map[instance.name] = instance
# Add the new instances
to_add_set = target_set - current_set
to_add = [target_map[name] for name in to_add_set]
if to_add:
gce_appengine.GceAppEngine().run_gce_request(
self,
gce_project.bulk_insert,
'Error inserting instances: ',
resources=to_add)
# Remove the old instances
to_remove_set = current_set - target_set
to_remove = [current_map[name] for name in to_remove_set]
if to_remove:
gce_appengine.GceAppEngine().run_gce_request(
self,
gce_project.bulk_delete,
'Error deleting instances: ',
resources=to_remove)
logging.info("current_set: %s", current_set)
logging.info("target_set: %s", target_set)
logging.info("to_add_set: %s", to_add_set)
logging.info("to_remove_set: %s", to_remove_set)
@oauth_decorator.oauth_required
@data_handler.data_required
def cleanup(self):
"""Stop instances using the gce_appengine helper class."""
gce_project = self._create_gce()
gce_appengine.GceAppEngine().delete_demo_instances(
self, gce_project, self.instance_prefix())
def _get_lb_servers(self, gce_project):
return LB_PROJECTS.get(gce_project.project_id, [])
def instance_prefix(self):
"""Return a prefix based on a request/query params."""
tag = self.request.get('tag')
prefix = DEMO_NAME
if tag:
prefix = prefix + '-' + tag
return prefix
def _create_gce(self):
gce_project_id = data_handler.stored_user_data[user_data.GCE_PROJECT_ID]
gce_zone_name = data_handler.stored_user_data[user_data.GCE_ZONE_NAME]
return gce.GceProject(oauth_decorator.credentials,
project_id=gce_project_id,
zone_name=gce_zone_name)
def _setup_firewall(self, gce_project):
"Create the firewall if it doesn't exist."
firewalls = gce_project.list_firewalls()
firewall_names = [firewall.name for firewall in firewalls]
if not FIREWALL in firewall_names:
firewall = gce.Firewall(
name=FIREWALL,
target_tags=[DEMO_NAME],
description=FIREWALL_DESCRIPTION)
gce_project.insert(firewall)
def _get_image(self, gce_project):
"""Returns the appropriate image to use. def _has_custom_image(self, gce_project):
Args:
gce_project: An instance of gce.GceProject
Returns: (project, image_name) for the image to use.
"""
images = gce_project.list_images(filter='name eq ^%s$' % CUSTOM_IMAGE)
if images:
return (gce_project.project_id, CUSTOM_IMAGE)
return ('google', None)
def _get_disks(self, gce_project):
"""Get boot disks for VMs."""
disks_array = gce_project.list_disks(
filter='name eq ^boot-%s-.*' % self.instance_prefix())
disks = {}
for d in disks_array:
disks[d.name] = d
return disks
def _get_instance_metadata(self, gce_project, instance_names):
"""The metadata values to pass into the instance."""
inline_values = {
'goargs': GO_ARGS,
}
file_values = {
'startup-script': STARTUP_SCRIPT,
'goprog': GO_PROGRAM,
}
# Try and use LBs if we have any. But only do that if we have more than one
# instance.
if instance_names:
tile_servers = ''
if len(instance_names) > 1:
tile_servers = self._get_lb_servers(gce_project)
if not tile_servers:
tile_servers = instance_names
tile_servers = ','.join(tile_servers)
inline_values['goargs'] += ' %s%s' %(GO_TILESERVER_FLAG, tile_servers)
metadata = []
for k, v in inline_values.items():
metadata.append({'key': k, 'value': v})
for k, fv in file_values.items():
v = open(fv, 'r').read()
metadata.append({'key': k, 'value': v})
return metadata
def _get_instance_list(self, gce_project, num_instances, image, disks):
"""Get a list of instances to start.
Args:
gce_project: An instance of gce.GceProject.
num_instances: The number of instances to start.
image: tuple with (project_name, image_name) for the image to use.
disks: A dictionary of disk_name -> disk resources
Returns:
A list of gce.Instances.
"""
instance_names = []
for i in range(num_instances):
instance_names.append('%s-%02d' % (self.instance_prefix(), i))
instance_list = []
for instance_name in instance_names:
disk_name = 'boot-%s' % instance_name
disk = disks.get(disk_name, None)
disk_mounts = []
image_project_id = None
image_name = None
kernel = None
if disk:
dm = gce.DiskMount(disk=disk, boot=True)
kernel = gce_project.settings['compute']['kernel']
disk_mounts.append(dm)
else:
image_project_id, image_name = image
instance = gce.Instance(
name=instance_name,
machine_type_name=MACHINE_TYPE,
image_name=image_name,
image_project_id=image_project_id,
disk_mounts=disk_mounts,
kernel=kernel,
tags=[DEMO_NAME, self.instance_prefix()],
metadata=self._get_instance_metadata(gce_project, instance_names),
service_accounts=gce_project.settings['cloud_service_account'])
instance_list.append(instance)
return instance_list
app = webapp2.WSGIApplication(
[
('/%s' % DEMO_NAME, Fractal),
webapp2.Route('/%s/instance' % DEMO_NAME,
handler=Fractal, handler_method='get_instances',
methods=['GET']),
webapp2.Route('/%s/instance' % DEMO_NAME,
handler=Fractal, handler_method='set_instances',
methods=['POST']),
webapp2.Route('/%s/cleanup' % DEMO_NAME,
handler=Fractal, handler_method='cleanup',
methods=['POST']),
(data_handler.url_path, data_handler.data_handler),
], debug=True)
|
{
"content_hash": "82fe85462940c6a3f0369a8b7f7adb75",
"timestamp": "",
"source": "github",
"line_count": 437,
"max_line_length": 105,
"avg_line_length": 33.807780320366135,
"alnum_prop": 0.6357113848653039,
"repo_name": "jbeda/compute-appengine-demo-suite-python",
"id": "a15516b6ad266623df21eb9459ed356463a20164",
"size": "15372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo-suite/demos/fractal/main.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "13533"
},
{
"name": "JavaScript",
"bytes": "58331"
},
{
"name": "Perl",
"bytes": "561"
},
{
"name": "Python",
"bytes": "82731"
},
{
"name": "Shell",
"bytes": "2898"
}
],
"symlink_target": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.