text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AudienceSegmentCriteria</title>
<meta name="date" content="2013-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.api.ads.dfp.v201211

Class AudienceSegmentCriteria

java.lang.Object

com.google.api.ads.dfp.v201211.CustomCriteriaNode

com.google.api.ads.dfp.v201211.CustomCriteriaLeaf

com.google.api.ads.dfp.v201211.AudienceSegmentCriteria

All Implemented Interfaces:

java.io.Serializable

public class AudienceSegmentCriteria
extends CustomCriteriaLeaf
implements java.io.Serializable

An AudienceSegmentCriteria object is used to target AudienceSegment objects.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

AudienceSegmentCriteria()

AudienceSegmentCriteria(java.lang.String customCriteriaNodeType,
                       AudienceSegmentCriteriaComparisonOperator operator,
                       long[] audienceSegmentIds)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

long[]
getAudienceSegmentIds()

Gets the audienceSegmentIds value for this AudienceSegmentCriteria.

long
getAudienceSegmentIds(int i)

static org.apache.axis.encoding.Deserializer
getDeserializer(java.lang.String mechType,
               java.lang.Class _javaType,
               javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

AudienceSegmentCriteriaComparisonOperator
getOperator()

Gets the operator value for this AudienceSegmentCriteria.

static org.apache.axis.encoding.Serializer
getSerializer(java.lang.String mechType,
             java.lang.Class _javaType,
             javax.xml.namespace.QName _xmlType)

Get Custom Serializer

static org.apache.axis.description.TypeDesc
getTypeDesc()

Return type metadata object

int
hashCode()

void
setAudienceSegmentIds(int i,
                     long _value)

void
setAudienceSegmentIds(long[] audienceSegmentIds)

Sets the audienceSegmentIds value for this AudienceSegmentCriteria.

void
setOperator(AudienceSegmentCriteriaComparisonOperator operator)

Sets the operator value for this AudienceSegmentCriteria.

Methods inherited from class com.google.api.ads.dfp.v201211.CustomCriteriaNode

getCustomCriteriaNodeType, setCustomCriteriaNodeType

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AudienceSegmentCriteria

public AudienceSegmentCriteria()

AudienceSegmentCriteria

public AudienceSegmentCriteria(java.lang.String customCriteriaNodeType,
                       AudienceSegmentCriteriaComparisonOperator operator,
                       long[] audienceSegmentIds)

Method Detail

getOperator

public AudienceSegmentCriteriaComparisonOperator getOperator()

Gets the operator value for this AudienceSegmentCriteria.

Returns:

operator   * The comparison operator. This attribute is required.

setOperator

public void setOperator(AudienceSegmentCriteriaComparisonOperator operator)

Sets the operator value for this AudienceSegmentCriteria.

Parameters:

operator - * The comparison operator. This attribute is required.

getAudienceSegmentIds

public long[] getAudienceSegmentIds()

Gets the audienceSegmentIds value for this AudienceSegmentCriteria.

Returns:

audienceSegmentIds   * The ids of AudienceSegment objects used to target audience
 segments. This attribute is
                     required.

setAudienceSegmentIds

public void setAudienceSegmentIds(long[] audienceSegmentIds)

Sets the audienceSegmentIds value for this AudienceSegmentCriteria.

Parameters:

audienceSegmentIds - * The ids of AudienceSegment objects used to target audience
 segments. This attribute is
                     required.

getAudienceSegmentIds

public long getAudienceSegmentIds(int i)

setAudienceSegmentIds

public void setAudienceSegmentIds(int i,
                         long _value)

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class CustomCriteriaLeaf

hashCode

public int hashCode()

Overrides:

hashCode in class CustomCriteriaLeaf

getTypeDesc

public static org.apache.axis.description.TypeDesc getTypeDesc()

Return type metadata object

getSerializer

public static org.apache.axis.encoding.Serializer getSerializer(java.lang.String mechType,
                                                java.lang.Class _javaType,
                                                javax.xml.namespace.QName _xmlType)

Get Custom Serializer

getDeserializer

public static org.apache.axis.encoding.Deserializer getDeserializer(java.lang.String mechType,
                                                    java.lang.Class _javaType,
                                                    javax.xml.namespace.QName _xmlType)

Get Custom Deserializer

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
1.2 Reference Document
======================

Other modeling information shall be found in the following sources:

:ref:`ELECTRICAL SPECIFICATIONS`

:ref:`DESIGN MANUAL`

redpajama_set_name: RedPajamaGithub


text:
package it.polimi.modaclouds.space4cloud.milp.datafiles;

import it.polimi.modaclouds.space4cloud.milp.Configuration;

public abstract class Model {

	public abstract boolean print(String file1, String file2);

	public static void print() {
		switch (Configuration.MATH_SOLVER) {
		case AMPL:
			ModelAMPL.print();
			break;
		case CMPL:
			ModelCMPL.print();
			break;
		}
	}
}


text:
<?php
/**
 * AuthenticateRepositoryInterface.php
 * Created by @anonymoussc on 05/01/16 17:57.
 */

namespace Componeint\Seneschal\Repositories\Authenticate;

use Componeint\Seneschal\DataTransferObjects\BaseResponse;

/**
 * Interface AuthenticateRepositoryInterface
 * @package Componeint\Seneschal\Repositories\Authenticate
 */
interface AuthenticateRepositoryInterface
{
    /**
     * @param $data
     * @return mixed
     */
    public function store($data);

    /**
     * @return mixed
     */
    public function destroy();
}


text:
package org.ops4j.pax.logging.jbosslogging;

import java.text.MessageFormat;

import org.jboss.logging.Logger;
import org.ops4j.pax.logging.PaxLogger;
import org.ops4j.pax.logging.PaxLoggingManager;
import org.ops4j.pax.logging.PaxLoggingManagerAwareLogger;
import org.ops4j.pax.logging.spi.support.FallbackLogFactory;
import org.osgi.framework.FrameworkUtil;

/**
 * pax-logging specific {@link Logger} that delegates to {@link PaxLogger} that is obtained from
 * framework specific {@link org.ops4j.pax.logging.PaxLoggingService} and eventually delegates to logging
 * implementation.
 */
public class JBossLoggingLogger extends Logger implements PaxLoggingManagerAwareLogger {

    static final String JBOSS_LOGGING_FQCN = JBossLoggingLogger.class.getName();

    private String m_name;
    private volatile PaxLogger m_delegate;

    public JBossLoggingLogger(String name, PaxLogger delegate) {
        super(name);
        m_name = name;
        m_delegate = delegate;
    }

    @Override
    public void setPaxLoggingManager(PaxLoggingManager manager) {
        if (manager == null) {
            m_delegate = FallbackLogFactory.createFallbackLog(FrameworkUtil.getBundle(JBossLoggingLogger.class), m_name);
        } else {
            m_delegate = manager.getLogger(m_name, JBOSS_LOGGING_FQCN);
        }
    }

    @Override
    protected void doLog(Level level, String fqcn, Object message, Object[] parameters, Throwable thrown) {
        final String text = parameters == null || parameters.length == 0 ? String.valueOf(message) : MessageFormat.format(String.valueOf(message), parameters);
        switch (level) {
            case FATAL:
                m_delegate.fqfatal(fqcn, text, thrown);
                break;
            case ERROR:
                m_delegate.fqerror(fqcn, text, thrown);
                break;
            case WARN:
                m_delegate.fqwarn(fqcn, text, thrown);
                break;
            case INFO:
                m_delegate.fqinfo(fqcn, text, thrown);
                break;
            case DEBUG:
                m_delegate.fqdebug(fqcn, text, thrown);
                break;
            case TRACE:
                m_delegate.fqtrace(fqcn, text, thrown);
                break;
        }
    }

    @Override
    protected void doLogf(Level level, String fqcn, String format, Object[] parameters, Throwable thrown) {
        if (parameters == null || parameters.length == 0) {
            doLog(level, fqcn, format, parameters, thrown);
        } else {
            String message = String.format(String.valueOf(format), parameters);
            doLog(level, fqcn, message, null, thrown);
        }
    }

    @Override
    public boolean isEnabled(Level level) {
        switch (level) {
            case FATAL:
                return m_delegate.isFatalEnabled();
            case ERROR:
                return m_delegate.isErrorEnabled();
            case WARN:
                return m_delegate.isWarnEnabled();
            case INFO:
                return m_delegate.isInfoEnabled();
            case DEBUG:
                return m_delegate.isDebugEnabled();
            case TRACE:
                return m_delegate.isTraceEnabled();
        }
        return false;
    }

}


text:
package org.camunda.bpm.engine.rest.helper;

public class ExampleVariableObject {

  private String property1;
  private boolean property2;

  public String getProperty1() {
    return property1;
  }
  public void setProperty1(String property1) {
    this.property1 = property1;
  }
  public boolean isProperty2() {
    return property2;
  }
  public void setProperty2(boolean property2) {
    this.property2 = property2;
  }
}


text:
![Header image](/images/header.png)

## Meet LoopBar - Tab Bar with Infinite Scrolling for Android by Cleveroad

At Cleveroad we've recently come to realize that navigation through categories in an app using nothing but a navigation panel is pretty boring and trivial. That's why, armed with our designer's creativity, we introduce you our new component for Android-based applications -- LoopBar. The idea was to make the navigation menu right at fingerprints, in a tab bar. What's more the view has a few specific features that make it stand out from the crowd of similar ones. So, try out the LoopBar library in your app and you'll see the difference.

![Demo image](/images/demo.gif)

If you strive to create an application with unusual looks and navigation, you are welcome to use the LoopBar library. It's really easy to integrate and can add spice to any app!

If you need more details on how you can use the component and what benefits it provides, read our blog post: Case Study: Loop Bar for Android

[![Article image](/images/article.png)](https://www.cleveroad.com/blog/case-study-loop-bar-for-android)

[![Awesome](/images/logo-footer.png)](https://www.cleveroad.com/?utm_source=github&utm_medium=label&utm_campaign=contacts)

## Setup and usage
### Installation
by gradle :
```groovy
dependencies {
    implementation "com.cleveroad:loopbar:1.2.0"
}
```

or just download zip and import module "LoopBar-widget" to be able to modify the sources

### Features
View consist from two parts:
 - A list of your selectable groups
 - Selected view

View can work in three scroll modes: infinite, finite and auto mode.
Names of first two speak for itself. In auto mode the list of groups
will be infinite if all adapter items didn't fit on screen in other case it will be a static list.
Selected view by request could overlay layout on screen on which it placed.
Widget has horizontal and vertical layouts and also start or end gravity of selected view.

You are allowed to use any RecyclerView adapter, which you want. Concrete infinite scroll logic is fully encapsulated

Android Studio layouts preview is supported.

### Usage
```XML
    <com.cleveroad.loopbar.widget.LoopBarView
        android:id="@+id/endlessView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:enls_placeholderId="@id/placeHolder"
        app:enls_orientation="horizontal"
        app:enls_selectionGravity="start"
        app:enls_selectionMargin="10dp"
        app:enls_overlaySize="5dp"
        app:enls_selectionInAnimation="@animator/enls_scale_restore"
        app:enls_selectionOutAnimation="@animator/enls_scale_small"
        app:enls_selectionBackground="@android:color/holo_blue_dark"
        app:enls_menu="@menu/loopbar"
        app:enls_scrollMode="auto"
        app:enls_listBackground="@android:color/holo_orange_dark"
        />
```

```enls_overlaySize``` & ```enls_placeholderId``` are used for overlay feature.
Placeholder must be the view lying under the LoopBar. And it's used for setting bounds In layout when selected view has overlay.
LoopBar will set width or height for this view by itself (depending of LoopBar orientation), it will be the same as LoopBar has.
Without this placeholder the bounds of LoopBar will be limited by selected view (with overlay). And thanks to placeholder the bounds
will be limited only by list of groups. You can see an example of overlay usage in sample.

|  attribute name | Description |
|---|---|
| enls_overlaySize  | A size of selected view overlaying |
| enls_orientation | Orientation of loopbar view. Can be verticalLeft, verticalRight, horizontalBottom, horizontalTop. Default verticalLeft
| enls_placeholderId | An id of view on which you should use layout:above or other attributes of RelativeLayouts,  because LoopBarView will have increased height in this case. See more in sample |
| enls_selectionGravity | A gravity of selection view. Can be vertical or horizontal. Default horizontal |
| enls_selectionMargin | A margin of selectionView from bounds of view. Default ```5dp``` |
| enls_selectionInAnimation | An animation of appearing an icon inside selection view |
| enls_selectionOutAnimation | An animation of hiding an icon inside selection view |
| enls_selectionBackground | Selection background. Default ```#ff0099cc``` |
| enls_menu | An id of menu which will be used for getting title and icon items  |
| enls_scrollMode | Scrolling mode. Can be ```infinite```, ```finite```, ```auto```. Default ```infinite``` |
| android:background | View have transparent background by default. Use standard ```android:background``` attribute to change it. Default ```#00000000``` |
| enls_listBackground | Set list background. View have yellow list background by default ```#ffc829``` |

To initialize items in widget and work with it you should setup adapter to it and add item click mListener:
```
LoopBarView loopBarView = findViewById(...);
categoriesAdapter = new SimpleCategoriesAdapter(MockedItemsFactory.getCategoryItems(getContext()));
loopBarView.setCategoriesAdapter(categoriesAdapter);
loopBarView.addOnItemClickListener(this);
```
Here SimpleCategoriesAdapter is used which required collection of [ICategoryItem] objects (to draw default view with icon and text).

 Also you can setup adapter through:
*   **Menu** via Java code (see example [MenuLoopBarFragment]):
```
        loopBarView.setCategoriesAdapterFromMenu(R.menu.loopbar);
        //or
        Menu menu = ...;
        loopBarView.setCategoriesAdapterFromMenu(menu);
```
    or via XML:
```
        <com.cleveroad.loopbar.widget.LoopBarView
        ...
        app:enls_menu="@menu/loopbar"
        />
```
* **ViewPager**. Just set a viewPager into your LoopBar. If you want to show category icons, your ViewPager adapter must implement [ILoopBarPagerAdapter] interface (see example [ViewPagerLoopBarFragment]), otherwise the icons will not be shown:
```
    loopBarView.setupWithViewPager(viewPager);
```

To customize wrapped ```RecyclerView``` (control animations, decorators or add ```RecyclerView.OnScrollListener```) you are able to use following methods:

|  method name | description |
|---|---|
| ```setItemAnimator(RecyclerView.ItemAnimator animator)```  | Sets the ```ItemAnimator``` to wrapped RecyclerView |
| ```isAnimating()```  | Returns true if wrapped RecyclerView is currently running some animations |
| ```addItemDecoration(RecyclerView.ItemDecoration decor)```   | Add an ```ItemDecoration``` to wrapped RecyclerView |
| ```addItemDecoration(RecyclerView.ItemDecoration decor, int index)```  | Add an ```ItemDecoration``` to wrapped RecyclerView |
| ```removeItemDecoration(RecyclerView.ItemDecoration decor)``` | Remove an ```ItemDecoration``` from wrapped RecyclerView |
| ```invalidateItemDecorations()``` | Invalidates all ```ItemDecoration```s in wrapped RecyclerView |
| ```addOnScrollListener(RecyclerView.OnScrollListener listener)``` | Add a ```OnScrollListener``` to wrapped RecyclerView |
| ```removeOnScrollListener(RecyclerView.OnScrollListener listener)``` | Remove a ```OnScrollListener``` from wrapped RecyclerView |
| ```clearOnScrollListeners()``` | Remove all secondary ```OnScrollListener``` from wrapped RecyclerView |
| ```setListBackgroundResource(int backgroundResource)``` | Set list background to a given resource |
| ```setListBackgroundColor(int color)``` | Set list background color |
| ```getListBackground()``` | Get list background drawable |
| ```setListBackground(Drawable background)``` | Set list background to a given Drawable |
| ```setListBackgroundTintList(ColorStateList tint)``` | Set tint to the list background drawable |
| ```getListBackgroundTintList()``` | Get tint applied to the list background drawable |
| ```setListBackgroundTintMode(PorterDuff.Mode tintMode)``` | Set blending mode used to apply the tint specified to the list background drawable |
| ```getListBackgroundTintMode()``` | Get blending mode used to apply the tint to the list background drawable |

## Changelog
See [changelog history].

#### Support ####
* * *
If you have any other questions regarding the use of this library, please contact us for support at info@cleveroad.com (email subject: "LoopBar. Support request.")
Also pull requests are welcome.

#### License ####
* * *
    The MIT License (MIT)

    Copyright (c) 2016 Cleveroad Inc.

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

[ILoopBarPagerAdapter]: /LoopBar-widget/src/main/java/com/cleveroad/loopbar/adapter/ILoopBarPagerAdapter.java
[MenuLoopBarFragment]: /sample/src/main/java/com/cleveroad/sample/fragments/MenuLoopBarFragment.java
[ViewPagerLoopbarFragment]: /sample/src/main/java/com/cleveroad/sample/fragments/ViewPagerLoopBarFragment.java
[CategoriesAdapterLoopBarFragment]: /sample/src/main/java/com/cleveroad/sample/fragments/CategoriesAdapterLoopBarFragment.java
[ICategoryItem]: /LoopBar-widget/src/main/java/com/cleveroad/loopbar/adapter/ICategoryItem.java
[changelog history]: /CHANGELOG.md


text:
package com.se1.Activity;

import android.content.Intent;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.se1.dao.DatabaseOperation;
import com.se1.dao.User;
import com.se1.main.MainActivity;
import com.se1.main.R;

public class ResetPasswordActivity extends SherlockFragmentActivity {
    private DatabaseOperation datasource;
    int noOfAttempts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);
        getSupportActionBar().setTitle(R.string.title_activity_reset_password);
        final Button resetPassword   = (Button)findViewById(R.id.resetPassword);
        final EditText oldPassword   = (EditText)findViewById(R.id.oldPassText);
        final EditText newPassword   = (EditText)findViewById(R.id.newPassText);
        noOfAttempts=0;
        datasource = new DatabaseOperation(this);
        datasource.open();

        resetPassword.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        User user=datasource.getUserDetail();
                        if(newPassword.getText().toString().equals("") || newPassword.getText().toString() == null )
                        {
                            Toast.makeText(getApplicationContext(), "Please enter new Password",
                                    Toast.LENGTH_LONG).show();
                        }
                        else if(user!=null && ((user.getEmailId()!= null || user.getEmailId().equalsIgnoreCase(""))))
                        {
                            if(user.getPassword().equals(oldPassword.getText().toString()))
                            {
                                datasource.resetPassword(user.getEmailId(),newPassword.getText().toString());
                                Toast.makeText(getApplicationContext(), "Password is Successfully Reset ",
                                        Toast.LENGTH_LONG).show();
                                goToLoginPage(user.getEmailId());
                            }
                            else {
                                setNoOfAttempts();
                                if(noOfAttempts == 3)
                                {
                                    goToLoginPage(user.getEmailId());
                                }
                                Toast.makeText(getApplicationContext(), "Please Enter Valid Password",
                                        Toast.LENGTH_LONG).show();
                            }

                        }
                    }

                });
    }
    //Navigate to Login page
    public void goToHomePage()
    {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }
    //Navigate to Login page
    public void goToLoginPage(String emaildId)
    {
        datasource.removeSignIn(emaildId);// Go to login page and remove signup option
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    public int getNoOfAttempts() {
        return noOfAttempts;
    }

    public void setNoOfAttempts() {
        noOfAttempts++;
    }

}


