text:
package csimigration

import (
	"errors"
	"fmt"

	v1 "k8s.io/api/core/v1"
	"k8s.io/component-base/featuregate"
	csilibplugins "k8s.io/csi-translation-lib/plugins"
	"k8s.io/kubernetes/pkg/features"
	"k8s.io/kubernetes/pkg/volume"
)

// PluginNameMapper contains utility methods to retrieve names of plugins
// that support a spec, map intree <=> migrated CSI plugin names, etc
type PluginNameMapper interface {
	GetInTreePluginNameFromSpec(pv *v1.PersistentVolume, vol *v1.Volume) (string, error)
	GetCSINameFromInTreeName(pluginName string) (string, error)
}

// PluginManager keeps track of migrated state of in-tree plugins
type PluginManager struct {
	PluginNameMapper
	featureGate featuregate.FeatureGate

	useADCPluginManagerFeatureGates bool
}

// NewPluginManager returns a new PluginManager instance
func NewPluginManager(m PluginNameMapper, featureGate featuregate.FeatureGate) PluginManager {
	return PluginManager{
		PluginNameMapper: m,
		featureGate:      featureGate,
	}
}

// IsMigrationCompleteForPlugin indicates whether CSI migration has been completed
// for a particular storage plugin. A complete migration will need to:
// 1. Enable CSIMigrationXX for the plugin
// 2. Unregister the in-tree plugin by setting the InTreePluginXXUnregister feature gate
func (pm PluginManager) IsMigrationCompleteForPlugin(pluginName string) bool {
	// CSIMigration feature and plugin specific InTreePluginUnregister feature flags should
	// be enabled for plugin specific migration completion to be take effect
	if !pm.IsMigrationEnabledForPlugin(pluginName) {
		return false
	}

	switch pluginName {
	case csilibplugins.AWSEBSInTreePluginName:
		return pm.featureGate.Enabled(features.InTreePluginAWSUnregister)
	case csilibplugins.GCEPDInTreePluginName:
		return pm.featureGate.Enabled(features.InTreePluginGCEUnregister)
	case csilibplugins.AzureFileInTreePluginName:
		return pm.featureGate.Enabled(features.InTreePluginAzureFileUnregister)
	case csilibplugins.AzureDiskInTreePluginName:
		return pm.featureGate.Enabled(features.InTreePluginAzureDiskUnregister)
	case csilibplugins.CinderInTreePluginName:
		return pm.featureGate.Enabled(features.InTreePluginOpenStackUnregister)
	case csilibplugins.VSphereInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationvSphereComplete) || pm.featureGate.Enabled(features.InTreePluginvSphereUnregister)
	default:
		return false
	}
}

func (pm PluginManager) isMigrationEnabledForPlugin(pluginName string) bool {
	// CSIMigration feature should be enabled along with the plugin-specific one
	if !pm.featureGate.Enabled(features.CSIMigration) {
		return false
	}

	switch pluginName {
	case csilibplugins.AWSEBSInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationAWS)
	case csilibplugins.GCEPDInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationGCE)
	case csilibplugins.AzureFileInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationAzureFile)
	case csilibplugins.AzureDiskInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationAzureDisk)
	case csilibplugins.CinderInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationOpenStack)
	case csilibplugins.VSphereInTreePluginName:
		return pm.featureGate.Enabled(features.CSIMigrationvSphere)
	default:
		return false
	}
}

// IsMigratable indicates whether CSI migration has been enabled for a volume
// plugin that the spec refers to
func (pm PluginManager) IsMigratable(spec *volume.Spec) (bool, error) {
	if spec == nil {
		return false, fmt.Errorf("could not find if plugin is migratable because volume spec is nil")
	}

	pluginName, _ := pm.GetInTreePluginNameFromSpec(spec.PersistentVolume, spec.Volume)
	if pluginName == "" {
		return false, nil
	}
	// found an in-tree plugin that supports the spec
	return pm.IsMigrationEnabledForPlugin(pluginName), nil
}

// InTreeToCSITranslator performs translation of Volume sources for PV and Volume objects
// from references to in-tree plugins to migrated CSI plugins
type InTreeToCSITranslator interface {
	TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
	TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)
}

// TranslateInTreeSpecToCSI translates a volume spec (either PV or inline volume)
// supported by an in-tree plugin to CSI
func TranslateInTreeSpecToCSI(spec *volume.Spec, podNamespace string, translator InTreeToCSITranslator) (*volume.Spec, error) {
	var csiPV *v1.PersistentVolume
	var err error
	inlineVolume := false
	if spec.PersistentVolume != nil {
		csiPV, err = translator.TranslateInTreePVToCSI(spec.PersistentVolume)
	} else if spec.Volume != nil {
		csiPV, err = translator.TranslateInTreeInlineVolumeToCSI(spec.Volume, podNamespace)
		inlineVolume = true
	} else {
		err = errors.New("not a valid volume spec")
	}
	if err != nil {
		return nil, fmt.Errorf("failed to translate in-tree pv to CSI: %v", err)
	}
	return &volume.Spec{
		Migrated:                        true,
		PersistentVolume:                csiPV,
		ReadOnly:                        spec.ReadOnly,
		InlineVolumeSpecForCSIMigration: inlineVolume,
	}, nil
}