text:
package org.apache.hadoop.hbase.regionserver.storefiletracker;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseCommonTestingUtil;
import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
import org.apache.hadoop.hbase.regionserver.StoreContext;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hbase.thirdparty.com.google.common.io.ByteStreams;

import org.apache.hadoop.hbase.shaded.protobuf.generated.StoreFileTrackerProtos.StoreFileEntry;
import org.apache.hadoop.hbase.shaded.protobuf.generated.StoreFileTrackerProtos.StoreFileList;

@Category({ RegionServerTests.class, SmallTests.class })
public class TestStoreFileListFile {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestStoreFileListFile.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestStoreFileListFile.class);

  private static final HBaseCommonTestingUtil UTIL = new HBaseCommonTestingUtil();

  private Path testDir;

  private StoreFileListFile storeFileListFile;

  @Rule
  public TestName name = new TestName();

  private StoreFileListFile create() throws IOException {
    HRegionFileSystem hfs = mock(HRegionFileSystem.class);
    when(hfs.getFileSystem()).thenReturn(FileSystem.get(UTIL.getConfiguration()));
    StoreContext ctx = StoreContext.getBuilder().withFamilyStoreDirectoryPath(testDir)
      .withRegionFileSystem(hfs).build();
    return new StoreFileListFile(ctx);
  }

  @Before
  public void setUp() throws IOException {
    testDir = UTIL.getDataTestDir(name.getMethodName());
    storeFileListFile = create();
  }

  @AfterClass
  public static void tearDown() {
    UTIL.cleanupTestDir();
  }

  @Test
  public void testEmptyLoad() throws IOException {
    assertNull(storeFileListFile.load(false));
  }

  private FileStatus getOnlyTrackerFile(FileSystem fs) throws IOException {
    return fs.listStatus(new Path(testDir, StoreFileListFile.TRACK_FILE_DIR))[0];
  }

  private byte[] readAll(FileSystem fs, Path file) throws IOException {
    try (FSDataInputStream in = fs.open(file)) {
      return ByteStreams.toByteArray(in);
    }
  }

  private void write(FileSystem fs, Path file, byte[] buf, int off, int len) throws IOException {
    try (FSDataOutputStream out = fs.create(file, true)) {
      out.write(buf, off, len);
    }
  }

  @Test
  public void testLoadPartial() throws IOException {
    StoreFileList.Builder builder = StoreFileList.newBuilder();
    storeFileListFile.update(builder);
    FileSystem fs = FileSystem.get(UTIL.getConfiguration());
    FileStatus trackerFileStatus = getOnlyTrackerFile(fs);
    // truncate it so we do not have enough data
    LOG.info("Truncate file {} with size {} to {}", trackerFileStatus.getPath(),
      trackerFileStatus.getLen(), trackerFileStatus.getLen() / 2);
    byte[] content = readAll(fs, trackerFileStatus.getPath());
    write(fs, trackerFileStatus.getPath(), content, 0, content.length / 2);
    assertNull(storeFileListFile.load(false));
  }

  private void writeInt(byte[] buf, int off, int value) {
    byte[] b = Bytes.toBytes(value);
    for (int i = 0; i < 4; i++) {
      buf[off + i] = b[i];
    }
  }

  @Test
  public void testZeroFileLength() throws IOException {
    StoreFileList.Builder builder = StoreFileList.newBuilder();
    storeFileListFile.update(builder);
    FileSystem fs = FileSystem.get(UTIL.getConfiguration());
    FileStatus trackerFileStatus = getOnlyTrackerFile(fs);
    // write a zero length
    byte[] content = readAll(fs, trackerFileStatus.getPath());
    writeInt(content, 0, 0);
    write(fs, trackerFileStatus.getPath(), content, 0, content.length);
    assertThrows(IOException.class, () -> storeFileListFile.load(false));
  }

  @Test
  public void testBigFileLength() throws IOException {
    StoreFileList.Builder builder = StoreFileList.newBuilder();
    storeFileListFile.update(builder);
    FileSystem fs = FileSystem.get(UTIL.getConfiguration());
    FileStatus trackerFileStatus = getOnlyTrackerFile(fs);
    // write a large length
    byte[] content = readAll(fs, trackerFileStatus.getPath());
    writeInt(content, 0, 128 * 1024 * 1024);
    write(fs, trackerFileStatus.getPath(), content, 0, content.length);
    assertThrows(IOException.class, () -> storeFileListFile.load(false));
  }

  @Test
  public void testChecksumMismatch() throws IOException {
    StoreFileList.Builder builder = StoreFileList.newBuilder();
    storeFileListFile.update(builder);
    FileSystem fs = FileSystem.get(UTIL.getConfiguration());
    FileStatus trackerFileStatus = getOnlyTrackerFile(fs);
    // flip one byte
    byte[] content = readAll(fs, trackerFileStatus.getPath());
    content[5] = (byte) ~content[5];
    write(fs, trackerFileStatus.getPath(), content, 0, content.length);
    assertThrows(IOException.class, () -> storeFileListFile.load(false));
  }

  @Test
  public void testLoadNewerTrackFiles() throws IOException, InterruptedException {
    StoreFileList.Builder builder = StoreFileList.newBuilder();
    storeFileListFile.update(builder);

    FileSystem fs = FileSystem.get(UTIL.getConfiguration());
    FileStatus trackFileStatus = getOnlyTrackerFile(fs);

    builder.addStoreFile(StoreFileEntry.newBuilder().setName("hehe").setSize(10).build());
    storeFileListFile = create();
    storeFileListFile.update(builder);

    // should load the list we stored the second time
    storeFileListFile = create();
    StoreFileList list = storeFileListFile.load(true);
    assertEquals(1, list.getStoreFileCount());
    // since read only is true, we should not delete the old track file
    // the deletion is in background, so we will test it multiple times through HTU.waitFor and make
    // sure that it is still there after timeout, i.e, the waitFor method returns -1
    assertTrue(UTIL.waitFor(2000, 100, false, () -> !fs.exists(testDir)) < 0);

    // this time read only is false, we should delete the old track file
    list = storeFileListFile.load(false);
    assertEquals(1, list.getStoreFileCount());
    UTIL.waitFor(5000, () -> !fs.exists(trackFileStatus.getPath()));
  }

  // This is to simulate the scenario where a 'dead' RS perform flush or compaction on a region
  // which has already been reassigned to another RS. This is possible in real world, usually caused
  // by a long STW GC.
  @Test
  public void testConcurrentUpdate() throws IOException {
    storeFileListFile.update(StoreFileList.newBuilder());

    StoreFileListFile storeFileListFile2 = create();
    storeFileListFile2.update(StoreFileList.newBuilder()
      .addStoreFile(StoreFileEntry.newBuilder().setName("hehe").setSize(10).build()));

    // let's update storeFileListFile several times
    for (int i = 0; i < 10; i++) {
      storeFileListFile.update(StoreFileList.newBuilder()
        .addStoreFile(StoreFileEntry.newBuilder().setName("haha-" + i).setSize(100 + i).build()));
    }

    // create a new list file, make sure we load the list generate by storeFileListFile2.
    StoreFileListFile storeFileListFile3 = create();
    StoreFileList fileList = storeFileListFile3.load(true);
    assertEquals(1, fileList.getStoreFileCount());
    StoreFileEntry entry = fileList.getStoreFile(0);
    assertEquals("hehe", entry.getName());
    assertEquals(10, entry.getSize());
  }
}


text:
layout: page
title: Buchanan Financial Trade Fair
date: 2016-05-24
author: Howard Clay
tags: weekly links, java
status: published
summary: Vestibulum rhoncus gravida turpis facilisis consequat. Morbi.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/22/2018
  endDate: 01/24/2018
  ctyhocn: KUFSAHX
  groupCode: BFTF
published: true
---
Fusce eros mauris, commodo vel velit volutpat, fermentum vestibulum diam. Duis aliquet, urna vitae placerat sagittis, ex massa tristique turpis, sed pretium arcu velit id mi. Mauris pellentesque nunc id diam malesuada dictum. Curabitur at leo ornare, porta nisi sed, vestibulum neque. Sed sed eros eget justo pulvinar viverra. Duis ac tincidunt odio. Donec congue porttitor purus eget sodales. Vivamus eu tempus lectus, in bibendum enim. In efficitur nunc id aliquam scelerisque.
Praesent et nibh arcu. Phasellus scelerisque, turpis vel sagittis vehicula, urna velit tincidunt neque, vitae luctus enim nunc convallis sapien. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras gravida pharetra vulputate. Duis ut purus lacus. Ut vehicula ornare ante, sit amet dignissim sem. Phasellus cursus ante massa, quis viverra sapien bibendum non. Nam quam ligula, iaculis quis leo eu, fringilla commodo augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

1 In facilisis urna vel felis aliquet, a sollicitudin nisi tempor
1 Nullam quis purus sed urna dictum sodales non vitae nisi
1 Vestibulum tempor quam vitae eros accumsan, non dignissim dolor malesuada
1 Nam viverra diam at lacus pretium tincidunt.

Aenean a elementum quam. Praesent non nibh a lorem semper posuere. Ut ornare tincidunt mollis. Pellentesque ac nibh sed urna dapibus gravida. Quisque interdum arcu fringilla, blandit turpis sit amet, suscipit arcu. Proin egestas cursus dignissim. Nulla imperdiet elit ac augue egestas, tempus pharetra velit suscipit.


text:
import * as _ from "underscore";
import {default as newickParser} from "./newick";