// CheckMigrationFeatureFlags checks the configuration of feature flags related
// to CSI Migration is valid. It will return whether the migration is complete
// by looking up the pluginMigrationComplete and pluginUnregister flag
func CheckMigrationFeatureFlags(f featuregate.FeatureGate, pluginMigration,
	pluginMigrationComplete, pluginUnregister featuregate.Feature) (migrationComplete bool, err error) {
	if f.Enabled(pluginMigration) && !f.Enabled(features.CSIMigration) {
		return false, fmt.Errorf("enabling %q requires CSIMigration to be enabled", pluginMigration)
	}
	// TODO: Remove the following two checks once the CSIMigrationXXComplete flag is removed
	if pluginMigrationComplete != "" && f.Enabled(pluginMigrationComplete) && !f.Enabled(pluginMigration) {
		return false, fmt.Errorf("enabling %q requires %q to be enabled", pluginMigrationComplete, pluginMigration)
	}
	// This is only needed for vSphere since we will deprecate the CSIMigrationvSphereComplete flag soon
	if pluginMigrationComplete != "" && f.Enabled(features.CSIMigration) &&
		f.Enabled(pluginMigration) && f.Enabled(pluginMigrationComplete) {
		return true, nil
	}
	// This is for other in-tree plugin that get migration finished
	if f.Enabled(pluginMigration) && f.Enabled(pluginUnregister) {
		return true, nil
	}
	return false, nil
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Reflection;
using Xunit;

namespace System.Linq.Expressions.Tests
{
    public static class UnaryIsTrueNullableTests
    {
        #region Test methods

        [Fact] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")]
        public static void CheckUnaryIsTrueNullableBoolTest()
        {
            bool?[] values = new bool?[] { null, false, true };
            for (int i = 0; i < values.Length; i++)
            {
                VerifyIsTrueNullableBool(values[i]);
            }
        }

        #endregion

        #region Test verifiers

        private static void VerifyIsTrueNullableBool(bool? value)
        {
            Expression<Func<bool?>> e =
                Expression.Lambda<Func<bool?>>(
                    Expression.IsTrue(Expression.Constant(value, typeof(bool?))),
                    Enumerable.Empty<ParameterExpression>());
            Func<bool?> f = e.Compile();
            Assert.Equal((bool?)(value == default(bool?) ? default(bool?) : value == true), f());
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using MusicPlayer.Managers;
using System.Threading.Tasks;
using MusicPlayer.Models;

namespace MusicPlayer
{
	public class BackgroundDownloadManager: ManagerBase<BackgroundDownloadManager>
	{
		public BackgroundDownloadManager ()
		{
		}

		public async Task Download (Track track)
		{
			App.ShowNotImplmented();
		}

		public int Count {
			get;
			set;
		}

		public Song PendingItemForRow (int row)
		{
			throw new NotImplementedException ();
		}

		public async Task Init ()
		{

		}
	}
}


text:
% generate the animated take
filename = '/data/HDM/HDM05_EG08/HDM05_CMU_EG08_tiny/cmu/CMU_01_jumping_01forwardMultiple+_120.amc';
info = filename2info(filename);
[skel,mot] = readMocap(fullfile(info.amcpath, info.asfname), fullfile(info.amcpath, info.amcname));
document=53;

docName = [info.amcname(1:end-4) '_doc' num2str(document)];

downsampling = 4;
compression = 'ffds';
quality = 100;
fps = 30;
figureSize = [800, 600];

if ~exist(['intro_' docName '.avi'], 'file') % generate the new video
    cameraFilename = ['intro_camera_' docName];
    if ~exist([cameraFilename '.m'], 'file')
        error(['If you want me to generate the video, you first have to generate the camera file ' [cameraFilename '.m'] '!']);
    end
    % at first generate the camera file
    % motionplayer('skel', {skel}, 'mot', {mot});
    % delete(findobj(gcf, 'type', 'uipanel'));
    % set(gcf, 'position', [1700, 200, 800, 250]);
    % saveCamera(gca, [cameraFilename '.m'])

    parameter.filename = ['intro_' docName];
    parameter.fps = fps;
    parameter.compression = compression;
    parameter.quality = quality;
    parameter.position = [300,300];
    parameter.size = figureSize;
    parameter.motDownsampling = downsampling;
    parameter.cameraFcn = cameraFilename;
    avi1=motionplayerVideo(skel, mot, parameter);
end

% now generate the animation of the annotation image, only coarse annotation.
addpath('./take_CMU_01_jumping_01forwardMultiple+_120.amc');

load Variables.mat

frames = 1:downsampling:mot.nframes;

aviobj = avifile(['intro_annotation_' docName], ...
    'compression',  'none', ...
    'quality',quality,...
    'fps',fps);

%     'compression',  compression, ...

parameter.position = [100, 100, 800, 350];
parameter.drawFineAnnotations = 0;

for f=1:length(frames);
    parameter.highlightFrame = f;
    plotMultiLayerResult2Fig_forVideo(annotation,h4File, parameter)
    frame = getframe(gcf);

    aviobj = addframe(aviobj,frame);
    close all hidden;

end

aviobj=close(aviobj);

% now generate the animation of the annotation image, now with fine annotation.
aviobj = avifile(['intro_annotationFine_' docName], ...
    'compression',  'none', ...
    'quality',quality,...
    'fps',fps);

%     'compression',  compression, ...

parameter.position = [100, 100, 800, 350];
parameter.drawFineAnnotations = 1;

for f=1:length(frames);
    parameter.highlightFrame = f;
    plotMultiLayerResult2Fig_forVideo(annotation,h4File, parameter)
    frame = getframe(gcf);

    aviobj = addframe(aviobj,frame);
    close all hidden;

end

aviobj=close(aviobj);

VARS_GLOBAL_ANIM.video_compression = 'ffds';
concatVideos_spatial({['intro_' docName '.avi'], ['intro_annotation_' docName '.avi']},['intro_annotationComparison_coarse'],'v');
concatVideos_spatial({['intro_' docName '.avi'], ['intro_annotationFine_' docName '.avi']},['intro_annotationComparison_fine'],'v');


text:
package org.wso2.carbon.messaging;

import java.util.HashMap;
import java.util.Map;

/**
 * Abstract implementation for the CarbonCallback.
 * Methods of this class are not thread-safe
 *
 * @since 2.3.2
 */
public abstract class AbstractCarbonCallback implements CarbonCallback {

    protected Map<String, Object> properties = new HashMap<>();

    /**
     * Get a property associated with the callback
     *
     * @param key property name
     * @return property for a particular key
     */
    public Object getProperty(String key) {
        return properties.get(key);
    }

    /**
     * Get all the properties associated with the callback
     *
     * @return map of all the properties
     */
    public Map<String, Object> getProperties() {
        return properties;
    }

    /**
     * Set a property which is associated with the callback
     *
     * @param key   key of the property
     * @param value value of the property
     */
    public void setProperty(String key, Object value) {
        properties.put(key, value);
    }

    /**
     * Remove a property associated with the callback
     *
     * @param key key of the property
     */
    public void removeProperty(String key) {
        properties.remove(key);
    }

}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit5b938720cfef7b7256946290ccab109b::getLoader();


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

Socializing

Wedding Discussion

  A: I always get so emotional at weddings.
 B: Me too, especially when I see the bride and groom kiss.
 A: The bride looked so beautiful.
 B: She did, and the groom looked so dapper in his tux.
 A: I'll see you at the reception in a little bit.
 B: No, you won't, because I wasn't invited.
 A: Oh, I'm so sorry. Maybe your invite was lost in the mail.
 B: It's okay. Why don't you bring me as your plus one?
 A: Actually no, because I'm going with my husband.
 B: Please take pictures so I can see how nice everyone looked.
 A: I'm sure there will be pictures online afterwards.
 B: It's not the same as being there.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
The implementation of correct fragment lifecycle

### Conclusion
The fragments have similar lifecycle than activities, but they more times destroys their views in the FragmentManager and other times not destroy.

This is an implementation of custom methods for work with child fragment manager and activities and for correct management of OnBackPressed runs on Android SO without override the method.

There are the abstract class BaseFragment which purpose is simplify implementation, and an example of use of them.

### Life cycle of the fragment
* **onAttach()** The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.

  Practice: You can atach all listeners wich implements the Context wich invoke this fragment (Activity or Fragment).

* **onCreate()** The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

 Practice: You should initialize essential components of the fragment that you want to retain (no linked in views, and not a component of view).

* **onCreateView()** The system calls this callback when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

* **onViewCreated()** The onViewCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object

 Practice: You should link screen with parameters of your fragment (or anonymous parameters). You should only link screen.

* **onStart()** The onStart() method is called once the fragment gets visible.

 Practice: This you should start the load data on components if you would programmicaly change. In this article method loadDataSceen(); The cause of you should put this in it, if you update a data of your fragment created, the lifecycle of the fragment run this method before created/updated data (in all posibilities: the fragment destroy the view, and the resumed fragment without destroy the view.

 Activity: call update function after the transaction.

* **onResume()** Fragment becomes active.

* **onPause()** The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.

* **onStop()** Fragment going to be stopped by calling onStop()

* **onDestroyView()** Fragment view will destroy after call this method

 Practice: for correct debug of application, you can deinitialize the parameters of the fragment relationated with the view (You don't have view).

* **onDestroy()** onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be called by the Android platform.

# Bibliography
https://www.tutorialspoint.com/android/android_fragments.htm
and analysis debug with Android Studio


text:
package com.sarality.app.config;

public interface AppStateValue<T> {

  public T getValue();

  public boolean isEditable();

  public void setValue(T value);
}


text:
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

namespace NLog
{
    /// <summary>
    /// Interface for handling object transformation
    /// </summary>
    internal interface IObjectTypeTransformer
    {
        /// <summary>
        /// Takes a dangerous (or massive) object and converts into a safe (or reduced) object
        /// </summary>
        /// <returns>
        /// Null if unknown object, or object cannot be handled
        /// </returns>
        object TryTransformObject(object obj);
    }
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Utilities

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticEndConstructCorrection
    <[UseExportProvider]>
    <Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
    Public Class AutomaticEndConstructCorrectorTests
        <WpfFact>
        Public Sub TestStructureToInterface()
            Dim code = [|Structure|] A
End [|Structure|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestEnumToInterface()
            Dim code = [|Enum|] A
End [|Enum|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestInterfaceToEnum()
            Dim code = [|Interface|] A
End [|Interface|].Value

            Verify(code, "Enum")
        End Sub

        <WpfFact>
        Public Sub TestClassToInterface()
            Dim code = [|Class|] A
End [|Class|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestModuleToInterface()
            Dim code = [|Module|] A
End [|Module|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestNamespaceToInterface()
            Dim code = [|Namespace|] A
End [|Namespace|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestSubToFunction()
            Dim code = Class A
    [|Sub|] Test()
    End [|Sub|]
End Class.Value

            Verify(code, "Function")
        End Sub

        <WpfFact>
        Public Sub TestFunctionToSub()
            Dim code = Class A
    [|Function|] Test() As Integer
    End [|Function|]
End Class.Value

            Verify(code, "Sub")
        End Sub

        <WpfFact>
        Public Sub TestModuleToInterface1()
            Dim code = [|Module|] A : End [|Module|] : Module B : End Module.Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestModuleToInterface2()
            Dim code = Module A : End Module : [|Module|] B : End [|Module|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestModuleToInterface3()
            Dim code = Module A : End Module:[|Module|] B : End [|Module|].Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestModuleToInterface4()
            Dim code = [|Module|] A : End [|Module|]:Module B : End Module.Value

            Verify(code, "Interface")
        End Sub

        <WpfFact>
        Public Sub TestErrorCaseMissingEndFunction()
            Dim code = Class A
    [|Function|] Test() As Integer
    End [|Sub|]
End Class.Value.Replace(vbLf, vbCrLf)

            VerifyBegin(code, "Interface", "Sub")
            VerifyEnd(code, "Interface", "Function")
        End Sub

        <WpfFact>
        Public Sub TestContinuousEditsOnFunctionToInterface()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
        End Sub

        <WpfFact>
        Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingSpaces()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "     Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
        End Sub

        <WpfFact>
        Public Sub TestContinuousEditsOnFunctionToInterfaceWithTrailingSpaces()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "Interface              ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
        End Sub

        <WpfFact>
        Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingAndTrailingSpaces()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "             Interface              ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
        End Sub

        <WpfFact>
        Public Sub TestAddSharedModifierToFunction()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, " Shared ", Function(s) "Function", removeOriginalContent:=False)
        End Sub

        <WpfFact>
        Public Sub TestAddSharedModifierToFunction1()
            Dim code = Class A
    [|Function$$|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "Shared   ", Function(s) "Function", removeOriginalContent:=False)
        End Sub

        <WpfFact>
        Public Sub TestAddTrailingSpaceToFunction()
            Dim code = Class A
    [|Function$$|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "           ", Function(s) "Function", removeOriginalContent:=False)
        End Sub

        <WpfFact>
        Public Sub TestAddLeadingSpaceToFunction()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "           ", Function(s) "Function", removeOriginalContent:=False)
        End Sub

        <WpfFact>
        Public Sub TestAddSharedModifierToFunction2()
            Dim code = Class A
    [|Function$$|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "Shared", Function(s) "Function", removeOriginalContent:=False, split:="Function")
        End Sub

        <WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
        <WpfFact>
        Public Sub TestMultiLineLambdaSubToFunction()
            Dim code = Class A
    Public Sub F()
        Dim nums() As Integer = {1, 2, 3, 4, 5}
        Array.ForEach(nums, [|Sub|](n)
                                Console.Write("Number: ")
                                Console.WriteLine(n)
                            End [|Sub|])
    End Sub
End Class.Value

            Verify(code, "Function")
        End Sub

        <WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
        <WpfFact>
        Public Sub TestMultiLineLambdaFunctionToSub()
            Dim code = Class A
    Public Sub F()
        Dim nums() As Integer = {1, 2, 3, 4, 5}
        Dim numDelegate = [|Function|](n As Integer)

                          End [|Function|]
    End Sub
End Class.Value

            Verify(code, "Sub")
        End Sub

        <WorkItem(539365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539365")>
        <WpfFact>
        Public Sub BugFix5290()
            Dim code = Public Class Class1
    Sub M()
        [|Class|]
    End Sub
End [|Class|].Value

            VerifyBegin(code, "Structure", "Class")
            VerifyEnd(code, "Structure", "Class")
        End Sub

        <WorkItem(539357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539357")>
        <WpfFact>
        Public Sub TestBugFix5276()
            Dim code = Class A
    [|Func$$tion|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "  ", Function(s) "Function", removeOriginalContent:=False)
        End Sub

        <WorkItem(539360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539360")>
        <WpfFact>
        Public Sub TestBugFix5283()
            Dim code = Class A
    [|$$Function|] Test() As Integer
    End [|Function|]
End Class.Value

            VerifyContinuousEdits(code, "Shared Sub", Function(s) If(s.Trim() = "Shared Sub", "Sub", "Function"), removeOriginalContent:=True)
        End Sub

        <WpfFact, WorkItem(539498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539498")>
        Public Sub TestDontThrowDueToSingleLineDeletion()
            Dim code = Class A
    [|$$Sub M() : End Sub|]
End Class.Value

            VerifyContinuousEdits(code, "", Function() "", removeOriginalContent:=True)
        End Sub

        <WpfFact>
        Public Sub TestPropertySet()
            Dim code = Class A
    Property Test
        [|Get|]
        End [|Get|]
        Set(value)
        End Set
    End Property
End Class.Value

            Verify(code, "Set")
        End Sub

        <WpfFact>
        Public Sub TestPropertyGet()
            Dim code = Class A
    Property Test
        Get
        End Get
        [|Set|](value)
        End [|Set|]
    End Property
End Class.Value

            Verify(code, "Get")
        End Sub

        Private Shared Sub VerifyContinuousEdits(codeWithMarker As String,
                                          type As String,
                                          expectedStringGetter As Func(Of String, String),
                                          removeOriginalContent As Boolean,
                                          Optional split As String = Nothing)
            ' do this since xml value put only vbLf
            codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)

            Using workspace = TestWorkspace.CreateVisualBasic(codeWithMarker)
                Dim document = workspace.Documents.Single()

                Dim buffer = document.GetTextBuffer()
                Dim initialTextSnapshot = buffer.CurrentSnapshot

                Dim caretPosition = initialTextSnapshot.CreateTrackingPoint(document.CursorPosition.Value,
                                                                            PointTrackingMode.Positive,
                                                                            TrackingFidelityMode.Backward)
                Dim corrector = New AutomaticEndConstructCorrector(buffer, workspace.GetService(Of IUIThreadOperationExecutor))

                corrector.Connect()

                If removeOriginalContent Then
                    Dim spanToRemove = document.SelectedSpans.Single(Function(s) s.Contains(caretPosition.GetPosition(initialTextSnapshot)))
                    buffer.Replace(spanToRemove.ToSpan(), "")
                End If

                For i = 0 To type.Length - 1
                    Dim charToInsert = type(i)
                    buffer.Insert(caretPosition.GetPosition(buffer.CurrentSnapshot), charToInsert)

                    Dim insertedString = type.Substring(0, i + 1)
                    For Each span In document.SelectedSpans.Skip(1)
                        Dim trackingSpan = New LetterOnlyTrackingSpan(span.ToSnapshotSpan(initialTextSnapshot))
                        Assert.Equal(expectedStringGetter(insertedString), trackingSpan.GetText(document.GetTextBuffer().CurrentSnapshot))
                    Next
                Next

                If split IsNot Nothing Then
                    Dim beginSpan = document.SelectedSpans.First()
                    Dim trackingSpan = New LetterOnlyTrackingSpan(beginSpan.ToSnapshotSpan(initialTextSnapshot))

                    buffer.Insert(trackingSpan.GetEndPoint(buffer.CurrentSnapshot).Position - type.Trim().Length, " ")

                    Assert.Equal(split, trackingSpan.GetText(buffer.CurrentSnapshot))
                End If

                corrector.Disconnect()
            End Using
        End Sub

        Private Shared Sub Verify(codeWithMarker As String, keyword As String)
            ' do this since xml value put only vbLf
            codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)

            VerifyBegin(codeWithMarker, keyword)
            VerifyEnd(codeWithMarker, keyword)
        End Sub

        Private Shared Sub VerifyBegin(code As String, keyword As String, Optional expected As String = Nothing)
            Using workspace = TestWorkspace.CreateVisualBasic(code)
                Dim document = workspace.Documents.Single()

                Dim selectedSpans = document.SelectedSpans

                Dim spanToReplace = selectedSpans.First()
                Dim spanToVerify = selectedSpans.Skip(1).Single()

                Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
            End Using
        End Sub

        Private Shared Sub VerifyEnd(code As String, keyword As String, Optional expected As String = Nothing)
            Using workspace = TestWorkspace.CreateVisualBasic(code)
                Dim document = workspace.Documents.Single()

                Dim selectedSpans = document.SelectedSpans

                Dim spanToReplace = selectedSpans.Skip(1).Single()
                Dim spanToVerify = selectedSpans.First()

                Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
            End Using
        End Sub

        Private Shared Sub Verify(document As TestHostDocument, keyword As String, expected As String, spanToReplace As TextSpan, spanToVerify As TextSpan, workspace As TestWorkspace)
            Dim buffer = document.GetTextBuffer()
            Dim uiThreadOperationExecutor = workspace.GetService(Of IUIThreadOperationExecutor)
            Dim corrector = New AutomaticEndConstructCorrector(buffer, uiThreadOperationExecutor)

            corrector.Connect()
            buffer.Replace(spanToReplace.ToSpan(), keyword)
            corrector.Disconnect()

            expected = If(expected Is Nothing, keyword, expected)

            Dim correspondingSpan = document.InitialTextSnapshot.CreateTrackingSpan(spanToVerify.ToSpan(), SpanTrackingMode.EdgeInclusive)
            Assert.Equal(expected, correspondingSpan.GetText(buffer.CurrentSnapshot))
        End Sub
    End Class
End Namespace


text:
    <?php dynamic_sidebar('sidebar-footer'); ?>

      Copyright © <?php echo date('Y'); ?> <?php bloginfo('name'); ?> |
      Site Design by John Hotovy


text:
namespace Microsoft.Zelig.Runtime.TypeSystem
{
    using System;
    using System.Collections.Generic;

    public sealed class DelayedTypeParameterTypeRepresentation : TypeRepresentation
    {
        //
        // State
        //

        private TypeRepresentation m_context;
        private int                m_parameterNumber;

        //
        // Constructor Methods
        //

        public DelayedTypeParameterTypeRepresentation( AssemblyRepresentation owner           ,
                                                       TypeRepresentation     context         ,
                                                       int                    parameterNumber ) : base( owner, BuiltInTypes.VAR, Attributes.None )
        {
            m_context         = context;
            m_parameterNumber = parameterNumber;
        }

        //
        // MetaDataEquality Methods
        //

        public override bool EqualsThroughEquivalence( object         obj ,
                                                       EquivalenceSet set )
        {
            if(obj is DelayedTypeParameterTypeRepresentation)
            {
                DelayedTypeParameterTypeRepresentation other = (DelayedTypeParameterTypeRepresentation)obj;

                if(m_parameterNumber == other.m_parameterNumber)
                {
                    //
                    // Don't compare the context with Equals, it would lead to an infinite recursion!
                    //
                    if(Object.ReferenceEquals( m_context, other.m_context ))
                    {
                        return true;
                    }

                    if(set != null)
                    {
                        if(set.AreEquivalent( this, this.m_context, other, other.m_context ))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        public override bool Equals( object obj )
        {
            return this.EqualsThroughEquivalence( obj, null );
        }

        public override int GetHashCode()
        {
            return (int)m_parameterNumber ^
                        m_context.GetHashCode();
        }

        //--//

        //
        // Helper Methods
        //

        protected override void PerformInnerDelayedTypeAnalysis(     TypeSystem        typeSystem ,
                                                                 ref ConversionContext context    )
        {
            m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Object;

            foreach(TypeRepresentation td in m_context.GenericParametersDefinition[m_parameterNumber].Constraints)
            {
                if(td is InterfaceTypeRepresentation)
                {
                    continue;
                }

                m_extends = td;
                break;
            }
        }

        //--//

        public override void ApplyTransformation( TransformationContext context )
        {
            context.Push( this );

            //
            // Load before calling the base method, because we might get a call to GetHashCode().
            //
            context.Transform( ref m_context         );
            context.Transform( ref m_parameterNumber );

            base.ApplyTransformation( context );

            context.Pop();
        }

        //--//

        protected override void SetShapeCategory( TypeSystem typeSystem )
        {
            m_vTable.ShapeCategory = VTable.Shape.Invalid;
        }

        //--//

        protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic )
        {
            return ic.TypeParameters[m_parameterNumber];
        }

        //--//

        public override GCInfo.Kind ClassifyAsPointer()
        {
            return GCInfo.Kind.Invalid;
        }

        //--//

        public override InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem )
        {
            if(m_extends.IsObject)
            {
                return InstantiationFlavor.Delayed;
            }

            if(m_extends == typeSystem.WellKnownTypes.System_ValueType)
            {
                return InstantiationFlavor.ValueType;
            }

            return m_extends.GetInstantiationFlavor( typeSystem );
        }

        //--//

        //
        // Access Methods
        //

        public override bool IsOpenType
        {
            get
            {
                return true;
            }
        }

        public override bool IsDelayedType
        {
            get
            {
                return true;
            }
        }

        public override uint SizeOfHoldingVariable
        {
            get
            {
                return 0;
            }
        }

        public override bool CanPointToMemory
        {
            get
            {
                return false; // We don't know at this stage.
            }
        }

        public TypeRepresentation Context
        {
            get
            {
                return m_context;
            }
        }

        public int ParameterNumber
        {
            get
            {
                return m_parameterNumber;
            }
        }

        //--//

        //
        // Debug Methods
        //

        public override String ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder( "DelayedTypeParameterTypeRepresentation(" );

            PrettyToString( sb, true, false );

            sb.Append( "," );
            sb.Append( m_context );

            sb.Append( ")" );

            return sb.ToString();
        }

        internal override void PrettyToString( System.Text.StringBuilder sb                 ,
                                               bool                      fPrefix            ,
                                               bool                      fWithAbbreviations )
        {
            GenericContext gc = m_context.Generic;

            if(gc != null)
            {
                TypeRepresentation[] parameters = gc.Parameters;
                if(m_parameterNumber < parameters.Length)
                {
                    parameters[m_parameterNumber].PrettyToString( sb, fPrefix, fWithAbbreviations );
                    return;
                }

                GenericParameterDefinition[] defs = gc.ParametersDefinition;
                if(defs != null && m_parameterNumber < defs.Length)
                {
                    sb.Append( defs[m_parameterNumber].Name );
                    return;
                }
            }

            sb.Append( "{VAR,"           );
            sb.Append( m_parameterNumber );
            sb.Append( "}"               );
        }
    }
}


text:
 /**
 * Created by Master on 2017-06-27.
 */
import { Injectable } from '@angular/core';
import { Jsonp, Http, Headers, RequestOptions, Response } from '@angular/http';

import { AppConfig } from '../app.config';
import { User } from '../_models/index';
import {errorHandler} from "@angular/platform-browser/src/browser";

@Injectable()
export class LoginService {

    constructor(private jsonp:Jsonp, private http: Http, private config: AppConfig) {}

    login(username: string, password: string) {
        // let headers = new Headers();
        let headers = new Headers({ 'Access-Control-Request-Headers': "Content-Type", 'Content-Type': 'application/json'});
        headers.append('Access-Control-Request-Methods', 'POST');
        let options = new RequestOptions({ headers: headers });
        var data = {
            username : username,
            password : password
        };
        return this.http.post(this.config.apiUrl+'/api/auth/login', data)
            .map (res => res.json());

    }
    googleLogin() {

        const headers: Headers = new Headers();
        // headers.append('Accept', 'application/json');
        // headers.append('Content-Type', 'application/json');
        // headers.append('Access-Control-Request-Method', 'Content-Type');

        const options = new RequestOptions({
            headers: headers
        });
        return this.http.get(this.config.apiUrl+'/api/auth/login/google')
            .map (res => {
                console.log("googleLogin res",res);
                return res;
            });

    }
    facebookLogin() {
        return this.http.get (this.config.apiUrl+'/api/auth/login/facebook')
            .map (res => {
                // console.log("res",res);
                return res;
            });

    }
    logout() {
        return this.http.get(this.config.apiUrl+'/api/auth/logout')
            .map (res => res.json());

    }
    handleError() {

    }
}


text:
![License badge](https://img.shields.io/github/license/widdowquinn/Notebooks-Bioinformatics.svg)

## Introduction

This repository contains Jupyter/iPython notebooks related to bioinformatics. Some of the notebooks are standalone examples/illustrations of concepts or code. Others are exercises or worksheets used in teaching, or for training courses.

All notebooks are stored with blank output cells.

Supporting information/data should always be available in subdirectories of this repository.

## Running Notebooks

You can run these notebooks on your own machine using [Project Jupyter](http://jupyter.org/), or at MyBinder, by visiting [http://mybinder.org/repo/widdowquinn/Notebooks-Bioinformatics](http://mybinder.org/repo/widdowquinn/Notebooks-Bioinformatics) or clicking on the button below:

[![Binder](http://mybinder.org/badge.svg)](http://mybinder.org/repo/widdowquinn/Notebooks-Bioinformatics)


text:
	$ npm install medikoo/i18n2

### Usage

Once initialized, translation engine should be used across your application as a translator of your messages

```javascript

var I18n = require('i18n2');

// locale (map of translations) is optional and can be provided at later step
var i18n = new I18n(locale);

// By convention name for gettext translator function is `_`
var _ = i18n;
...
_("Hello World"); // Witaj Świecie!
```

#### Contexts

Different contexts can be assigned:

```javascript
var _ = i18n.bind('admin');

// Resolved in context of 'admin'
_("Hello World!"); // Admin: Witaj Świecie

```

#### Configuration of messages

##### Singular message: `_(msg[, inserts])`

Singular message can be plain:

```javascript
_("Hello World!"); // Witaj Świecie!
```

or filled with substitutions to replace:

```javascript
_("My name is ${firstName} ${lastName}", {
  firstName: "John",
  lastName: "Smith"
}); // Nazywam się John Smith
```

Substitutions syntax follows [ECMAScript's 6 template strings](http://www.2ality.com/2011/09/quasi-literals.html) format

##### Singular + plural message: _(singularMsg, pluralMsg, count[, inserts])

Singular and plural key, plus resolved count needs to be provided:

```javascript
_("${n} cat", "${n} cats", 1); // 1 kot
_("${n} cat", "${n} cats", 3); // 3 koty
_("${n} cat", "${n} cats", 5); // 5 kotów
```
Same way as in case of singular messages, inserts can be provided as fourth argument

#### Configuration of locale map

Configuration with no contexts (`default` context is assumed):

```javascript
var locale = {
  "Hello World": "Witaj Świecie!"
};
```

With contexts

```javascript
var locale = {
  "Hello World": {
    default: "Witaj Świecie!",
    admin: "Admin: Witaj Świecie!"
  }
};
```

##### Singular + plural messages

Key of such message is generated with following concatenation rule `key = 'n\0' + singularMsg + '\0' + pluralMsg`;

There are two ways of providing translations

###### with Array of options

```javascript
var locale = {
  "\0${n} cat\0${n} cats": [
    "${n} kot",  // 1
    "${n} koty",,, // 2,3,4
    "${n} kotów" // 5+
  ]
};
```

###### with Function

In some languages (like Polish) resolving plurals is more tricky, the definite way can only be achieved with custom function:

```javascript
var locale = {
  "\0${n} cat\0${n} cats": function (n) {
    if (n === 1) return "${n} kot";
    n = n % 100;
    if ((n > 4) && (n < 22)) return "${n} kotów";
    switch (n % 10) {
      case 2:
      case 3:
      case 4:
      return "${n} koty";
    }
    return "${n} kotów";
  }
};
```

### Tests [![Build Status](https://travis-ci.org/medikoo/i18n2.svg)](https://travis-ci.org/medikoo/i18n2)

	$ npm test


text:
// Copyright (c) 2013, Eric Maupin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with
// or without modification, are permitted provided that
// the following conditions are met:
//
// - Redistributions of source code must retain the above
//   copyright notice, this list of conditions and the
//   following disclaimer.
//
// - Redistributions in binary form must reproduce the above
//   copyright notice, this list of conditions and the
//   following disclaimer in the documentation and/or other
//   materials provided with the distribution.
//
// - Neither the name of Gablarski nor the names of its
//   contributors may be used to endorse or promote products
//   or services derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
// AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using Gablarski.Audio;

namespace Gablarski.Clients.ViewModels
{
	public class AudioCaptureSettingsViewModel
		: ViewModelBase
	{
		public AudioCaptureSettingsViewModel()
		{
			CaptureProviders = Modules.Capture;

			IAudioCaptureProvider savedCaptureProvider = Modules.Capture.FirstOrDefault (p => p.GetType().GetSimpleName() == Settings.VoiceProvider);
			if (savedCaptureProvider == null)
				CurrentCaptureProvider = Modules.Capture.FirstOrDefault();
			else {
				CurrentCaptureProvider = savedCaptureProvider;

				if (Settings.VoiceDevice != null)
				{
					var setDevice = CaptureDevices.FirstOrDefault (d => d.Device.Name == Settings.VoiceDevice);
					if (setDevice != null)
						CurrentCaptureDevice = setDevice;
				}
			}

			VoiceActivationThreshold = Settings.VoiceActivationLevel;
			VoiceActivationSilenceThreshold = Settings.VoiceActivationContinueThreshold / 100;
			UseVoiceActivation = !Settings.UsePushToTalk;
		}

		private const int FrameSize = 480;
		private void UpdateActivation()
		{
			IsActivating = false;
			ActivationLevel = 0;
			this.activation = new VoiceActivation (AudioFormat.Mono16bitLPCM, FrameSize, VoiceActivationThreshold, VoiceActivationThreshold / 2, VoiceActivationSilenceTime);
		}

		private void OnSamplesAvailable (object sender, SamplesAvailableEventArgs e)
		{
			if (this.activation == null)
				return;
			if (e.Available < FrameSize)
				return;

			byte[] samples = e.Provider.ReadSamples (FrameSize);
			ActivationLevel = this.activation.GetLevel (samples);
			IsActivating = this.activation.IsTalking (samples);
		}

		public int ActivationLevel
		{
			get { return this.activationLevel; }
			set
			{
				if (this.activationLevel == value)
					return;

				this.activationLevel = value;
				OnPropertyChanged();
			}
		}

		public bool IsActivating
		{
			get { return this.isActivating; }
			set
			{
				if (this.isActivating == value)
					return;

				this.isActivating = value;
				OnPropertyChanged();
			}
		}

		public IEnumerable<IAudioCaptureProvider> CaptureProviders
		{
			get;
			private set;
		}

		private IAudioCaptureProvider currentCaptureProvider;
		public IAudioCaptureProvider CurrentCaptureProvider
		{
			get { return this.currentCaptureProvider; }
			set
			{
				if (this.currentCaptureProvider == value)
					return;

				if (this.currentCaptureProvider != null)
					this.currentCaptureProvider.SamplesAvailable -= OnSamplesAvailable;

				this.currentCaptureProvider = value;
				OnPropertyChanged();

				if (value != null) {
					value.SamplesAvailable += OnSamplesAvailable;

					CaptureDevices = new[] { new DefaultDevice() }
						.Concat (value.GetDevices())
						.Select (d => new DeviceViewModel (value, d))
						.ToArray();

					CurrentCaptureDevice = CaptureDevices.First();
				} else {
					CaptureDevices = Enumerable.Empty<DeviceViewModel>();
					CurrentCaptureDevice = null;
				}
			}
		}

		private IEnumerable<DeviceViewModel> captureDevices;
		public IEnumerable<DeviceViewModel> CaptureDevices
		{
			get { return this.captureDevices; }
			set
			{
				if (this.captureDevices == value)
					return;

				this.captureDevices = value;
				OnPropertyChanged();
			}
		}

		private DeviceViewModel currentCaptureDevice;
		public DeviceViewModel CurrentCaptureDevice
		{
			get { return this.currentCaptureDevice; }
			set
			{
				if (value == null && CurrentCaptureProvider != null)
					value = CaptureDevices.FirstOrDefault();
				if (this.currentCaptureDevice == value)
					return;

				if (UseVoiceActivation && CurrentCaptureProvider != null) {
					if (CurrentCaptureProvider.IsCapturing)
						CurrentCaptureProvider.EndCapture();

					UpdateActivation();

					if (value != null)
					{
						var actualDevice = value.Device;
						if (actualDevice is DefaultDevice)
							actualDevice = CaptureDevices.First (d => d.Device.Equals (CurrentCaptureProvider.DefaultDevice)).Device;

						CurrentCaptureProvider.Device = actualDevice;
						CurrentCaptureProvider.BeginCapture (AudioFormat.Mono16bitLPCM, FrameSize);
					}
				}

				this.currentCaptureDevice = value;
				OnPropertyChanged();
			}
		}

		private bool useVoiceActivation;
		public bool UseVoiceActivation
		{
			get { return this.useVoiceActivation; }
			set
			{
				if (this.useVoiceActivation == value)
					return;

				if (CurrentCaptureProvider != null) {
					if (!value && CurrentCaptureProvider.IsCapturing) {
						CurrentCaptureProvider.EndCapture();
						UpdateActivation();
					} else if (value && !CurrentCaptureProvider.IsCapturing) {
						UpdateActivation();
						if (CurrentCaptureProvider.Device == null) {
							CurrentCaptureProvider.Device = (CurrentCaptureDevice.Device is DefaultDevice)
								? CurrentCaptureProvider.DefaultDevice
								: CurrentCaptureDevice.Device;
						}

						CurrentCaptureProvider.BeginCapture (AudioFormat.Mono16bitLPCM, FrameSize);
					}
				}

				this.useVoiceActivation = value;
				OnPropertyChanged();
			}
		}

		private int voiceActivationThreshold;
		public int VoiceActivationThreshold
		{
			get { return this.voiceActivationThreshold; }
			set
			{
				if (this.voiceActivationThreshold == value)
					return;

				this.voiceActivationThreshold = value;
				OnPropertyChanged();

				UpdateActivation();
			}
		}

		public TimeSpan VoiceActivationSilenceTime
		{
			get { return TimeSpan.FromMilliseconds (VoiceActivationSilenceThreshold * 100); }
		}

		private int voiceActivationSilenceThreshold;
		public int VoiceActivationSilenceThreshold
		{
			get { return this.voiceActivationSilenceThreshold; }
			set
			{
				if (this.voiceActivationSilenceThreshold == value)
					return;

				this.voiceActivationSilenceThreshold = value;
				OnPropertyChanged();
				OnPropertyChanged ("VoiceActivationSilenceTime");

				UpdateActivation();
			}
		}

		public void UpdateSettings()
		{
			Settings.VoiceProvider = (CurrentCaptureProvider != null)
				? CurrentCaptureProvider.GetType().GetSimpleName()
				: null;

			Settings.VoiceDevice = (CurrentCaptureDevice != null)
				? CurrentCaptureDevice.Device.Name
				: null;

			Settings.VoiceActivationLevel = VoiceActivationThreshold;
			Settings.VoiceActivationContinueThreshold = VoiceActivationSilenceThreshold * 100;
			Settings.UsePushToTalk = !UseVoiceActivation;
		}

		public void Close()
		{
			if (CurrentCaptureProvider == null)
				return;

			CurrentCaptureProvider.SamplesAvailable -= OnSamplesAvailable;
			if (CurrentCaptureProvider.IsCapturing)
				CurrentCaptureProvider.EndCapture();
		}

		private VoiceActivation activation;
		private bool isActivating;
		private int activationLevel;
	}
}


text:
<!DOCTYPE html>
<!--
 * Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this
 * source code is governed by a BSD-style license that can be found in the
 * LICENSE file.
-->
<html>
  <head>
    <title>OAuth Redirect Page</title>
    <style type="text/css">
      body {
        font: 16px Arial;
        color: #333;
      }
    </style>
    <script type="text/javascript" src="scripts/chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="scripts/chrome_ex_oauth.js"></script>
    <script type="text/javascript" src="scripts/onload.js"></script>
  </head>
  <body>
    Redirecting...
  </body>
</html>


text:
/*--------------------------------------------------------------------*/
/*--- Replacements for strlen() and strnlen(), which run on the    ---*/
/*--- simulated CPU.                                               ---*/
/*--------------------------------------------------------------------*/

/*
  This file is part of DRD, a heavyweight Valgrind tool for
  detecting threading errors. The code below has been extracted
  from memchec/mc_replace_strmem.c, which has the following copyright
  notice:

  Copyright (C) 2000-2012 Julian Seward
  jseward@acm.org

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License as
  published by the Free Software Foundation; either version 2 of the
  License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  02111-1307, USA.

  The GNU General Public License is contained in the file COPYING.
*/

#include "pub_tool_basics.h"
#include "pub_tool_hashtable.h"
#include "pub_tool_redir.h"
#include "pub_tool_tooliface.h"
#include "valgrind.h"

#define STRNLEN(soname, fnname)                                         \
   SizeT VG_REPLACE_FUNCTION_ZU(soname,fnname) ( const char* str, SizeT n ); \
   SizeT VG_REPLACE_FUNCTION_ZU(soname,fnname) ( const char* str, SizeT n ) \
   {                                                                    \
      SizeT i = 0;                                                      \
      while (i < n && str[i] != 0) i++;                                 \
      return i;                                                         \
   }

#if defined(VGO_linux)
 STRNLEN(VG_Z_LIBC_SONAME, strnlen)
#elif defined(VGO_darwin)
 STRNLEN(VG_Z_LIBC_SONAME, strnlen)
#endif

// Note that this replacement often doesn't get used because gcc inlines
// calls to strlen() with its own built-in version.  This can be very
// confusing if you aren't expecting it.  Other small functions in this file
// may also be inline by gcc.
#define STRLEN(soname, fnname)                                          \
   SizeT VG_REPLACE_FUNCTION_ZU(soname,fnname)( const char* str );      \
   SizeT VG_REPLACE_FUNCTION_ZU(soname,fnname)( const char* str )       \
   {                                                                    \
      SizeT i = 0;                                                      \
      while (str[i] != 0) i++;                                          \
      return i;                                                         \
   }

#if defined(VGO_linux)
 STRLEN(VG_Z_LIBC_SONAME,          strlen)
 STRLEN(VG_Z_LD_LINUX_SO_2,        strlen)
 STRLEN(VG_Z_LD_LINUX_X86_64_SO_2, strlen)
#elif defined(VGO_darwin)
 STRLEN(VG_Z_LIBC_SONAME,          strlen)
#endif

/*--------------------------------------------------------------------*/
/*--- end                                                          ---*/
/*--------------------------------------------------------------------*/


text:
namespace base {
class FilePath;
}  // namespace base

namespace component_updater {

class ComponentUpdateService;

class FileTypePoliciesComponentInstallerTraits
    : public ComponentInstallerTraits {
 public:
  FileTypePoliciesComponentInstallerTraits() {}
  ~FileTypePoliciesComponentInstallerTraits() override {}

 private:
  // The following methods override ComponentInstallerTraits.
  bool SupportsGroupPolicyEnabledComponentUpdates() const override;
  bool RequiresNetworkEncryption() const override;
  update_client::CrxInstaller::Result OnCustomInstall(
      const base::DictionaryValue& manifest,
      const base::FilePath& install_dir) override;
  bool VerifyInstallation(const base::DictionaryValue& manifest,
                          const base::FilePath& install_dir) const override;
  void ComponentReady(const base::Version& version,
                      const base::FilePath& install_dir,
                      std::unique_ptr<base::DictionaryValue> manifest) override;
  base::FilePath GetRelativeInstallDir() const override;
  void GetHash(std::vector<uint8_t>* hash) const override;
  std::string GetName() const override;
  update_client::InstallerAttributes GetInstallerAttributes() const override;
  std::vector<std::string> GetMimeTypes() const override;

  static base::FilePath GetInstalledPath(const base::FilePath& base);

  DISALLOW_COPY_AND_ASSIGN(FileTypePoliciesComponentInstallerTraits);
};

// Call once during startup to make the component update service aware of
// the File Type Policies component.
void RegisterFileTypePoliciesComponent(ComponentUpdateService* cus,
                                       const base::FilePath& user_data_dir);

}  // namespace component_updater

#endif  // CHROME_BROWSER_COMPONENT_UPDATER_FILE_TYPE_POLICIES_COMPONENT_INSTALLER_H_


text:
@interface WDUnlockView : UIControl <UIGestureRecognizerDelegate>

+ (WDUnlockView *) unlockView;

@end


text:
<!doctype html>

    <meta charset="utf-8">
    <title>carousel-3d Test Suite</title>

    <link rel="stylesheet" href="../bower_components/qunit/qunit/qunit.css" media="screen">

      lame test markup
      normal test markup
      awesome test markup


text:
package net.jp2p.jxse.core.peergroup;

import java.net.URI;

import net.jp2p.chaupal.peergroup.IJp2pModuleClassID;
import net.jp2p.jxse.core.id.IJp2pModuleID;
import net.jxta.peergroup.core.ModuleClassID;

public class Jp2pModuleClassID implements IJp2pModuleClassID, IJp2pModuleID<ModuleClassID>{
	private static final long serialVersionUID = -447557117932175222L;

	private ModuleClassID mcid;

	Jp2pModuleClassID(ModuleClassID mcid) {
		super();
		this.mcid = mcid;
	}

	@Override
	public boolean isOfSameBaseClass(Jp2pModuleClassID id) {
		return this.mcid.isOfSameBaseClass(id.getID());
	}

	@Override
	public Jp2pModuleClassID getBaseClass() {
		return new Jp2pModuleClassID( this.mcid.getBaseClass());
	}

	@Override
	public boolean isOfSameBaseClass(ModuleClassID id) {
		return mcid.isOfSameBaseClass(id);
	}

	@Override
	public ModuleClassID getID() {
		return mcid;
	}

	@Override
	public String getIDFormat() {
		return mcid.getIDFormat();
	}

	@Override
	public Object getUniqueValue() {
		return mcid.getUniqueValue();
	}

	@Override
	public URI toURI() {
		return mcid.toURI();
	}
}


text:
<?php
    if(isset($_GET['email'])) {
        $email = $_GET['email'];
        $uname = $_GET['username'];
    }
    else {
        $email = '';
        $uname = '';
    }
?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <base href="https://nxtdrop.com/">
        <title></title>
        <meta name="description" content="Welcome to NXTDROP">
        <meta name="author" content="NXTDROP, Inc.">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="https://fonts.googleapis.com/css?family=Gloria+Hallelujah|Roboto" rel="stylesheet">

Daniel Arsham's collab with adidas droppping this week!

&#x1F525 OR &#x2744?

The artist Daniel Arsham collaborated with adidas to release his own version of the Futurecraft 4D. Like the Futurecraft "Aero Green", the 4D has the same green color. The shoes also have hidden details that appears when exposed to UV Light. The collab is set to release October 12th at a retail price of $450. &#x1F605

Colorway: Aero Green

OFF-WHITE x Converse Chuck 70 released October 8th. Hope you had a chance to get your hands on them. If you didn't, they'll soon be up for sale on NXTDROP.

Colorway: White/Bold Orange-Black

Hypefest by HYPEBEAST occured last week-end and a lot of designers, brands and celebrities were present at the event. Nike displayed a new pair of Air Force 1 High in collaboration with ALYX Studio in all-black and all-white colorway. The cool thing about it is ALYX Studio's signature buckle at the ankle strap. Unfortunately, there is no release date yet, but stay tuned.

Colorway: White

&#x1F525 Popular this week:

adidas YEEZY Boost 350 Cream White

adidas Ultra Boost 2.0 White Reflective

Nike Air Presto Mid Acronym Dynamic Yellow

Air Jordan 4 Retro Raptors

The NXTDROP Team.

TAKE CARE!

                        INSTAGRAM
                        TWITTER
                        PRIVACY
                        TERMS

© NXTDROP, Inc. All rights reserved.

If you prefer not to receive emails like this from NXTDROP, you may <a href="<?php echo 'https://nxtdrop.com/unsubscribe/'.$email; ?>" style="text-decoration: underline; color: #424242;">unsubscribe


text:
package com.sqisland.android.test_demo.mvvmschedulers;

import android.support.annotation.NonNull;
import rx.Scheduler;
import rx.schedulers.Schedulers;

/**
 * Implementation of the {@link ISchedulerProvider} making all {@link Scheduler}s immediate.
 */
public class ImmediateSchedulerProvider implements ISchedulerProvider {

    @NonNull
    @Override
    public Scheduler computation() {
        return Schedulers.immediate();
    }

    @NonNull
    @Override
    public Scheduler ui() {
        return Schedulers.immediate();
    }
}


text:
<?php

namespace Tkotosz\CatalogRouter\Model;

class UrlPath
{
    /**
     * @var string[]
     */
    private $urlKeys;

    /**
     * @var string
     */
    private $identifier;

    /**
     * @param string $path
     */
    public function __construct(string $path)
    {
        $this->identifier = trim($path, '/');
        $this->urlKeys = explode('/', $this->identifier);
    }

    /**
     * @return string
     */
    public function getIdentifier() : string
    {
        return $this->identifier;
    }

    /**
     * @return string
     */
    public function getFullPath() : string
    {
        return $this->getIdentifier();
    }

    /**
     * @return string[]
     */
    public function getAllPart() : array
    {
        return $this->urlKeys;
    }

    /**
     * @return array
     */
    public function getBeginningParts() : array
    {
        return array_slice($this->urlKeys, 0, -1);
    }

    /**
     * @return string
     */
    public function getLastPart() : string
    {
        return end($this->urlKeys);
    }
}


text:
import { element, by, protractor, browser, ElementFinder } from 'protractor';

import { AngularMentionsPage } from './app.po';
import { DemoEventsPage } from './demo-events.po';

describe('angular-mentions events', function() {
  let appPage: AngularMentionsPage;
  let demoPage: DemoEventsPage;
  let input: ElementFinder;

  beforeEach(() => {
    appPage = new AngularMentionsPage();
    demoPage = new DemoEventsPage();
    demoPage.navigateTo();
    expect(appPage.getHeadingText()).toEqual('Angular Mentions');
    expect(appPage.getSubHeadingText()).toEqual('Events');
    input = element.all(by.css('input')).first();
  })

  it('test basic events', () => {
    input.sendKeys('Hello @he', protractor.Key.ENTER);
    validateEvents([
      'Ready...',
      'opened',
      'searchTerm "h"',
      'searchTerm "he"',
      'itemSelected {"label":"Henry"}',
      'closed'
    ]);
  });

  it('test returnTrigger option', () => {
    const checkbox = element.all(by.css("input[type='checkbox']"));
    checkbox.click();
    expect(checkbox.isSelected()).toBeTruthy();
    input.sendKeys('Hello @bl', protractor.Key.ENTER);
    validateEvents([
      'Ready...',
      'opened',
      'searchTerm "@"',
      'searchTerm "@b"',
      'searchTerm "@bl"',
      'itemSelected {"label":"Blake"}',
      'closed'
    ]);
  });

  it('test closed event on blur', () => {
    const heading = element.all(by.css('h3'));
    // no event before opened
    input.click();
    heading.click();
    validateEvents([
      'Ready...'
    ]);
    // check blur after list opened
    input.sendKeys('Hello @he');
    heading.click();
    validateEvents([
      'Ready...',
      'opened',
      'searchTerm "h"',
      'searchTerm "he"',
      'closed'
    ]);
  });

  it('test closed event when no mentions', () => {
    input.sendKeys('Hello @hex');
    validateEvents([
      'Ready...',
      'opened',
      'searchTerm "h"',
      'searchTerm "he"',
      'searchTerm "hex"',
      // 'closed' // should 'closed' be emitted when no items?
    ]);
  });

  it('test searchTerm ignore special keys', () => {
    input.sendKeys('Hello @hx', protractor.Key.F10, protractor.Key.BACK_SPACE);
    validateEvents([
      'Ready...',
      'opened',
      'searchTerm "h"',
      'searchTerm "hx"', // f10 is ignored
      'searchTerm "h"' // after back_space
    ]);
  });

  function validateEvents(expectedLines:string[]) {
    let textPromise = demoPage.getOutputText();
    return textPromise.then( (text:string) => {
      let gotLines = text.split('\n').reverse().map(s=>s.substring(25)); // remove the timestamps
      expect(expectedLines).toEqual(gotLines);
    });
  }

});


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Exodus.Npgsql.Commands
{
    class DropDatabase : PostgresCommand
    {
        public DropDatabase(string serverConnectionString, string databaseName)
            : base(serverConnectionString, false)
        {
            Sql = $@"DROP DATABASE ""{databaseName}""";
        }
    }
}


text:
package e2e

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"sync"
	"text/tabwriter"
	"time"

	cadvisor "github.com/google/cadvisor/info/v1"
	"k8s.io/kubernetes/pkg/api"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/kubelet"
	"k8s.io/kubernetes/pkg/kubelet/metrics"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/master/ports"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/prometheus/client_golang/extraction"
	"github.com/prometheus/client_golang/model"
)

// KubeletMetric stores metrics scraped from the kubelet server's /metric endpoint.
// TODO: Get some more structure around the metrics and this type
type KubeletMetric struct {
	// eg: list, info, create
	Operation string
	// eg: sync_pods, pod_worker
	Method string
	// 0 <= quantile <=1, e.g. 0.95 is 95%tile, 0.5 is median.
	Quantile float64
	Latency  time.Duration
}

// KubeletMetricByLatency implements sort.Interface for []KubeletMetric based on
// the latency field.
type KubeletMetricByLatency []KubeletMetric

func (a KubeletMetricByLatency) Len() int           { return len(a) }
func (a KubeletMetricByLatency) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a KubeletMetricByLatency) Less(i, j int) bool { return a[i].Latency > a[j].Latency }

// KubeletMetricIngester implements extraction.Ingester
type kubeletMetricIngester []KubeletMetric

func (k *kubeletMetricIngester) Ingest(samples model.Samples) error {
	acceptedMethods := sets.NewString(
		metrics.PodWorkerLatencyKey,
		metrics.PodWorkerStartLatencyKey,
		metrics.SyncPodsLatencyKey,
		metrics.PodStartLatencyKey,
		metrics.PodStatusLatencyKey,
		metrics.ContainerManagerOperationsKey,
		metrics.DockerOperationsKey,
		metrics.DockerErrorsKey,
	)

	for _, sample := range samples {
		const prefix = metrics.KubeletSubsystem + "_"
		metricName := string(sample.Metric[model.MetricNameLabel])
		if !strings.HasPrefix(metricName, prefix) {
			// Not a kubelet metric.
			continue
		}

		method := strings.TrimPrefix(metricName, prefix)
		if !acceptedMethods.Has(method) {
			continue
		}

		if method == metrics.DockerErrorsKey {
			Logf("ERROR %v", sample)
		}

		latency := sample.Value
		operation := string(sample.Metric["operation_type"])
		var quantile float64
		if val, ok := sample.Metric[model.QuantileLabel]; ok {
			var err error
			if quantile, err = strconv.ParseFloat(string(val), 64); err != nil {
				continue
			}
		}

		*k = append(*k, KubeletMetric{operation, method, quantile, time.Duration(int64(latency)) * time.Microsecond})
	}
	return nil
}

// ReadKubeletMetrics reads metrics from the kubelet server running on the given node
func ParseKubeletMetrics(metricsBlob string) ([]KubeletMetric, error) {
	var ingester kubeletMetricIngester
	err := extraction.Processor004.ProcessSingle(strings.NewReader(metricsBlob), &ingester, &extraction.ProcessOptions{})
	return ingester, err
}

// HighLatencyKubeletOperations logs and counts the high latency metrics exported by the kubelet server via /metrics.
func HighLatencyKubeletOperations(c *client.Client, threshold time.Duration, nodeName string) ([]KubeletMetric, error) {
	var metricsBlob string
	var err error
	// If we haven't been given a client try scraping the nodename directly for a /metrics endpoint.
	if c == nil {
		metricsBlob, err = getKubeletMetricsThroughNode(nodeName)
	} else {
		metricsBlob, err = getKubeletMetricsThroughProxy(c, nodeName)
	}
	if err != nil {
		return []KubeletMetric{}, err
	}
	metric, err := ParseKubeletMetrics(metricsBlob)
	if err != nil {
		return []KubeletMetric{}, err
	}
	sort.Sort(KubeletMetricByLatency(metric))
	var badMetrics []KubeletMetric
	Logf("\nLatency metrics for node %v", nodeName)
	for _, m := range metric {
		if m.Latency > threshold {
			badMetrics = append(badMetrics, m)
			Logf("%+v", m)
		}
	}
	return badMetrics, nil
}

// getContainerInfo contacts kubelet for the container informaton. The "Stats"
// in the returned ContainerInfo is subject to the requirements in statsRequest.
func getContainerInfo(c *client.Client, nodeName string, req *kubelet.StatsRequest) (map[string]cadvisor.ContainerInfo, error) {
	reqBody, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	data, err := c.Post().
		Prefix("proxy").
		Resource("nodes").
		Name(fmt.Sprintf("%v:%v", nodeName, ports.KubeletPort)).
		Suffix("stats/container").
		SetHeader("Content-Type", "application/json").
		Body(reqBody).
		Do().Raw()

	var containers map[string]cadvisor.ContainerInfo
	err = json.Unmarshal(data, &containers)
	if err != nil {
		return nil, err
	}
	return containers, nil
}

const (
	// cadvisor records stats about every second.
	cadvisorStatsPollingIntervalInSeconds float64 = 1.0
	// cadvisor caches up to 2 minutes of stats (configured by kubelet).
	maxNumStatsToRequest int = 120
)

// A list of containers for which we want to collect resource usage.
func targetContainers() []string {
	if providerIs("gce", "gke") {
		return []string{
			"/",
			"/docker-daemon",
			"/kubelet",
			"/kube-proxy",
			"/system",
		}
	} else {
		return []string{
			"/",
		}
	}
}

type containerResourceUsage struct {
	Name                    string
	Timestamp               time.Time
	CPUUsageInCores         float64
	MemoryUsageInBytes      int64
	MemoryWorkingSetInBytes int64
	// The interval used to calculate CPUUsageInCores.
	CPUInterval time.Duration
}

func (r *containerResourceUsage) isStrictlyGreaterThan(rhs *containerResourceUsage) bool {
	return r.CPUUsageInCores > rhs.CPUUsageInCores && r.MemoryUsageInBytes > rhs.MemoryUsageInBytes && r.MemoryWorkingSetInBytes > rhs.MemoryWorkingSetInBytes
}

// getOneTimeResourceUsageOnNode queries the node's /stats/container endpoint
// and returns the resource usage of targetContainers for the past
// cpuInterval.
// The acceptable range of the interval is 2s~120s. Be warned that as the
// interval (and #containers) increases, the size of kubelet's response
// could be sigificant. E.g., the 60s interval stats for ~20 containers is
// ~1.5MB. Don't hammer the node with frequent, heavy requests.
//
// cadvisor records cumulative cpu usage in nanoseconds, so we need to have two
// stats points to compute the cpu usage over the interval. Assuming cadvisor
// polls every second, we'd need to get N stats points for N-second interval.
// Note that this is an approximation and may not be accurate, hence we also
// write the actual interval used for calcuation (based on the timestampes of
// the stats points in containerResourceUsage.CPUInterval.
func getOneTimeResourceUsageOnNode(c *client.Client, nodeName string, cpuInterval time.Duration) (map[string]*containerResourceUsage, error) {
	numStats := int(float64(cpuInterval.Seconds()) / cadvisorStatsPollingIntervalInSeconds)
	if numStats < 2 || numStats > maxNumStatsToRequest {
		return nil, fmt.Errorf("numStats needs to be > 1 and < %d", maxNumStatsToRequest)
	}
	// Get information of all containers on the node.
	containerInfos, err := getContainerInfo(c, nodeName, &kubelet.StatsRequest{
		ContainerName: "/",
		NumStats:      numStats,
		Subcontainers: true,
	})
	if err != nil {
		return nil, err
	}
	// Process container infos that are relevant to us.
	containers := targetContainers()
	usageMap := make(map[string]*containerResourceUsage, len(containers))
	for _, name := range containers {
		info, ok := containerInfos[name]
		if !ok {
			return nil, fmt.Errorf("missing info for container %q on node %q", name, nodeName)
		}
		first := info.Stats[0]
		last := info.Stats[len(info.Stats)-1]
		usageMap[name] = computeContainerResourceUsage(name, first, last)
	}
	return usageMap, nil
}

// logOneTimeResourceUsageSummary collects container resource for the list of
// nodes, formats and logs the stats.
func logOneTimeResourceUsageSummary(c *client.Client, nodeNames []string, cpuInterval time.Duration) {
	var summary []string
	for _, nodeName := range nodeNames {
		stats, err := getOneTimeResourceUsageOnNode(c, nodeName, cpuInterval)
		if err != nil {
			summary = append(summary, fmt.Sprintf("Error getting resource usage from node %q, err: %v", nodeName, err))
		} else {
			summary = append(summary, formatResourceUsageStats(nodeName, stats))
		}
	}
	Logf("\n%s", strings.Join(summary, "\n"))
}

func formatResourceUsageStats(nodeName string, containerStats map[string]*containerResourceUsage) string {
	// Example output:
	//
	// Resource usage for node "e2e-test-foo-minion-abcde":
	// container        cpu(cores)  memory(MB)
	// "/"              0.363       2942.09
	// "/docker-daemon" 0.088       521.80
	// "/kubelet"       0.086       424.37
	// "/kube-proxy"    0.011       4.66
	// "/system"        0.007       119.88
	buf := &bytes.Buffer{}
	w := tabwriter.NewWriter(buf, 1, 0, 1, ' ', 0)
	fmt.Fprintf(w, "container\tcpu(cores)\tmemory(MB)\n")
	for name, s := range containerStats {
		fmt.Fprintf(w, "%q\t%.3f\t%.2f\n", name, s.CPUUsageInCores, float64(s.MemoryUsageInBytes)/1000000)
	}
	w.Flush()
	return fmt.Sprintf("Resource usage on node %q:\n%s", nodeName, buf.String())
}

// Performs a get on a node proxy endpoint given the nodename and rest client.
func nodeProxyRequest(c *client.Client, node, endpoint string) client.Result {
	return c.Get().
		Prefix("proxy").
		Resource("nodes").
		Name(fmt.Sprintf("%v:%v", node, ports.KubeletPort)).
		Suffix(endpoint).
		Do()
}

// Retrieve metrics from the kubelet server of the given node.
func getKubeletMetricsThroughProxy(c *client.Client, node string) (string, error) {
	metric, err := nodeProxyRequest(c, node, "metrics").Raw()
	if err != nil {
		return "", err
	}
	return string(metric), nil
}

// Retrieve metrics from the kubelet on the given node using a simple GET over http.
// Currently only used in integration tests.
func getKubeletMetricsThroughNode(nodeName string) (string, error) {
	resp, err := http.Get(fmt.Sprintf("http://%v/metrics", nodeName))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}

// GetKubeletPods retrieves the list of running pods on the kubelet. The pods
// includes necessary information (e.g., UID, name, namespace for
// pods/containers), but do not contain the full spec.
func GetKubeletPods(c *client.Client, node string) (*api.PodList, error) {
	result := &api.PodList{}
	if err := nodeProxyRequest(c, node, "runningpods").Into(result); err != nil {
		return &api.PodList{}, err
	}
	return result, nil
}

func computeContainerResourceUsage(name string, oldStats, newStats *cadvisor.ContainerStats) *containerResourceUsage {
	return &containerResourceUsage{
		Name:                    name,
		Timestamp:               newStats.Timestamp,
		CPUUsageInCores:         float64(newStats.Cpu.Usage.Total-oldStats.Cpu.Usage.Total) / float64(newStats.Timestamp.Sub(oldStats.Timestamp).Nanoseconds()),
		MemoryUsageInBytes:      int64(newStats.Memory.Usage),
		MemoryWorkingSetInBytes: int64(newStats.Memory.WorkingSet),
		CPUInterval:             newStats.Timestamp.Sub(oldStats.Timestamp),
	}
}

// resourceCollector periodically polls the node, collect stats for a given
// list of containers, computes and cache resource usage up to
// maxEntriesPerContainer for each container.
type resourceCollector struct {
	lock            sync.RWMutex
	node            string
	containers      []string
	client          *client.Client
	buffers         map[string][]*containerResourceUsage
	pollingInterval time.Duration
	stopCh          chan struct{}
}

func newResourceCollector(c *client.Client, nodeName string, containerNames []string, pollingInterval time.Duration) *resourceCollector {
	buffers := make(map[string][]*containerResourceUsage)
	return &resourceCollector{
		node:            nodeName,
		containers:      containerNames,
		client:          c,
		buffers:         buffers,
		pollingInterval: pollingInterval,
	}
}

// Start starts a goroutine to poll the node every pollingInerval.
func (r *resourceCollector) Start() {
	r.stopCh = make(chan struct{}, 1)
	// Keep the last observed stats for comparison.
	oldStats := make(map[string]*cadvisor.ContainerStats)
	go util.Until(func() { r.collectStats(oldStats) }, r.pollingInterval, r.stopCh)
}

// Stop sends a signal to terminate the stats collecting goroutine.
func (r *resourceCollector) Stop() {
	close(r.stopCh)
}

// collectStats gets the latest stats from kubelet's /stats/container, computes
// the resource usage, and pushes it to the buffer.
func (r *resourceCollector) collectStats(oldStats map[string]*cadvisor.ContainerStats) {
	infos, err := getContainerInfo(r.client, r.node, &kubelet.StatsRequest{
		ContainerName: "/",
		NumStats:      1,
		Subcontainers: true,
	})
	if err != nil {
		Logf("Error getting container info on %q, err: %v", r.node, err)
		return
	}
	r.lock.Lock()
	defer r.lock.Unlock()
	for _, name := range r.containers {
		info, ok := infos[name]
		if !ok || len(info.Stats) < 1 {
			Logf("Missing info/stats for container %q on node %q", name, r.node)
			return
		}
		if _, ok := oldStats[name]; ok {
			r.buffers[name] = append(r.buffers[name], computeContainerResourceUsage(name, oldStats[name], info.Stats[0]))
		}
		oldStats[name] = info.Stats[0]
	}
}

// LogLatest logs the latest resource usage of each container.
func (r *resourceCollector) LogLatest() {
	r.lock.RLock()
	defer r.lock.RUnlock()
	stats := make(map[string]*containerResourceUsage)
	for _, name := range r.containers {
		s := r.buffers[name][len(r.buffers)-1]
		if s == nil {
			Logf("Resource usage on node %q is not ready yet", r.node)
			return
		}
		stats[name] = s
	}
	Logf("\n%s", formatResourceUsageStats(r.node, stats))
}

// Reset frees the stats and start over.
func (r *resourceCollector) Reset() {
	r.lock.Lock()
	defer r.lock.Unlock()
	for _, name := range r.containers {
		r.buffers[name] = []*containerResourceUsage{}
	}
}

type resourceUsageByCPU []*containerResourceUsage

func (r resourceUsageByCPU) Len() int           { return len(r) }
func (r resourceUsageByCPU) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r resourceUsageByCPU) Less(i, j int) bool { return r[i].CPUUsageInCores < r[j].CPUUsageInCores }

// The percentiles to report.
var percentiles = [...]float64{0.05, 0.20, 0.50, 0.70, 0.90, 0.95, 0.99}

// GetBasicCPUStats returns the percentiles the cpu usage in cores for
// containerName. This method examines all data currently in the buffer.
func (r *resourceCollector) GetBasicCPUStats(containerName string) map[float64]float64 {
	r.lock.RLock()
	defer r.lock.RUnlock()
	result := make(map[float64]float64, len(percentiles))
	usages := r.buffers[containerName]
	sort.Sort(resourceUsageByCPU(usages))
	for _, q := range percentiles {
		index := int(float64(len(usages))*q) - 1
		if index < 0 {
			// We don't have enough data.
			result[q] = 0
			continue
		}
		result[q] = usages[index].CPUUsageInCores
	}
	return result
}

// resourceMonitor manages a resourceCollector per node.
type resourceMonitor struct {
	client          *client.Client
	containers      []string
	pollingInterval time.Duration
	collectors      map[string]*resourceCollector
}

func newResourceMonitor(c *client.Client, containerNames []string, pollingInterval time.Duration) *resourceMonitor {
	return &resourceMonitor{
		containers:      containerNames,
		client:          c,
		pollingInterval: pollingInterval,
	}
}

func (r *resourceMonitor) Start() {
	nodes, err := r.client.Nodes().List(labels.Everything(), fields.Everything())
	if err != nil {
		Failf("resourceMonitor: unable to get list of nodes: %v", err)
	}
	r.collectors = make(map[string]*resourceCollector, 0)
	for _, node := range nodes.Items {
		collector := newResourceCollector(r.client, node.Name, r.containers, pollInterval)
		r.collectors[node.Name] = collector
		collector.Start()
	}
}

func (r *resourceMonitor) Stop() {
	for _, collector := range r.collectors {
		collector.Stop()
	}
}

func (r *resourceMonitor) Reset() {
	for _, collector := range r.collectors {
		collector.Reset()
	}
}

func (r *resourceMonitor) LogLatest() {
	for _, collector := range r.collectors {
		collector.LogLatest()
	}
}

func (r *resourceMonitor) LogCPUSummary() {
	// Example output for a node (the percentiles may differ):
	// CPU usage of containers on node "e2e-test-yjhong-minion-0vj7":
	// container        5th%  50th% 90th% 95th%
	// "/"              0.051 0.159 0.387 0.455
	// "/docker-daemon" 0.000 0.000 0.146 0.166
	// "/kubelet"       0.036 0.053 0.091 0.154
	// "/kube-proxy"    0.017 0.000 0.000 0.000
	// "/system"        0.001 0.001 0.001 0.002
	var header []string
	header = append(header, "container")
	for _, p := range percentiles {
		header = append(header, fmt.Sprintf("%.0fth%%", p*100))
	}
	for nodeName, collector := range r.collectors {
		buf := &bytes.Buffer{}
		w := tabwriter.NewWriter(buf, 1, 0, 1, ' ', 0)
		fmt.Fprintf(w, "%s\n", strings.Join(header, "\t"))
		for _, containerName := range targetContainers() {
			data := collector.GetBasicCPUStats(containerName)
			var s []string
			s = append(s, fmt.Sprintf("%q", containerName))
			for _, p := range percentiles {
				s = append(s, fmt.Sprintf("%.3f", data[p]))
			}
			fmt.Fprintf(w, "%s\n", strings.Join(s, "\t"))
		}
		w.Flush()
		Logf("\nCPU usage of containers on node %q:\n%s", nodeName, buf.String())
	}
}


text:
angular.module('myApp').directive('ip', ['ipService', function(ipService) {
    return {
        restrict: 'E',
        templateUrl: 'components/ip/ip.html',

        scope: {
        },
        controller: function($scope) {
            ipService.ip().then(function(ip) {
                $scope.ip = ip;
            });
        }
    };
}]);


text:
var gulp 		= require('gulp')
	sass 		= require('gulp-sass')
	uglify 		= require('gulp-uglify')
	connect 	= require('gulp-connect-php')
	browserSync = require('browser-sync')
	notifier 	= require('node-notifier')
	runSequence = require('run-sequence')
	annotate 	= require('gulp-ng-annotate')
	cssnano     = require('gulp-cssnano')
	del 		= require('del')
	args		= require('yargs').argv;

require('gulp-stats')(gulp);

const APP_ICON = __dirname + '\\zblogo.png';

gulp.task('notify', function() {
	notifier.notify({
		title: 'ZenBoard Notification Test',
		message: 'Hi there! If you can see me, Your notifications are working just fine!',
		icon: APP_ICON,
		sound: (args.s || args.sound) ? true : false,
		id: 113
	});
})

/** Serve Tasks */
gulp.task('serve', ['build'], function() {
	var config = {
		php: {
			host: '127.0.0.1',
			port: 1000,
			base: 'dist/public',
		},
		bs: {
			proxy: 'localhost:1000',
			open: (!args.o) ? false : true
		}
	}

	connect.server(config.php);

	return browserSync.init(config.bs, function() {
		gulp.watch('src/php/**', ['build:zend:reload'])
		gulp.watch('src/sass/**', ['build:sass'])
		gulp.watch('src/angular/**', ['build:angular:reload'])
	});
})

/** Build Tasks */
gulp.task('build', function(callback) {
	if(!args.t) {
		runSequence(
			'build:composer',
			[
				'build:bower',
				'build:sass',
				'build:angular',
				'build:zend:reload'
			],
			'build:notify',
			callback
		);
	} else {
		runSequence(
			// 'purge:all',
			'build:vendor',
			[
				'build:bower',
				'build:sass',
				'build:angular',
				'build:zend:reload'
			],
			'build:notify',
			callback
		);
	}
})

gulp.task('build:notify', function() {
	if(args.v) {
		notifier.notify({
			title: 'ZB Task Notification',
			message: 'Build Complete',
			sound: (args.s) ? true : false,
			icon: __dirname + '/src/php/public/logo.png',
			remove: 112
		});
	}
})

gulp.task('build:vendor', function() {
	return gulp.src('vendor/**')
			   .pipe(gulp.dest('dist/vendor'));
})

gulp.task('build:composer', function() {
	return gulp.src('composer.json')
			   .pipe(gulp.dest('dist'))
})

gulp.task('build:bower', function() {
	return gulp.src('bower_components/**', { base: '.' })
			   .pipe(gulp.dest('dist/public'))
})

gulp.task('build:zend', function() {
	return gulp.src('src/php/**')
			   .pipe(gulp.dest('dist'))
})

gulp.task('build:zend:reload', ['build:zend'], function() {
	browserSync.reload();
})

gulp.task('build:sass', function() {
    return gulp.src('src/sass/**/*.sass')
	           .pipe(sass({ outputStyle: 'compressed'})
	               .on('error', sass.logError)
	           )
	           .pipe(cssnano())
	           .pipe(gulp.dest('dist/public/css'))
	           .pipe(browserSync.stream())
})

gulp.task('build:angular', function() {
	return gulp.src('src/angular/**/*.js')
			   .pipe(annotate())
			   .pipe(uglify()
			   		.on('error', function(uglify) {
				   			console.error(uglify.message);
				   			notifier.notify({
				   				title: 'ZB Task Notification',
				   				message: 'Uglify encountered an error:' + uglify.message + '',
				   				sound: false,
				   				icon: __dirname + '/src/php/public/logo.png'
				   			});
				   			this.emit('end');
			   			})
			   		)
		   	   .pipe(gulp.dest('dist/public/js'))
})

gulp.task('build:angular:reload', ['build:angular'], function() {
	browserSync.reload();
})

/** Purge Tasks */
gulp.task('purge:all', function(callback) {
	runSequence(
		'purge:cache',
		[
			'purge:php',
			'purge:js',
			'purge:css',
			'purge:fonts',
			'purge:dir'
		],
		callback
	);
})

gulp.task('purge:notify', function() {
	if(args.v) {
		notifier.notify({
			title: 'ZB Task Notification',
			message : 'Task: purge:all - Completed successfully',
			sound: false,
			timeout: 2,
			id: 112
		});
	}
})

gulp.task('purge:custom', function(array) {
	return runSequence(array);
})

gulp.task('purge:cache', function() {
	del(['dist/data/cache/**', '!dist/data/cache', '!dist/data/cache/.gitkeep']);
})

gulp.task('purge:php', function() {
	del(['dist/module/**', '!dist/module']);
})

gulp.task('purge:js', function() {
	del(['dist/public/js/**', '!dist/public/js']);
})

gulp.task('purge:css', function() {
	del(['dist/public/css/**', '!dist/public/css']);
})

gulp.task('purge:fonts', function() {
	del(['dist/public/fonts/**', '!dist/public/fonts']);
})

gulp.task('purge:dir', function() {
	del(['dist']);
})


text:
package org.wso2.carbon.uuf.test;

import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.uuf.api.Server;
import org.wso2.carbon.uuf.spi.HttpConnector;

@Component(name = "org.wso2.carbon.uuf.test.DummyHttpConnector",
           service = HttpConnector.class,
           immediate = true)
@SuppressWarnings("unused")
public class DummyHttpConnector implements HttpConnector {

    private static final Logger LOGGER = LoggerFactory.getLogger(DummyHttpConnector.class);

    @Override
    public void setServer(Server server) {
        LOGGER.info("Server '{}' registered to '{}'.", server, getClass().getName());
    }

    public void registerAppContextPath(String appContextPath) {
        LOGGER.info("App context path '{}' registered to '{}'.", appContextPath, getClass().getName());
    }
}


text:
pub mod black_sabbath;
pub mod musician;


text:
package com.xcc.advancedday13.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by DaXianSheng on 2016/9/21.
 */
public class JudgeSharePreference {
    public static boolean isFistLogin(Context context){
        SharedPreferences sp = context.getSharedPreferences("Login", Context.MODE_PRIVATE);
        return sp.getBoolean("isFist", true);
    }
    public static boolean isLogin(Context context){
        SharedPreferences sp = context.getSharedPreferences("Login", Context.MODE_PRIVATE);
        return sp.getBoolean("isLogin", false);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('inventory', '0003_add_host_uuid'),
    ]

    operations = [
        migrations.AlterField(
            model_name='host',
            name='vm_name',
            field=models.CharField(max_length=30, null=True),
        ),
    ]


text:
title: "ImageMagick"
category: "UNIX"
img: "unix.jpg"
excerpt: "ImageMagick® is a software suite to create, edit, compose, or convert bitmap images."
tags: [Linux, UNIX, Mac, Windows, ImageMagick]
---
ImageMagick® is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, JPEG-2000, GIF, TIFF, DPX, EXR, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.

## Installation

To install ImageMagick, I recommend [MacPorts](https://www.macports.org) which custom builds ImageMagick in your environment.

[PKG installer](https://www.macports.org/install.php) is the simplest way to install MacPorts on a OS X system.

Also, you can simply type this to install [Homebrew](https://brew.sh):

```sh

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

```

For me, I prefer MacPorts, just type:

```sh

sudo port install ImageMagick

```

This may take a while. The `port` command downloads ImageMagick and many of its delegate libraries and configures, builds, and installs ImageMagick automagically.

## Get Started

To get started, lets convert an image in the JPEG format to PNG:

```sh

convert rose.jpg rose.png

```

Next, we reduce the image size before it is written to the PNG format:

```sh

convert rose.jpg -resize 50% rose.png

```

You can combine multiple image-processing operations to produce complex results:

```sh

convert -size 320x85 canvas:none -font Bookman-DemiItalic -pointsize 72 \
  -draw "text 25,60 \'Magick\'" -channel RGBA -blur 0x6 -fill darkred -stroke magenta \
  -draw "text 20,55 \'Magick\'" fuzzy-magick.png

```

or here we resize an image with improved quality:

```sh

convert input.png -colorspace RGB +sigmoidal-contrast 11.6933 \
  -define filter:filter=Sinc -define filter:window=Jinc -define filter:lobes=3 \
  -resize 400% -sigmoidal-contrast 11.6933 -colorspace sRGB output.png');

```


text:
package com.bupt.poirot.pattern.abstractFactoryPattern;

/**
 * Created by hui.chen on 11/25/16.
 */

class BollywoodComedyMovie implements IBollywoodMovie {
    @Override
    public String movieName() {
        return "Munna Bhai MBBS is a Bollywood Comedy Movie";
    }
}