export function parseAnnotations (buf) {

  let str = buf;
  let index = str.toUpperCase().indexOf('BEGIN DATA;');
  let data = str.slice(index);

  if(data.length < 2) {
    return '';
  }

  index = data.toUpperCase().indexOf('END;');
  let data_str = data.slice(0, index);

  // split on semicolon
  data = _.map(data_str.split(';'), d => { return d.trim() } );

  // get dimensions
  let dimensions = _.filter(data, d => {return d.toUpperCase().startsWith('DIMENSION')});
  dimensions = dimensions[0].split(' ');
  dimensions = _.object(_.map(_.rest(dimensions), d => { return d.split('=') }));

  // get formats
  let format = _.filter(data, d => {return d.toUpperCase().startsWith('FORMAT')});
  format = format[0].split(' ');
  format = _.object(_.map(_.rest(format), d => { return d.split('=') }));
  format.symbols = _.reject(format.symbols.split(""), d => d=='"');

  // get character matrix
  let matrix = _.filter(data, d => {return d.toUpperCase().startsWith('MATRIX')});
  matrix = matrix[0].split('\n')
  matrix = _.object(_.map(_.rest(matrix), d=> { return _.compact(d.split(' ')) }));

  // create all possible states for matrix
  matrix = _.mapObject(matrix, (v,k) => {

    if(v == '?') {
      return format.symbols
    }
    else {
      return Array(v)
    }

  });

  return { 'dimensions' : dimensions, 'format' : format, 'matrix' : matrix }

}

/**
 *  Loads annotations from a nexus-formatted buffer and annotates existing tree
 *  nodes appropriately.
 *
 * @param {Object} tree - Instatiated phylotree
 * @param {String} NEXUS string
 * @returns {Object} Annotations
 */
export function loadAnnotations(tree, label, annotations) {

  // if filename, then load from filesystem
  _.each(tree.getTips(), d => { d.data["test"] = annotations.matrix[d.data.name] });

  // decorate nodes with annotations

}

export default function loadTree(buf) {

  // if filename, then load from filesystem
  // Parse first tree from NEXUS file and send to newickParser

  // Make all upper case
  let str = buf;

  // Get TREE block
  let index = str.toUpperCase().indexOf('BEGIN TREES;');
  let split = str.slice(index);

  if(split.length < 2) {
    return '';
  }

  index = split.toUpperCase().indexOf('END;');
  let tree_str = split.slice(0, index);

  // Filter lines that start with TREE
  let trees = tree_str.split('\n');
  trees = _.filter(trees, d => { return d.trim().toUpperCase().startsWith('TREE') });

  // Identify start of newick string
  return newickParser(trees[0]);

}


text:
import torch
from torch import nn
from torch.nn.modules.utils import _single
from torch import Tensor

class ConvTBC(torch.nn.Module):
    """1D convolution over an input of shape (time x batch x channel)

    The implementation uses gemm to perform the convolution. This implementation
    is faster than cuDNN for small kernel sizes.
    """

    def __init__(self, in_channels, out_channels, kernel_size, padding=0):
        super(ConvTBC, self).__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = _single(kernel_size)
        self.padding = _single(padding)

        self.weight = torch.nn.Parameter(
            torch.Tensor(self.kernel_size[0], in_channels, out_channels)
        )
        self.bias = torch.nn.Parameter(torch.Tensor(out_channels))

        self.reset_parameters()

    def reset_parameters(self):
        nn.init.xavier_normal_(self.weight)
        nn.init.zeros_(self.bias)

    def conv_tbc(self, input: Tensor):
        return torch.conv_tbc(
            input.contiguous(), self.weight, self.bias, self.padding[0]
        )

    def forward(self, input: Tensor):
        return self.conv_tbc(input)

    def __repr__(self):
        s = (
            "{name}({in_channels}, {out_channels}, kernel_size={kernel_size}"
            ", padding={padding}"
        )
        if self.bias is None:
            s += ", bias=False"
        s += ")"
        return s.format(name=self.__class__.__name__, **self.__dict__)


text:
isBumpCommit() {
  msg=`git log --pretty=format:'%s' -1`
  if [[ "$msg" =~ ^\[pr-bumper\]* ]]
  then
    # totally un-intuitive, but returning 0 evaluates to true when put in a if
    # http://stackoverflow.com/a/5431932
    return 0
  else
    # totally un-intuitive, but returning 1 evaluates to false when put in a if
    # http://stackoverflow.com/a/5431932
    return 1
  fi
}


text:
import errors from '../errors';
import * as crypto from 'crypto';
import * as constants from '../constants';
import * as werelogs from 'werelogs';

/**
 * createAggregateETag - creates ETag from concatenated MPU part ETags to
 * mimic AWS
 * @param partETags - array of all parts' unquoted ETags
 * @return aggregateETag - final complete MPU obj ETag
 */
export function createAggregateETag(partETags: string[]) {
    // AWS documentation is unclear on what the MD5 is that it returns
    // in the response for a complete multipart upload request.
    // The docs state that they might or might not
    // return the MD5 of the complete object. It appears
    // they are returning the MD5 of the parts' MD5s so that is
    // what we have done here. We:
    // 1) concatenate the hex version of the
    // individual ETags
    // 2) convert the concatenated hex to binary
    // 3) take the md5 of the binary
    // 4) create the hex digest of the md5
    // 5) add '-' plus the number of parts at the end

    // Convert the concatenated hex ETags to binary
    const concatETags = partETags.reduce((concat, eTag) => concat + eTag, '');
    const bufferedHex = Buffer.from(concatETags, 'hex');
    // Convert the buffer to a binary string
    const binaryString = bufferedHex.toString('binary');
    // Get the md5 of the binary string and the hex digest of the md5
    const md5Hash =
        crypto
            .createHash('md5')
            .update(binaryString, 'binary')
            .digest('hex');
    // Add the number of parts at the end
    return `${md5Hash}-${partETags.length}`;
}

/**
 * generateMpuPartStorageInfo - generates info needed for storage of
 * completed MPU object
 * @param filteredPartList - list of parts filtered from metadata
 * @return partsInfo - contains three keys: aggregateETag,
 * dataLocations, and calculatedSize
 */
export function generateMpuPartStorageInfo(filteredPartList: any[]) {
    // Assemble array of part locations, aggregate size
    // and build string to create aggregate ETag
    let calculatedSize = 0;
    const dataLocations: any[] = [];
    const partETags: string[] = [];

    filteredPartList.forEach((storedPart, index) => {
        const partETagWithoutQuotes = storedPart.ETag.slice(1, -1);
        const dataStoreETag = `${index + 1}:${partETagWithoutQuotes}`;
        partETags.push(partETagWithoutQuotes);

        // If part was put by a regular put part rather than a
        // copy it is always one location.  With a put part
        // copy, could be multiple locations so loop over array
        // of locations.
        for (let j = 0; j < storedPart.locations.length; j++) {
            // If the piece has parts (was a put part object
            // copy) each piece will have a size attribute.
            // Otherwise, the piece was put by a regular put
            // part and the size the of the piece is the full
            // part size.
            const location = storedPart.locations[j];
            // If there is no location, move on
            if (!location || typeof location !== 'object') {
                continue;
            }
            let pieceSize = Number.parseInt(storedPart.size, 10);
            if (location.size) {
                pieceSize = Number.parseInt(location.size, 10);
            }
            const pieceRetrievalInfo = {
                key: location.key,
                size: pieceSize,
                start: calculatedSize,
                dataStoreName: location.dataStoreName,
                dataStoreETag,
                cryptoScheme: location.sseCryptoScheme,
                cipheredDataKey: location.sseCipheredDataKey,
            };
            dataLocations.push(pieceRetrievalInfo);
            // eslint-disable-next-line no-param-reassign
            calculatedSize += pieceSize;
        }
    });

    return {
        aggregateETag: createAggregateETag(partETags),
        dataLocations,
        calculatedSize,
    };
}

/**
 * validateAndFilterMpuParts - validates part list sent by user and filters
 * parts stored in metadata against user part list
 * @param {array} storedParts - array of parts stored in metadata
 * @param {array} jsonList - array of parts sent by user for completion
 * @param {string} mpuOverviewKey - metadata mpu key
 * @param {string} splitter - mpu key divider
 * @param {object} log - Werelogs instance
 * @return {object} filtersPartsObj - contains 3 keys: partList, keysToDelete,
 * and extraPartLocations
 */
export function validateAndFilterMpuParts(
    storedParts: any[],
    jsonList: { Part: any[] },
    mpuOverviewKey: string,
    splitter: string,
    log: werelogs.Logger,
) {
    let storedPartsCopy: any[] = [];
    const filteredPartsObj: any = {};
    filteredPartsObj.partList = [];

    const keysToDelete: string[] = [];
    storedParts.forEach((item: any) => {
        keysToDelete.push(item.key);
        storedPartsCopy.push({
            // In order to delete the part listing in the shadow
            // bucket, need the full key
            key: item.key,
            ETag: `"${item.value.ETag}"`,
            size: item.value.Size,
            locations: Array.isArray(item.value.partLocations) ?
                item.value.partLocations : [item.value.partLocations],
        });
    });
    keysToDelete.push(mpuOverviewKey);

    // Check list sent to make sure valid
    const partLength = jsonList.Part.length;
    // A user can put more parts than they end up including
    // in the completed MPU but there cannot be more
    // parts in the complete message than were already put
    if (partLength > storedPartsCopy.length) {
        filteredPartsObj.error = errors.InvalidPart;
        return filteredPartsObj;
    }

    let extraParts: any = [];
    const extraPartLocations: any = [];

    for (let i = 0; i < partLength; i++) {
        const part = jsonList.Part[i];
        const partNumber = Number.parseInt(part.PartNumber[0], 10);
        // If the complete list of parts sent with
        // the complete multipart upload request is not
        // in ascending order return an error
        if (i > 0) {
            const previousPartNumber =
                Number.parseInt(jsonList.Part[i - 1].PartNumber[0], 10);
            if (partNumber <= previousPartNumber) {
                filteredPartsObj.error = errors.InvalidPartOrder;
                return filteredPartsObj;
            }
        }

        let isPartUploaded = false;
        while (storedPartsCopy.length > 0 && !isPartUploaded) {
            const storedPart = storedPartsCopy[0];
            const storedPartNumber =
                Number.parseInt(storedPart.key.split(splitter)[1], 10);

            if (storedPartNumber === partNumber) {
                isPartUploaded = true;
                filteredPartsObj.partList.push(storedPart);

                let partETag = part.ETag[0].replace(/['"]/g, '');
                // some clients send base64, convert to hex
                // 32 chars = 16 bytes(2 chars-per-byte) = 128 bits of
                // MD5 hex
                if (partETag.length !== 32) {
                    const buffered = Buffer.from(part.ETag[0], 'base64')
                        .toString('hex');
                    partETag = `${buffered}`;
                }
                partETag = `"${partETag}"`;
                // If list of parts sent with complete mpu request contains
                // a part ETag that does not match the ETag for the part
                // stored in metadata, return an error
                if (partETag !== storedPart.ETag) {
                    filteredPartsObj.error = errors.InvalidPart;
                    return filteredPartsObj;
                }

                // If any part other than the last part is less than
                // 5MB, return an error
                const storedPartSize =
                    Number.parseInt(storedPart.size, 10);
                // allow smaller parts for testing
                if (process.env.MPU_TESTING) {
                    log.info('MPU_TESTING env variable setting',
                        { setting: process.env.MPU_TESTING });
                }
                if (process.env.MPU_TESTING !== 'yes' &&
                i < jsonList.Part.length - 1 &&
                storedPartSize < constants.minimumAllowedPartSize) {
                    log.debug('part too small on complete mpu');
                    filteredPartsObj.error = errors.EntityTooSmall;
                    return filteredPartsObj;
                }

                storedPartsCopy = storedPartsCopy.splice(1);
            } else {
                extraParts.push(storedPart);
                storedPartsCopy = storedPartsCopy.splice(1);
            }
        }
        if (!isPartUploaded) {
            filteredPartsObj.error = errors.InvalidPart;
            return filteredPartsObj;
        }
    }
    extraParts = extraParts.concat(storedPartsCopy);
    // if extra parts, need to delete the data when done with completing
    // mpu so extract the info to delete here
    if (extraParts.length > 0) {
        extraParts.forEach(part => {
            const locations = part.locations;
            locations.forEach(location => {
                if (!location || typeof location !== 'object') {
                    return;
                }
                extraPartLocations.push(location);
            });
        });
    }
    filteredPartsObj.keysToDelete = keysToDelete;
    filteredPartsObj.extraPartLocations = extraPartLocations;
    return filteredPartsObj;
}


text:
class ChangeBodyToText < ActiveRecord::Migration
  def up
    change_column :mail_templates, :body, :text
  end

  def down
    change_column :mail_templates, :body, :string
  end
end


text:
<?php namespace Vi\Core\Users\Registration;

use Vi\Core\Users\User;

interface SendsConfirmationEmail {

	/**
	 * Send the user a confirmation email
	 *
	 * @param  User   $user
	 * @return void
	 */
	public function sendConfirmEmail( User $user );

	/**
	 * Confirm the user
	 *
	 * @param  string $code
	 * @param  array  $input
	 * @return void
	 */
	public function confirm( $code, array $input );

}


text:
"""
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from byceps.database import db
from byceps.services.authentication.password.dbmodels import (
    Credential as DbCredential,
)
from byceps.services.authentication.password import service as password_service
from byceps.services.user import log_service

def test_update_password_hash(site_app, admin_user, make_user):
    user = make_user(password='InitialPassw0rd')

    admin_id = admin_user.id
    user_id = user.id

    password_hash_before = get_password_hash(user_id)
    assert password_hash_before is not None

    log_entries_before = log_service.get_entries_for_user(user_id)
    assert len(log_entries_before) == 1  # user creation

    # -------------------------------- #

    password_service.update_password_hash(
        user_id, 'ReplacementPassw0rd', admin_id
    )

    # -------------------------------- #

    password_hash_after = get_password_hash(user_id)
    assert password_hash_after is not None
    assert password_hash_after != password_hash_before

    log_entries_after = log_service.get_entries_for_user(user_id)
    assert len(log_entries_after) == 2

    password_updated_log_entry = log_entries_after[1]
    assert password_updated_log_entry.event_type == 'password-updated'
    assert password_updated_log_entry.data == {
        'initiator_id': str(admin_id),
    }

# helpers

def get_password_hash(user_id):
    credential = db.session.query(DbCredential).get(user_id)
    return credential.password_hash


text:
@class IBConnectionInterfaceStyle, IBImageButton;

@interface IBConnectionDisclosureHeaderView : DVTDisclosureHeaderView
{
    IBImageButton *disclosureImageButton;
    IBConnectionInterfaceStyle *connectionInterfaceStyle;
}

- (void).cxx_destruct;
- (void)drawRect:(struct CGRect)arg1;
- (void)disclosureClicked:(id)arg1;
- (void)layoutBottomUp;
- (double)preferredHeight;
- (struct CGRect)titleFrame;
- (struct CGRect)disclosureButtonFrame;
- (void)setDisclosed:(BOOL)arg1;
- (id)connectionInterfaceStyle;
- (id)frameView;
- (id)initWithFrame:(struct CGRect)arg1 andInterfaceStyle:(id)arg2;

@end


text:
module.exports = {
  Parser: require('./parser'),
  VM: require('./vm'),
  Constants: require('./constants'),
  Errors: require('./errors')
};


text:
var config = require('./');

module.exports = {
    autoprefixer: { browsers: ['last 2 versions'] },
    src: config.sourceAssets + '/sass/**/*{sass,scss}',
    dest: config.publicAssets + '/css',
    settings: {
        indentedSyntax: false, // sass syntax
        imagePath: config.publicAssets + '/images' // image-url helper
    }
};


text:
#pragma once
#include <aws/dlm/DLM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DLM
{
namespace Model
{

  /**
   *
The service failed in an unexpected way.

See Also:
   AWS
   * API Reference

   */
  class AWS_DLM_API InternalServerException
  {
  public:
    InternalServerException();
    InternalServerException(Aws::Utils::Json::JsonView jsonValue);
    InternalServerException& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const Aws::String& GetMessage() const{ return m_message; }

    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    inline InternalServerException& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    inline InternalServerException& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    inline InternalServerException& WithMessage(const char* value) { SetMessage(value); return *this;}

    inline const Aws::String& GetCode() const{ return m_code; }

    inline bool CodeHasBeenSet() const { return m_codeHasBeenSet; }

    inline void SetCode(const Aws::String& value) { m_codeHasBeenSet = true; m_code = value; }

    inline void SetCode(Aws::String&& value) { m_codeHasBeenSet = true; m_code = std::move(value); }

    inline void SetCode(const char* value) { m_codeHasBeenSet = true; m_code.assign(value); }

    inline InternalServerException& WithCode(const Aws::String& value) { SetCode(value); return *this;}

    inline InternalServerException& WithCode(Aws::String&& value) { SetCode(std::move(value)); return *this;}

    inline InternalServerException& WithCode(const char* value) { SetCode(value); return *this;}

  private:

    Aws::String m_message;
    bool m_messageHasBeenSet = false;

    Aws::String m_code;
    bool m_codeHasBeenSet = false;
  };

} // namespace Model
} // namespace DLM
} // namespace Aws


text:
<?php

namespace Gettext\Generators;

use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
use Symfony\Component\Yaml\Yaml as YamlDumper;

class Yaml extends Generator implements GeneratorInterface
{
    use MultidimensionalArrayTrait;

    public static $options = [
        'includeHeaders' => false,
        'indent' => 2,
        'inline' => 4,
    ];

    /**
     * {@inheritdoc}
     */
    public static function toString(Translations $translations, array $options = [])
    {
        $options += static::$options;

        return YamlDumper::dump(self::toArray($translations, $options['includeHeaders']), $options['inline'], $options['indent']);
    }
}


text:
package org.apache.portals.pluto.demo.integration.test;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;

/**
 *
 * @author Kyle Stiemann
 */
public class ElementEnabled implements ExpectedCondition<WebElement> {

   private final By locator;

   public ElementEnabled(By locator) {
      this.locator = locator;
   }

   @Override
   public WebElement apply(WebDriver webDriver) {

      WebElement webElement = null;

      try {

         List<WebElement> webElements = webDriver.findElements(locator);

         if (!webElements.isEmpty() && webElements.get(0).isEnabled()) {
            webElement = webElements.get(0);
         }
      } catch (StaleElementReferenceException e) {
         // Do nothing.
      }

      return webElement;
   }
}


text:
<?php

namespace League\Services;

use Nakade\Standings\Results;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
 * Class ResultService
 *
 * @package League\Services
 */
class ResultService implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $services
     *
     * @return Results
     */
    public function createService(ServiceLocatorInterface $services)
    {
        $config  = $services->get('config');

        //configuration
        $textDomain = isset($config['League']['text_domain']) ?
            $config['League']['text_domain'] : null;

        $translator = $services->get('translator');

        //result types using i18N
        $results  = new Results();
        $results->setTranslator($translator, $textDomain);
        return $results;
    }
}


text:
<?php

namespace awaluk\DhlApi\Structure;

class ItemToPrint implements StructureInterface
{
    private $labelType;
    private $shipmentId;

    /**
     * @param string $labelType
     * @param int $shipmentId
     */
    public function __construct(string $labelType, int $shipmentId)
    {
        $this->labelType = $labelType;
        $this->shipmentId = $shipmentId;
    }

    /**
     * @return array
     */
    public function get(): array
    {
        return get_object_vars($this);
    }
}


text:
#ifndef INCLUDED_OBJECT_HPP
#define INCLUDED_OBJECT_HPP

#include <pdal/pdal_internal.hpp>

#include <boost/property_tree/ptree.hpp>

namespace pdal
{

/// pdal::Object is a base class that provides serialization, allocation, and
/// deallocation control for all basic objects inside of PDAL.

class PDAL_DLL Object
{
public:

    /** @name Constructors
    */
    Object(std::string const& type_name) : m_typename(type_name) {};

    /** @name Destructor
    */
    virtual ~Object() {};

    virtual std::string to_xml() const;
    virtual std::string to_json() const;

    virtual boost::property_tree::ptree toPTreeImpl() const
    {
        return boost::property_tree::ptree();
    }

    boost::property_tree::ptree toPTree() const;
    inline std::string getTypeName() const
    {
        return m_typename;
    }
    /** @name private attributes
    */

private:
    Object(const Object&);
    Object& operator =(const Object&);

    std::string m_typename;

};

} // namespace pdal

#endif


text:
.class Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;
.super Ljava/lang/Object;
.source "MediaList.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sec/android/app/camera/imageviewer/MediaList;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "MediaItem"
.end annotation

# instance fields
.field public dataTaken:J

.field private id:J

.field public mimeType:Ljava/lang/String;

.field public orientation:I

.field public path:Ljava/lang/String;

.field final synthetic this$0:Lcom/sec/android/app/camera/imageviewer/MediaList;

.field public title:Ljava/lang/String;

# direct methods
.method public constructor <init>(Lcom/sec/android/app/camera/imageviewer/MediaList;Landroid/database/Cursor;)V
    .locals 3
    .parameter
    .parameter "cursor"

    .prologue
    const/4 v2, 0x1

    .line 328
    iput-object p1, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->this$0:Lcom/sec/android/app/camera/imageviewer/MediaList;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 329
    const/4 v0, 0x0

    invoke-interface {p2, v0}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v0

    iput-wide v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->id:J

    .line 330
    invoke-interface {p2, v2}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->path:Ljava/lang/String;

    .line 331
    const/4 v0, 0x2

    invoke-interface {p2, v0}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->title:Ljava/lang/String;

    .line 332
    const/4 v0, 0x3

    invoke-interface {p2, v0}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->mimeType:Ljava/lang/String;

    .line 333
    const/4 v0, 0x4

    invoke-interface {p2, v0}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v0

    iput-wide v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->dataTaken:J

    .line 334
    iget-object v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->mimeType:Ljava/lang/String;

    const-string v1, "image/"

    invoke-virtual {v0, v1}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v0

    if-ne v0, v2, :cond_0

    .line 335
    const/4 v0, 0x5

    invoke-interface {p2, v0}, Landroid/database/Cursor;->getInt(I)I

    move-result v0

    iput v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->orientation:I

    .line 338
    :goto_0
    return-void

    .line 337
    :cond_0
    const/4 v0, -0x1

    iput v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->orientation:I

    goto :goto_0
.end method

.method static synthetic access$000(Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;)J
    .locals 2
    .parameter "x0"

    .prologue
    .line 320
    iget-wide v0, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->id:J

    return-wide v0
.end method

# virtual methods
.method public getUri(Z)Landroid/net/Uri;
    .locals 3
    .parameter "isVideo"

    .prologue
    .line 341
    if-eqz p1, :cond_0

    .line 342
    sget-object v0, Landroid/provider/MediaStore$Video$Media;->EXTERNAL_CONTENT_URI:Landroid/net/Uri;

    iget-wide v1, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->id:J

    invoke-static {v0, v1, v2}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;

    move-result-object v0

    .line 345
    :goto_0
    return-object v0

    :cond_0
    sget-object v0, Landroid/provider/MediaStore$Images$Media;->EXTERNAL_CONTENT_URI:Landroid/net/Uri;

    iget-wide v1, p0, Lcom/sec/android/app/camera/imageviewer/MediaList$MediaItem;->id:J

    invoke-static {v0, v1, v2}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;

    move-result-object v0

    goto :goto_0
.end method


text:
<DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">

<title>PubMed++ - Search</title>

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="js/chosen/chosen-boot.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

Search

                <form class="navbar-form navbar-left" role="search">

                        <input type="text" name="q" class="form-control" placeholder="PubMed ID (PMID)">

                    <button type="submit" formaction="info.html" class="btn btn-default">Info!</button>
                </form>

Plugin

Help

PubMed++

Enhance your PubMed searches with the "knowledge graph".

        <select id="pubmed_chosen" target="_blank" name="pubmed_chosen" class="chzn-choices-lg" multiple="multiple" data-placeholder="Select concepts to search PubMed" style="width: 450px;"></select>
        <button id="generate_query" class="btn btn-default btn-lg" onclick="getClassDescendants();">PubMed++ Enhanced Search</button>

        <form enctype="application/x-www-form-urlencoded" method="post" action="http://www.ncbi.nlm.nih.gov/pubmed">
          <input type="hidden" name="term" id="pm_term" value="">
          <input type="hidden" name="from_pubmed++" value="true">
          <button id="search_pubmed">Search</button>
        </form>


text:
package picocli.examples.jsr380.beanvalidation;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import picocli.CommandLine;
import picocli.CommandLine.IExecutionStrategy;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult;

import java.util.Set;

class ValidatingExecutionStrategy implements IExecutionStrategy {
    public int execute(ParseResult parseResult) {
        validate(parseResult.commandSpec());
        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
    }

    void validate(CommandSpec spec) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(spec.userObject());
        if (!violations.isEmpty()) {
            String errorMsg = "";
            for (ConstraintViolation<?> violation : violations) {
                errorMsg += "ERROR: " + violation.getMessage() + "\n";
            }
            throw new ParameterException(spec.commandLine(), errorMsg);
        }
    }
}


text:
import * as React from 'react';
import {addComponentCSS} from '../../utils/css_styler';

addComponentCSS({
  //language=CSS
  default: `
  .pr-hello-world__title {
    margin: 10px 15px;
  }
  `
});

interface IHelloWorldProps {
  helloString: string
}

export class HelloWorld extends React.Component<IHelloWorldProps, any> {
  public render(): JSX.Element {
    const {helloString} = this.props;
    return (
      <h1 className="pr-hello-world__title">
        {helloString}
      </h1>
    );
  }
}


text:
package at.gridgears.aml;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static at.gridgears.aml.PositioningMethod.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

public class PositioningMethodMapperTest {
    private final PositioningMethodMapper positioningMethodMapper = new PositioningMethodMapper();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void resolveGNSS() {
        assertThat(positioningMethodMapper.get("G"), is(GNSS));
    }

    @Test
    public void resolveWifiSignal() {
        assertThat(positioningMethodMapper.get("W"), is(WIFI_SIGNAL));
    }

    @Test
    public void resolveCell() {
        assertThat(positioningMethodMapper.get("C"), is(CELL));
    }

    @Test
    public void resolveNoLocation() {
        assertThat(positioningMethodMapper.get("N"), is(NO_LOCATION));
    }

    @Test
    public void throwsExceptionOnUnknown() {
        thrown.expect(IllegalArgumentException.class);

        positioningMethodMapper.get("ZZ");
    }

    @Test
    public void returnsNullOnNull() {
        assertThat(positioningMethodMapper.get(null), nullValue());
    }
}


text:
const MongoClient = require('mongodb').MongoClient

let database, client

function db() {
  if (database) {
    return Promise.resolve(database)
  } else {
    return new Promise((resolve, reject) => {
      MongoClient.connect(
        process.env.DATABASE_URL,
        (err, dbClient) => {
          if (err) {
            console.log('connection error:', err, process.env.DATABASE_URL)
            reject(err)
          } else {
            client = dbClient
            database = client.db()
            resolve(database)
          }
        }
      )
    })
  }
}

function close() {
  if (client) {
    client.close()
  }
}

module.exports = {
  db,
  close,
}


text:
//
//  XHHomeViewController.m
//  DYZB
//
//  Created by juxiaohui on 16/11/24.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

#import "XHHomeViewController.h"
#import "UIBarButtonItem+XHExt.h"
#import "XHPageTitleView.h"
#import "XHPageContentView.h"
#import "XHRecommendViewController.h"
#import "XHOtherCategoryTagController.h"

@interface XHHomeViewController ()<XHPageTitleViewDelegate,XHPageContentViewDelegate>

@property(nonatomic, strong)XHPageTitleView * titleView;
@property(nonatomic, strong)XHPageContentView * contentView;

@end

@implementation XHHomeViewController

#pragma mark - lazyLoad

-(XHPageContentView *)contentView{
    if (!_contentView) {
        CGFloat contentH = ScreenHeight - NavigationBarH - titleViewH - TabBarH;

        CGRect rect = CGRectMake(0, NavigationBarH + titleViewH, ScreenWidth, contentH);

        XHRecommendViewController * recommendVc = [[XHRecommendViewController alloc]init];
        NSMutableArray * VCs = [NSMutableArray array];
        [VCs addObject:recommendVc];

        NSArray * titles = @[@"手游",@"娱乐",@"游戏",@"趣玩"];

        for (int i= 0; i<titles.count; i++) {
            XHOtherCategoryTagController * vc = [[XHOtherCategoryTagController alloc]init];
            vc.tagName = titles[i];
            [VCs addObject:vc];
        }
        XHPageContentView * contentView = [[XHPageContentView alloc]initWithFrame:rect childViewControllers:VCs parentViewController:self];
            contentView.delegate = self;
        _contentView = contentView;
    }
    return _contentView;
}
-(XHPageTitleView *)titleView{
    if (!_titleView) {
        XHPageTitleView * titleView = [[XHPageTitleView alloc]initWithFrame:CGRectMake(0, NavigationBarH, ScreenWidth, titleViewH) titles:@[@"推荐",@"手游",@"娱乐",@"游戏",@"趣玩"]];
        titleView.delegate = self;
        _titleView = titleView;
    }
    return _titleView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    [self setupNavigationBar];

}

-(void)setupUI{

    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.contentView];
}

-(void)setupNavigationBar{

    UIBarButtonItem * logoItem = [UIBarButtonItem itemWithImage:@"homeLogoIcon" highImage:nil size:CGSizeZero target:self action:@selector(logoItemClick)];
    self.navigationItem.leftBarButtonItem = logoItem;

    CGSize  size = CGSizeMake(35, 35);
    UIBarButtonItem * historyItem = [UIBarButtonItem itemWithImage:@"viewHistoryIcon" highImage:nil size:size target:self action:@selector(historyItemClick)];
    UIBarButtonItem * searchItem = [UIBarButtonItem itemWithImage:@"searchBtnIcon" highImage:nil size:size target:self action:@selector(searchItemClick)];
    UIBarButtonItem * qrcodeItem = [UIBarButtonItem itemWithImage:@"scanIcon" highImage:nil size:size target:self action:@selector(qrcodeItemClick)];
    self.navigationItem.rightBarButtonItems = @[historyItem,searchItem,qrcodeItem];
}

#pragma mark - 按钮事件监听

-(void)logoItemClick{

}
-(void)historyItemClick{

}
-(void)searchItemClick{

}
-(void)qrcodeItemClick{

}

#pragma mark - XHPageTitleViewDelegate

-(void)XHPageTitleView:(XHPageTitleView *)titleView selectedIndex:(NSInteger)index{

    [self.contentView setCurrentIndex:index];
}

#pragma mark - XHPageContentViewDelegate

-(void)XHPageContentView:(XHPageContentView *)contentView scrollWithSourceIndex:(NSInteger)sourceIndex targetIndex:(NSInteger)targetIndex progress:(CGFloat)progress{

    [self.titleView setTitleViewWithSourceIndex:sourceIndex targetIndex:targetIndex progress:progress];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
require 'acts_as_decimal/acts_as_decimal'
require 'active_record'

ActiveRecord::Base.send :include, ActsAsDecimal


text:
package com.hazelcast.impl;

import com.hazelcast.config.Config;
import com.hazelcast.core.*;
import com.hazelcast.impl.partition.PartitionInfo;
import com.hazelcast.impl.partition.PartitionListener;
import com.hazelcast.impl.partition.PartitionReplicaChangeEvent;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Data;
import com.hazelcast.partition.MigrationEvent;
import com.hazelcast.partition.MigrationListener;
import com.hazelcast.partition.Partition;
import com.hazelcast.partition.PartitionService;
import org.junit.Ignore;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.nio.IOUtil.toData;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;

@Ignore
public class TestUtil {

    public static boolean migrateKey(Object key, HazelcastInstance oldest, HazelcastInstance to, final int replicaIndex) throws Exception {
        final int partitionId = oldest.getPartitionService().getPartition(key).getPartitionId();
        final ConcurrentMapManager concurrentMapManagerOldest = getConcurrentMapManager(oldest);
        final ConcurrentMapManager concurrentMapManagerTo = getConcurrentMapManager(to);
        final PartitionInfo partitionInfoOldest = concurrentMapManagerOldest.getPartitionInfo(partitionId);
        final PartitionInfo partitionInfoTo = concurrentMapManagerTo.getPartitionInfo(partitionId);
        final MemberImpl currentOwnerMember = concurrentMapManagerOldest.getMember(partitionInfoOldest.getReplicaAddress(replicaIndex));
        final MemberImpl toMember = (MemberImpl) to.getCluster().getLocalMember();
        if (!currentOwnerMember.equals(toMember)) {
            final Address addressCurrentOwner = currentOwnerMember.getAddress();
            final Address addressNewOwner = toMember.getAddress();
            PartitionListenerLatch latchOldest = new PartitionListenerLatch(toMember.getAddress(), partitionId, replicaIndex);
            PartitionListenerLatch latchTo = new PartitionListenerLatch(toMember.getAddress(), partitionId, replicaIndex);
            concurrentMapManagerOldest.getPartitionManager().addPartitionListener(latchOldest);
            concurrentMapManagerTo.getPartitionManager().addPartitionListener(latchTo);
            concurrentMapManagerOldest.enqueueAndReturn(new Processable() {
                public void process() {
                    concurrentMapManagerOldest.partitionManager.forcePartitionOwnerMigration(partitionId, replicaIndex, addressCurrentOwner, addressNewOwner);
                }
            });
            assertTrue("Migration should get completed in 20 seconds!!", latchOldest.await(20, TimeUnit.SECONDS));
            assertTrue("Migration should get completed in 20 seconds!!", latchTo.await(20, TimeUnit.SECONDS));
        }
        assertEquals(toMember.getAddress(), partitionInfoOldest.getReplicaAddress(replicaIndex));
        assertEquals(toMember.getAddress(), partitionInfoTo.getReplicaAddress(replicaIndex));
        return true;
    }

    public static class MigrationCompletionLatch implements MigrationListener {
        final int partitionId;
        final CountDownLatch latch;

        public MigrationCompletionLatch(Object key, HazelcastInstance... h) {
            this.partitionId = h[0].getPartitionService().getPartition(key).getPartitionId();
            this.latch = new CountDownLatch(h.length);
            for (HazelcastInstance hazelcastInstance : h) {
                hazelcastInstance.getPartitionService().addMigrationListener(this);
            }
        }

        public void migrationStarted(MigrationEvent migrationEvent) {
        }

        public void migrationCompleted(MigrationEvent migrationEvent) {
            if (migrationEvent.getPartitionId() == partitionId) {
                latch.countDown();
            }
        }

        public void migrationFailed(final MigrationEvent migrationEvent) {
        }

        public boolean await(int time, TimeUnit timeUnit) throws InterruptedException {
            return latch.await(time, timeUnit);
        }
    }

    static class PartitionListenerLatch implements PartitionListener {
        final CountDownLatch migrationLatch = new CountDownLatch(1);
        final Address toAddress;
        final int partitionId;
        final int replicaIndex;

        PartitionListenerLatch(Address toAddress, int partitionId, int replicaIndex) {
            this.toAddress = toAddress;
            this.partitionId = partitionId;
            this.replicaIndex = replicaIndex;
        }

        public void replicaChanged(PartitionReplicaChangeEvent event) {
            if (event.getReplicaIndex() == replicaIndex
                    && event.getPartitionId() == partitionId
                    && toAddress != null
                    && toAddress.equals(event.getNewAddress())) {
                migrationLatch.countDown();
            }
        }

        public boolean await(int time, TimeUnit timeUnit) throws InterruptedException {
            return migrationLatch.await(time, timeUnit);
        }
    }

    public static Node getNode(HazelcastInstance h) {
        FactoryImpl.HazelcastInstanceProxy hiProxy = (FactoryImpl.HazelcastInstanceProxy) h;
        return hiProxy.getFactory().node;
    }

    public static ConcurrentMapManager getConcurrentMapManager(HazelcastInstance h) {
        return getNode(h).concurrentMapManager;
    }

    public static CMap mockCMap(String name) {
        FactoryImpl mockFactory = mock(FactoryImpl.class);
        Node node = new Node(mockFactory, new Config());
        node.serviceThread = Thread.currentThread();
        return new CMap(node.concurrentMapManager, "c:" + name);
    }

    public static CMap getCMap(HazelcastInstance h, String name) {
        ConcurrentMapManager concurrentMapManager = getConcurrentMapManager(h);
        String fullName = Prefix.MAP + name;
        return concurrentMapManager.getMap(fullName);
    }

    public static CMap getCMapForMultiMap(HazelcastInstance h, String name) {
        ConcurrentMapManager concurrentMapManager = getConcurrentMapManager(h);
        String fullName = Prefix.MULTIMAP + name;
        return concurrentMapManager.getMap(fullName);
    }

    public static Partition getPartitionById(PartitionService partitionService, int partitionId) {
        for (Partition partition : partitionService.getPartitions()) {
            if (partition.getPartitionId() == partitionId) {
                return partition;
            }
        }
        return null;
    }

    public static Record newRecord(CMap cmap, long recordId, Data key, Data value) {
        return new DefaultRecord(cmap, 1, key, value, 0, 0, recordId);
    }

    public static Record newRecord(long recordId, Data key, Data value) {
        CMap cmap = mock(CMap.class);
        return newRecord(cmap, recordId, key, value);
    }

    public static Record newRecord(CMap cmap, long recordId, Object key, Object value) {
        return newRecord(cmap, recordId, toData(key), toData(value));
    }

    public static Record newRecord(long recordId, Object key, Object value) {
        return newRecord(recordId, toData(key), toData(value));
    }

    public static Record newRecord(long recordId) {
        return newRecord(recordId, null, null);
    }

    public static Request newPutRequest(Data key, Data value) {
        return newPutRequest(key, value, -1);
    }

    public static Request newPutRequest(Data key, Data value, long ttl) {
        return newRequest(ClusterOperation.CONCURRENT_MAP_PUT, key, value, ttl);
    }

    public static Request newPutIfAbsentRequest(Data key, Data value, long ttl) {
        return newRequest(ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT, key, value, ttl);
    }

    public static Request newRequest(ClusterOperation operation, Data key, Data value, long ttl) {
        Request request = new Request();
        request.setLocal(operation, null, key, value, -1, -1, ttl, null);
        return request;
    }

    public static Request newRemoveRequest(Data key) {
        return newRequest(ClusterOperation.CONCURRENT_MAP_REMOVE, key, null, -1);
    }

    public static Request newEvictRequest(Data key) {
        return newRequest(ClusterOperation.CONCURRENT_MAP_EVICT, key, null, -1);
    }

    public static Request newGetRequest(Data key) {
        return newRequest(ClusterOperation.CONCURRENT_MAP_GET, key, null, -1);
    }

    public static Request newContainsRequest(Data key, Data value) {
        if (value == null) {
            return newRequest(ClusterOperation.CONCURRENT_MAP_CONTAINS_KEY, key, value, -1);
        } else {
            return newRequest(ClusterOperation.CONCURRENT_MAP_CONTAINS_ENTRY, key, value, -1);
        }
    }

    @Ignore
    public static class ValueType implements Serializable {
        String typeName;

        public ValueType(String typeName) {
            this.typeName = typeName;
        }

        public ValueType() {
        }

        public String getTypeName() {
            return typeName;
        }
    }

    @Ignore
    public static abstract class AbstractValue implements Serializable {
        public String name;

        public AbstractValue(String name) {
            this.name = name;
        }

        protected AbstractValue() {
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            final AbstractValue that = (AbstractValue) o;

            if (name != null ? !name.equals(that.name) : that.name != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return name != null ? name.hashCode() : 0;
        }
    }

    @Ignore
    public static class Value extends AbstractValue implements Serializable {
        ValueType type;
        int index;

        public Value(String name, ValueType type, int index) {
            super(name);
            this.type = type;
            this.index = index;
        }

        public Value(String name, int index) {
            super(name);
            this.index = index;
        }

        public Value(String name) {
            this(name, null, 0);
        }

        public Value() {
            super("unknown");
        }

        public ValueType getType() {
            return type;
        }

        public int getIndex() {
            return index;
        }

        public void setIndex(final int index) {
            this.index = index;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            if (!super.equals(o)) return false;

            final Value value = (Value) o;

            if (index != value.index) return false;
            if (type != null ? !type.equals(value.type) : value.type != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = super.hashCode();
            result = 31 * result + (type != null ? type.hashCode() : 0);
            result = 31 * result + index;
            return result;
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            sb.append("Value");
            sb.append("{name=").append(name);
            sb.append(", index=").append(index);
            sb.append(", type=").append(type);
            sb.append('}');
            return sb.toString();
        }
    }

    @Ignore
    public static class EmptyMapEntry implements MapEntry {
        private long cost;
        private long creationTime;
        private long expirationTime;
        private int hits;
        private long lastAccessTime;
        private long lastUpdateTime;
        private long lastStoredTime;
        private int version;
        private boolean valid;
        private Object key;
        private Object value;
        private long id;

        public EmptyMapEntry(long id) {
            this.id = id;
        }

        public long getCost() {
            return cost;
        }

        public long getCreationTime() {
            return creationTime;
        }

        public long getExpirationTime() {
            return expirationTime;
        }

        public int getHits() {
            return hits;
        }

        public long getLastAccessTime() {
            return lastAccessTime;
        }

        public long getLastStoredTime() {
            return lastStoredTime;
        }

        public long getLastUpdateTime() {
            return lastUpdateTime;
        }

        public long getVersion() {
            return version;
        }

        public boolean isValid() {
            return valid;
        }

        public Object getKey() {
            return key;
        }

        public Object getValue() {
            return value;
        }

        public Object setValue(Object value) {
            Object oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public void setCost(long cost) {
            this.cost = cost;
        }

        public void setCreationTime(long creationTime) {
            this.creationTime = creationTime;
        }

        public void setExpirationTime(long expirationTime) {
            this.expirationTime = expirationTime;
        }

        public void setHits(int hits) {
            this.hits = hits;
        }

        public void setKey(Object key) {
            this.key = key;
        }

        public void setLastAccessTime(long lastAccessTime) {
            this.lastAccessTime = lastAccessTime;
        }

        public void setLastUpdateTime(long lastUpdateTime) {
            this.lastUpdateTime = lastUpdateTime;
        }

        public void setValid(boolean valid) {
            this.valid = valid;
        }

        public void setVersion(int version) {
            this.version = version;
        }

        public long getId() {
            return id;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            EmptyMapEntry that = (EmptyMapEntry) o;
            if (id != that.id) return false;
            return true;
        }

        @Override
        public int hashCode() {
            return (int) (id ^ (id >>> 32));
        }

        @Override
        public String toString() {
            return "EmptyMapEntry{" +
                    "id=" + id +
                    ", expirationTime=" + expirationTime +
                    ", hits=" + hits +
                    ", lastAccessTime=" + lastAccessTime +
                    ", lastUpdateTime=" + lastUpdateTime +
                    ", key=" + key +
                    ", value=" + value +
                    ", valid=" + valid +
                    ", creationTime=" + creationTime +
                    ", cost=" + cost +
                    ", version=" + version +
                    '}';
        }
    }

    @Ignore
    public static class OrderUpdateRunnable implements Serializable, Runnable, PartitionAware<Integer>, HazelcastInstanceAware {
        int customerId;
        int orderId;
        transient HazelcastInstance hazelcastInstance;

        public OrderUpdateRunnable(int orderId, int customerId) {
            this.customerId = customerId;
            this.orderId = orderId;
        }

        public void run() {
            if (!hazelcastInstance.getPartitionService().getPartition(customerId).getOwner().localMember()) {
                throw new RuntimeException("Not local member");
            }
        }

        public int getCustomerId() {
            return customerId;
        }

        public int getOrderId() {
            return orderId;
        }

        public Integer getPartitionKey() {
            return customerId;
        }

        public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
            this.hazelcastInstance = hazelcastInstance;
        }

        @Override
        public String toString() {
            return "OrderUpdateRunnable{" +
                    "customerId=" + customerId +
                    ", orderId=" + orderId +
                    '}';
        }
    }

    @Ignore
    public static class OrderUpdateCallable implements Serializable, Callable<Boolean>, PartitionAware, HazelcastInstanceAware {
        int customerId;
        int orderId;
        transient HazelcastInstance hazelcastInstance;

        public OrderUpdateCallable(int orderId, int customerId) {
            this.customerId = customerId;
            this.orderId = orderId;
        }

        public Boolean call() throws Exception {
            return hazelcastInstance.getPartitionService().getPartition(customerId).getOwner().localMember();
        }

        public int getCustomerId() {
            return customerId;
        }

        public int getOrderId() {
            return orderId;
        }

        public Object getPartitionKey() {
            return customerId;
        }

        public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
            this.hazelcastInstance = hazelcastInstance;
        }

        @Override
        public String toString() {
            return "OrderUpdateCallable{" +
                    "customerId=" + customerId +
                    ", orderId=" + orderId +
                    '}';
        }
    }

    @Ignore
    public static class OrderKey implements Serializable, PartitionAware {
        int customerId;
        int orderId;

        public OrderKey(int orderId, int customerId) {
            this.customerId = customerId;
            this.orderId = orderId;
        }

        public int getCustomerId() {
            return customerId;
        }

        public int getOrderId() {
            return orderId;
        }

        public Object getPartitionKey() {
            return customerId;
        }

        @Override
        public String toString() {
            return "OrderKey{" +
                    "customerId=" + customerId +
                    ", orderId=" + orderId +
                    '}';
        }
    }

    public static enum State {
        STATE1, STATE2
    }

    @Ignore
    public static class Employee implements Serializable {
        long id;
        String name;
        String city;
        int age;
        boolean active;
        double salary;
        Timestamp date;
        Date createDate;
        java.sql.Date sqlDate;
        State state;

        public Employee(long id, String name, int age, boolean live, double salary, State state) {
            this.state = state;
        }

        public Employee(long id, String name, int age, boolean live, double salary) {
            this(id, name, null, age, live, salary);
        }

        public Employee(String name, int age, boolean live, double salary) {
            this(-1, name, age, live, salary);
        }

        public Employee(long id, String name, String city, int age, boolean live, double salary) {
            this.id = id;
            this.name = name;
            this.city = city;
            this.age = age;
            this.active = live;
            this.salary = salary;
            this.createDate = new Date();
            this.date = new Timestamp(createDate.getTime());
            this.sqlDate = new java.sql.Date(createDate.getTime());
        }

        public Employee() {
        }

        public Timestamp getDate() {
            return date;
        }

        public String getName() {
            return name;
        }

        public String getCity() {
            return city;
        }

        public int getAge() {
            return age;
        }

        public double getSalary() {
            return salary;
        }

        public boolean isActive() {
            return active;
        }

        public State getState() {
            return state;
        }

        public void setState(State state) {
            this.state = state;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Employee employee = (Employee) o;
            if (active != employee.active) return false;
            if (age != employee.age) return false;
            if (Double.compare(employee.salary, salary) != 0) return false;
            if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
            return true;
        }

        @Override
        public int hashCode() {
            int result;
            long temp;
            result = name != null ? name.hashCode() : 0;
            result = 31 * result + age;
            result = 31 * result + (active ? 1 : 0);
            temp = salary != +0.0d ? Double.doubleToLongBits(salary) : 0L;
            result = 31 * result + (int) (temp ^ (temp >>> 32));
            return result;
        }

        @Override
        public String toString() {
            final StringBuffer sb = new StringBuffer();
            sb.append("Employee");
            sb.append("{name='").append(name).append('\'');
            sb.append(", city=").append(city);
            sb.append(", age=").append(age);
            sb.append(", active=").append(active);
            sb.append(", salary=").append(salary);
            sb.append('}');
            return sb.toString();
        }
    }
}