text:
node-func-queue
===============

A simple NodeJS function sequence & concurrent execute Queue.

## Installation

```bash
$ npm install func-queue
```

## Usage

```javascript
var queue = require('func-queue');

console.log("Queue test:");
var q = queue.createQueue(function(err, code) {
  console.log("error: " + err + " code: " + code);
}, function() {
  console.log("finished");
});
q.add(function(arg1) {
  console.log("step1, arg1: " + arg1);
  q.deliver(++arg1);
});
q.add(function(arg1) {
  console.log("step2, arg1: " + arg1);
  q.append(function(arg1) {
    console.log("step3, arg1: " + arg1);
    return q.error("last", -1);
    console.log("This is never printed.");
  });
  q.deliver(++arg1);
});
q.execute(1);

console.log("PersistentQueue test:");
var pq = queue.createPersistentQueue(function(err, code) {
  console.log("error: " + err + " code: " + code);
}, function() {
  console.log("finished");
});
pq.add(function(i) {
  console.log("value: " + i);
});
pq.execute(1);
pq.execute(2);

console.log("ConcurrentQueue test:");
var qa = queue.createConcurrentQueue(function(results) {
  console.log("ConcurrentQueue results:");
  for(var i=0; i<results.length; i++) {
    var result = results[i];
    console.log("key: %s, error: %j, successed: %j", result.key, result.error, result.successed);
  }
});
var q1 = qa.createQueue("k1");
q1.add(function() {
  setTimeout(function() {
    console.log("k1, func1");
    q1.deliver("q1 successed", 999);
  }, 100);
});
var q2 = qa.createQueue("k2");
q2.add(function() {
  console.log("k2, func1");
  q2.deliver();
});
q2.add(function() {
  setTimeout(function() {
    console.log("k2, func2");
    q2.error("q2 error");
  }, 200);
});
qa.execute();
```
### Output
```
Queue test:
step1, arg1: 1
step2, arg1: 2
step3, arg1: 3
error: last code: -1
PersistentQueue test:
value: 1
value: 2
ConcurrentQueue test:
k2, func1
k1, func1
k2, func2
ConcurrentQueue results:
key: k1, error: null, successed: {"0":"q1 successed","1":999}
key: k2, error: {"0":"q2 error"}, successed: null
```

## API

***
### createQueue(callback_error, [callback_succssed], [callback_thisArg])

Creates a new query Queue.

#### callback_error([...])

The callback function was called when the `Queue`'s function call `error()`.

#### callback_successed([...])

The callback function was called when the `Queue` executed completed. It's parameters come from the last function call `deliver()`.
If the function was undefined or null, call callback_error with append new first parameter to null when completed.

#### callback_thisArg

The value of `this` provided for the call to `callback_error()` and `callback_successed()`.

### Queue.add(callback)

Add a delegate function. This query will be queued for execution until `execute()` was called by the `Queue`.
Calling `add()` on an already executing Queue has throws an Exception.

#### callback([...])

The current `Queue` object is its value of `this` when it called.

### Queue.append(callback)

Append a delegate function when the Queue already executing.

#### callback([...])

The current `Queue` object is its value of `this` when it called.

### error([...])

Call it when the delegate function catch a error.

### escape([...])

Call it when the delegate function escape the Queue as completed.

### deliver([...])

Deliver to the next delegate function in the Queue.

### Queue.execute([...])

Executes all function that were queued using `Queue.add` as sequence.
Calling `execute()` on an already executing Queue has throws an Exception.

***
### createPersistentQueue(callback_error, callback_succssed, [callback_thisArg])

Creates a new query Queue.

#### callback_error([...])

The callback function was called when the `PersistentQueue`'s function call `error()`.

#### callback_successed([...])

The callback function was called when the `PersistentQueue` executed completed. It's parameters come from the last function call `deliver()`.

#### callback_thisArg

The value of `this` provided for the call to `callback_error()` and `callback_successed()`.

### PersistentQueue.add(callback)

Add a delegate function. This query will be queued for execution until `execute()` was called by the `PersistentQueue`.
Calling `add()` on an already executing Queue has throws an Exception.

#### callback([...])

The current `PersistentQueue` object is its value of `this` when it called.

### error([...])

Call it when the delegate function catch a error.

### escape([...])

Call it when the delegate function escape the Queue as completed.

### deliver([...])

Deliver to the next delegate function in the Queue.

### PersistentQueue.execute([...])

Executes all function that were queued using `PersistentQueue.add` as sequence.
Calling `execute()` on an already executing Queue has throws an Exception.

***
### createConcurrentQueue(callback_done, [callback_thisArg])

Creates a new query ConcurrentQueue.

#### callback_done(results)

The callback function was called when the `ConcurrentQueue`'s all child `Queue` was completed.

### ConcurrentQueue.createQueue([key])

Create and add a child `Queue`, return the new `Queue`'s instance. Don't direct call the `Queue`'s `execute()`, it automatic be called until `execute()` was called by the `ConcurrentQueue`.
Calling `createQueue()` on an already executing ConcurrentQueue has throws an Exception.

### ConcurrentQueue.execute()

Executes all child `Queue` that were created using `ConcurrentQueue.createQueue` as concurrented.
Calling `execute()` on an already executing ConcurrentQueue has throws an Exception.


text:
package com.intellij.openapi.roots.ui.configuration;

import com.intellij.icons.AllIcons;
import com.intellij.ide.util.treeView.AbstractTreeBuilder;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.ex.ToolbarLabelAction;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.fileChooser.actions.NewFolderAction;
import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl;
import com.intellij.openapi.fileChooser.impl.FileTreeBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ContentFolder;
import com.intellij.openapi.roots.ui.configuration.actions.ToggleFolderStateAction;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.containers.ComparatorUtil;
import com.intellij.util.ui.tree.TreeUtil;
import consulo.disposer.Disposer;
import consulo.localize.LocalizeValue;
import consulo.roots.ContentFolderTypeProvider;
import consulo.roots.ContentFoldersSupportUtil;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.util.dataholder.Key;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Set;

/**
 * @author Eugene Zhuravlev
 *         Date: Oct 9, 2003
 *         Time: 1:19:47 PM
 */
public class ContentEntryTreeEditor {
  private final Project myProject;
  private final ModuleConfigurationState myState;
  protected final Tree myTree;
  private FileSystemTreeImpl myFileSystemTree;
  private final JPanel myTreePanel;
  private final DefaultMutableTreeNode EMPTY_TREE_ROOT = new DefaultMutableTreeNode(ProjectBundle.message("module.paths.empty.node"));
  protected final DefaultActionGroup myEditingActionsGroup;
  private ContentEntryEditor myContentEntryEditor;
  private final MyContentEntryEditorListener myContentEntryEditorListener = new MyContentEntryEditorListener();
  private final FileChooserDescriptor myDescriptor;

  public ContentEntryTreeEditor(Project project, ModuleConfigurationState state) {
    myProject = project;
    myState = state;
    myTree = new Tree();
    myTree.setRootVisible(true);
    myTree.setShowsRootHandles(true);

    myEditingActionsGroup = new DefaultActionGroup();

    TreeUtil.installActions(myTree);
    new TreeSpeedSearch(myTree);

    myTreePanel = new MyPanel(new BorderLayout());
    final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
    myTreePanel.add(scrollPane, BorderLayout.CENTER);

    myTreePanel.setVisible(false);
    myDescriptor = FileChooserDescriptorFactory.createMultipleFoldersDescriptor();
    myDescriptor.setShowFileSystemRoots(false);
  }

  protected void updateMarkActions() {
    myEditingActionsGroup.removeAll();

    myEditingActionsGroup.add(new ToolbarLabelAction() {
      @RequiredUIAccess
      @Override
      public void update(@Nonnull AnActionEvent e) {
        super.update(e);
       e.getPresentation().setTextValue(LocalizeValue.localizeTODO("Mark as:"));
      }
    });
    Set<ContentFolderTypeProvider> folders = ContentFoldersSupportUtil.getSupportedFolders(myState.getRootModel());
    ContentFolderTypeProvider[] supportedFolders = folders.toArray(new ContentFolderTypeProvider[folders.size()]);
    Arrays.sort(supportedFolders, (o1, o2) -> ComparatorUtil.compareInt(o1.getWeight(), o2.getWeight()));
    for (ContentFolderTypeProvider contentFolderTypeProvider : supportedFolders) {
      ToggleFolderStateAction action = new ToggleFolderStateAction(myTree, this, contentFolderTypeProvider);
     /* CustomShortcutSet shortcutSet = editor.getMarkRootShortcutSet();
      if (shortcutSet != null) {
        action.registerCustomShortcutSet(shortcutSet, myTree);
      }     */
      myEditingActionsGroup.add(action);
    }
  }

  protected TreeCellRenderer getContentEntryCellRenderer() {
    return new ContentEntryTreeCellRenderer(this);
  }

  /**
   * @param contentEntryEditor : null means to clear the editor
   */
  public void setContentEntryEditor(@Nullable final ContentEntryEditor contentEntryEditor) {
    if (myContentEntryEditor != null && myContentEntryEditor.equals(contentEntryEditor)) {
      return;
    }
    if (myFileSystemTree != null) {
      Disposer.dispose(myFileSystemTree);
      myFileSystemTree = null;
    }
    if (myContentEntryEditor != null) {
      myContentEntryEditor.removeContentEntryEditorListener(myContentEntryEditorListener);
      myContentEntryEditor = null;
    }
    if (contentEntryEditor == null) {
      ((DefaultTreeModel)myTree.getModel()).setRoot(EMPTY_TREE_ROOT);
      myTreePanel.setVisible(false);
      return;
    }
    myTreePanel.setVisible(true);
    myContentEntryEditor = contentEntryEditor;
    myContentEntryEditor.addContentEntryEditorListener(myContentEntryEditorListener);

    final ContentEntry entry = contentEntryEditor.getContentEntry();
    assert entry != null : contentEntryEditor;
    final VirtualFile file = entry.getFile();
    myDescriptor.setRoots(file);
    if (file == null) {
      final String path = VfsUtilCore.urlToPath(entry.getUrl());
      myDescriptor.setTitle(FileUtil.toSystemDependentName(path));
    }

    final Runnable init = () -> {
      myFileSystemTree.updateTree();
      myFileSystemTree.select(file, null);
    };

    myFileSystemTree = new FileSystemTreeImpl(myProject, myDescriptor, myTree, getContentEntryCellRenderer(), init, null) {
      @Override
      protected AbstractTreeBuilder createTreeBuilder(JTree tree,
                                                      DefaultTreeModel treeModel,
                                                      AbstractTreeStructure treeStructure,
                                                      Comparator<NodeDescriptor> comparator,
                                                      FileChooserDescriptor descriptor,
                                                      final Runnable onInitialized) {
        return new MyFileTreeBuilder(tree, treeModel, treeStructure, comparator, descriptor, onInitialized);
      }
    };
    myFileSystemTree.showHiddens(true);
    Disposer.register(myProject, myFileSystemTree);

    final NewFolderAction newFolderAction = new MyNewFolderAction();
    final DefaultActionGroup mousePopupGroup = new DefaultActionGroup();
    mousePopupGroup.add(myEditingActionsGroup);
    mousePopupGroup.addSeparator();
    mousePopupGroup.add(newFolderAction);
    myFileSystemTree.registerMouseListener(mousePopupGroup);
  }

  public ContentEntryEditor getContentEntryEditor() {
    return myContentEntryEditor;
  }

  public JComponent createComponent() {
    updateMarkActions();
    return myTreePanel;
  }

  public void select(VirtualFile file) {
    if (myFileSystemTree != null) {
      myFileSystemTree.select(file, null);
    }
  }

  public void requestFocus() {
    IdeFocusManager.getGlobalInstance().doForceFocusWhenFocusSettlesDown(myTree);
  }

  public void update() {
    updateMarkActions();
    if (myFileSystemTree != null) {
      myFileSystemTree.updateTree();
      final DefaultTreeModel model = (DefaultTreeModel)myTree.getModel();
      final int visibleRowCount = myTree.getVisibleRowCount();
      for (int row = 0; row < visibleRowCount; row++) {
        final TreePath pathForRow = myTree.getPathForRow(row);
        if (pathForRow != null) {
          final TreeNode node = (TreeNode)pathForRow.getLastPathComponent();
          if (node != null) {
            model.nodeChanged(node);
          }
        }
      }
    }
  }

  private class MyContentEntryEditorListener implements ContentEntryEditor.ContentEntryEditorListener {
    @Override
    public void folderAdded(@Nonnull ContentEntryEditor editor, ContentFolder folder) {
      update();
    }

    @Override
    public void folderRemoved(@Nonnull ContentEntryEditor editor, ContentFolder file) {
      update();
    }
  }

  private static class MyNewFolderAction extends NewFolderAction {
    private MyNewFolderAction() {
      super(ActionsBundle.message("action.FileChooser.NewFolder.text"), ActionsBundle.message("action.FileChooser.NewFolder.description"), AllIcons.Actions.NewFolder);
    }
  }

  private static class MyFileTreeBuilder extends FileTreeBuilder {
    public MyFileTreeBuilder(JTree tree,
                             DefaultTreeModel treeModel,
                             AbstractTreeStructure treeStructure,
                             Comparator<NodeDescriptor> comparator,
                             FileChooserDescriptor descriptor,
                             @Nullable Runnable onInitialized) {
      super(tree, treeModel, treeStructure, comparator, descriptor, onInitialized);
    }

    @Override
    protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) {
      return false; // need this in order to not show plus for empty directories
    }
  }

  private class MyPanel extends JPanel implements DataProvider {
    private MyPanel(final LayoutManager layout) {
      super(layout);
    }

    @Override
    @Nullable
    public Object getData(@Nonnull final Key<?> dataId) {
      if (FileSystemTree.DATA_KEY == dataId) {
        return myFileSystemTree;
      }
      return null;
    }
  }

  public DefaultActionGroup getEditingActionsGroup() {
    return myEditingActionsGroup;
  }
}

redpajama_set_name: RedPajamaGithub


text:
from signals import SignalOrderedReceivers
from util import case

sig = SignalOrderedReceivers()

class Receiver(object):

    @property
    def bucket(self):
        return self.__dict__.setdefault('_bucket', [])

    @bucket.deleter
    def bucket(self):
        del self._bucket

    def handler1(self, sender):
        self.bucket.append(1)

    def handler2(self, sender):
        self.bucket.append(2)

    def handler3(self, sender):
        self.bucket.append(3)

obj = Receiver()

sig.connect(obj.handler2)
sig.connect(obj.handler1)
sig.connect(obj.handler3)

for i in range(10):
    sig.send('sender')
    case.assertEqual(obj.bucket, [2, 1, 3])
    del obj.bucket


text:
package duration

import (
	"fmt"
	"math"
	"math/big"
	"time"
)

const (
	daysInMonth  = 30
	nanosInDay   = 24 * int64(time.Hour) // Try as I might, couldn't do this without the cast.
	nanosInMonth = daysInMonth * nanosInDay
)

// A Duration represents a length of time.
//
// A duration of "1 month" cannot be represented as a fixed number of
// nanoseconds because the length of months vary. The same is true for days
// because of leap seconds. Given a begin or end time to anchor a duration, the
// nanosecond count can be calculated, but it's useful to represent durations
// such as "1 year 3 months" without an anchor. Duration allows this.
//
// For the purposes of Compare and Encode, 1 month is considered equivalent to
// 30 days and 1 day is equivalent to 24 * 60 * 60 * 1E9 nanoseconds.
//
// TODO(dan): Until the overflow and underflow handling is fixed, this is only
// useful for durations of < 292 years.
type Duration struct {
	Months int64
	Days   int64
	Nanos  int64
}

// Compare returns an integer representing the relative length of two Durations.
// The result will be 0 if d==x, -1 if d < x, and +1 if d > x.
func (d Duration) Compare(x Duration) int {
	normD := d.normalize()
	normX := x.normalize()
	if normD.Months < normX.Months {
		return -1
	} else if normD.Months > normX.Months {
		return 1
	} else if normD.Days < normX.Days {
		return -1
	} else if normD.Days > normX.Days {
		return 1
	} else if normD.Nanos < normX.Nanos {
		return -1
	} else if normD.Nanos > normX.Nanos {
		return 1
	}
	return 0
}

// String returns a string representation of a Duration.
func (d Duration) String() string {
	return fmt.Sprintf("%dm%dd%s", d.Months, d.Days, time.Duration(d.Nanos)*time.Nanosecond)
}

// Encode returns three integers such that the original Duration is recoverable
// (using Decode) and the first int will approximately sort a collection of
// encoded Durations.
func (d Duration) Encode() (sortNanos int64, months int64, days int64, err error) {
	totalNanos := d.Months*nanosInMonth + d.Days*nanosInDay + d.Nanos
	// TODO(dan): Handle overflow, then document that EncodeBigInt can be used
	// in overflow cases.
	return totalNanos, d.Months, d.Days, nil
}

// EncodeBigInt is the same as Encode, except that it always returns
// successfully and is slower.
func (d Duration) EncodeBigInt() (sortNanos *big.Int, months int64, days int64) {
	bigMonths := big.NewInt(d.Months)
	bigMonths.Mul(bigMonths, big.NewInt(nanosInMonth))
	bigDays := big.NewInt(d.Days)
	bigDays.Mul(bigDays, big.NewInt(nanosInDay))
	totalNanos := big.NewInt(d.Nanos)
	totalNanos.Add(totalNanos, bigMonths).Add(totalNanos, bigDays)
	return totalNanos, d.Months, d.Days
}

// Decode reverses the three integers returned from Encode and produces an equal
// Duration to the original.
func Decode(sortNanos int64, months int64, days int64) (Duration, error) {
	nanos := sortNanos - months*nanosInMonth - days*nanosInDay
	// TODO(dan): Handle underflow, then document that DecodeBigInt can be used
	// in underflow cases.
	return Duration{Months: months, Days: days, Nanos: nanos}, nil
}

// TODO(dan): Write DecodeBigInt.

// Add returns the time t+d.
func Add(t time.Time, d Duration) time.Time {
	// TODO(dan): Overflow handling.
	return t.AddDate(0, int(d.Months), int(d.Days)).Add(time.Duration(d.Nanos) * time.Nanosecond)
}

// Add returns a Duration representing a time length of d+x.
func (d Duration) Add(x Duration) Duration {
	return Duration{d.Months + x.Months, d.Days + x.Days, d.Nanos + x.Nanos}
}

// Sub returns a Duration representing a time length of d-x.
func (d Duration) Sub(x Duration) Duration {
	return Duration{d.Months - x.Months, d.Days - x.Days, d.Nanos - x.Nanos}
}

// Mul returns a Duration representing a time length of d*x.
func (d Duration) Mul(x int64) Duration {
	return Duration{d.Months * x, d.Days * x, d.Nanos * x}
}

// Div returns a Duration representing a time length of d/x.
func (d Duration) Div(x int64) Duration {
	return Duration{d.Months / x, d.Days / x, d.Nanos / x}
}

// normalized returns a new Duration transformed using the equivalence rules.
// Each quantity of days greater than the threshold is moved into months,
// likewise for nanos. Integer overflow is avoided by partial transformation.
func (d Duration) normalize() Duration {
	if d.Days > 0 {
		d = d.shiftPosDaysToMonths()
	} else if d.Days < 0 {
		d = d.shiftNegDaysToMonths()
	}
	// After shifting days into months, there are two cases:
	// - Months did not hit MaxInt64 or MinInt64, in which case Days is now in
	//   (-30,30). We shift nanos, then days one more time in case the nano shift
	//   made a full month.
	// - Months did hit MaxInt64 or MinInt64, in which case there can be no more
	//   months. We only need to shift nanos.
	if d.Nanos > 0 {
		d = d.shiftPosNanosToDays()
		d = d.shiftPosDaysToMonths()
	} else if d.Nanos < 0 {
		d = d.shiftNegNanosToDays()
		d = d.shiftNegDaysToMonths()
	}
	return d
}

func (d Duration) shiftPosDaysToMonths() Duration {
	var maxMonths int64 = math.MaxInt64
	if d.Months > 0 {
		// If d.Months < 0, then this would overflow, but because of the exchange
		// rate, we can never transfer more than math.MaxInt64 anyway.
		maxMonths = math.MaxInt64 - d.Months
	}
	monthsFromDays := int64Min(d.Days/daysInMonth, maxMonths)
	d.Months += monthsFromDays
	d.Days -= monthsFromDays * daysInMonth
	return d
}

func (d Duration) shiftPosNanosToDays() Duration {
	var maxDays int64 = math.MaxInt64
	if d.Days > 0 {
		// If d.Days < 0, then this would overflow, but because of the exchange
		// rate, we can never transfer more than math.MaxInt64 anyway.
		maxDays = math.MaxInt64 - d.Days
	}
	daysFromNanos := int64Min(d.Nanos/nanosInDay, maxDays)
	d.Days += daysFromNanos
	d.Nanos -= daysFromNanos * nanosInDay
	return d
}

func (d Duration) shiftNegDaysToMonths() Duration {
	var minMonths int64 = math.MinInt64
	if d.Months < 0 {
		// If d.Months > 0, then this would overflow, but because of the exchange
		// rate, we can never transfer more than math.MaxInt64 anyway.
		minMonths = math.MinInt64 - d.Months
	}
	monthsFromDays := int64Max(d.Days/daysInMonth, minMonths)
	d.Months += monthsFromDays
	d.Days -= monthsFromDays * daysInMonth
	return d
}

func (d Duration) shiftNegNanosToDays() Duration {
	var minDays int64 = math.MinInt64
	if d.Days < 0 {
		// If d.Days > 0, then this would overflow, but because of the exchange
		// rate, we can never transfer more than math.MaxInt64 anyway.
		minDays = math.MinInt64 - d.Days
	}
	daysFromNanos := int64Max(d.Nanos/nanosInDay, minDays)
	d.Days += daysFromNanos
	d.Nanos -= daysFromNanos * nanosInDay
	return d
}

func int64Max(a int64, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func int64Min(a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}


text:
using Auth0.AuthenticationApi.Models;
using Auth0.ManagementApi;
using Auth0.ManagementApi.Models;
using Auth0.Tests.Shared;
using FluentAssertions;
using System;
using System.Threading.Tasks;
using Auth0.AuthenticationApi.IntegrationTests.Testing;
using Auth0.IntegrationTests.Shared.CleanUp;
using Xunit;

namespace Auth0.AuthenticationApi.IntegrationTests
{
    public class AccessTokenTests : ManagementTestBase, IAsyncLifetime
    {
        private AuthenticationApiClient _authenticationApiClient;
        private Connection _connection;
        private User _newUser;
        private const string Password = "4cX8awB3T%@Aw-R:=h@ae@k?";

        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            ApiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"), new HttpClientManagementConnection(options: new HttpClientManagementConnectionOptions { NumberOfHttpRetries = 9 }));

            // We will need a connection to add the users to...
            _connection = await ApiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name = $"{TestingConstants.ConnectionPrefix}-{MakeRandomName()}",
                Strategy = "auth0",
                EnabledClients = new[] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") }
            });

            // Add a new user
            var newUserRequest = new UserCreateRequest
            {
                Connection = _connection.Name,
                Email = $"{Guid.NewGuid():N}{TestingConstants.UserEmailDomain}",
                EmailVerified = true,
                Password = Password
            };

            _newUser = await ApiClient.Users.CreateAsync(newUserRequest);

            _authenticationApiClient = new TestAuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));
        }

        public override async Task DisposeAsync()
        {
            _authenticationApiClient.Dispose();

            await CleanupAndDisposeAsync(CleanUpType.Connections);
            await CleanupAndDisposeAsync(CleanUpType.Users);
        }

        //[Test, Explicit]
        //public async Task Can_get_delegation_token()
        //{
        //    var authenticationApiClient = new TestAuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

        //    // First get the access token
        //    var token = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
        //    {
        //        ClientId = GetVariable("AUTH0_CLIENT_ID"),
        //        ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
        //        Realm = connection.Name,
        //        Username = newUser.Email,
        //        Password = "password",
        //        Scope = "openid"
        //    });

        //    // Then request the delegation token
        //    var delegationToken = await authenticationApiClient.GetDelegationTokenAsync(new IdTokenDelegationRequest(
        //        GetVariable("AUTH0_CLIENT_ID"),
        //        GetVariable("AUTH0_CLIENT_ID"),
        //        token.IdToken)
        //    {
        //        Scope = "openid",
        //        GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer",
        //        ApiType = "app"
        //    });

        //    delegationToken.Should().NotBeNull();
        //    delegationToken.IdToken.Should().NotBeNull();
        //}

        [Fact]
        public async Task Can_obtain_user_info()
        {
            // First get the access token
            var token = await _authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm = _connection.Name,
                Username = _newUser.Email,
                Password = Password,
                Scope = "openid profile"
            });

            // Get the user info
            var user = await _authenticationApiClient.GetUserInfoAsync(token.AccessToken);
            user.Should().NotBeNull();
            user.UserId.Should().NotBeNull();
        }

        [Fact(Skip = "Run manually")]
        public async Task Can_exchange_authorization_code_for_access_token()
        {
            var authenticationApiClient = new TestAuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Exchange the authorization code
            var token = await authenticationApiClient.GetTokenAsync(new AuthorizationCodeTokenRequest
            {
                ClientId = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                RedirectUri = "http://www.blah.com/test",
                Code= "AaBhdAOl4OKvjX2I"
            });

            // Assert
            token.Should().NotBeNull();
        }

    }
}


text:
module TaggableCache
  module CacheStoreExtension
    extend ActiveSupport::Concern

    def taggable
      @taggable ||= TaggableCache.new_store
    end

    # Add tag to cache element
    def add_tags(key, *params)
      taggable.add(key, *params)
    end

    # Expire cache elements by list of keys
    def expire_tags(*params)
      taggable.get(*params).each do |m|
        self.delete(m)
      end
    end

    # Expire all cache entries availible for taggable
    # WARNING: this is expensive function and may take VERY long on big data
    def expire_all
      #Load all the models
      Dir.glob(Rails.root + '/app/models/*.rb').each {|file| require file}

      ActiveRecord::Base.subclasses.each do |cls|
        expire_tags cls

        pk_name = cls.primary_key

        return if cls.unscoped.first.nil? #There is no sence in continuing, if model is empty

        last_id = cls.order(pk_name).last.try(pk_name.to_sym)

        #hardcoded value for first record
        first_id = 1

        (first_id..last_id).each do |id|
          expire_tags({:cls => cls, :id => id})
        end
      end
    end

    included do |base|
      base.class_eval do
        # Returns taggable store instance
        def write_with_taggable(name, value, options = {})
          begin
            k = namespaced_key(name, options)
          rescue
            k = name
          end

          add_tags(k, *options[:depends_on]) if options.has_key?(:depends_on)

          write_without_taggable(name, value, options)
        end

        alias_method_chain :write, :taggable
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.models.common — Colour 0.3.4 documentation</title>

    <link rel="stylesheet" href="../../../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.4 documentation" href="../../../index.html" />
    <link rel="up" title="colour.models" href="../models.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

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

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

<form class="navbar-form navbar-right" action="../../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source code for colour.models.common

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Common Colour Models Utilities
==============================

Defines various colour models common utilities.

See Also
--------
`RGB Colourspaces IPython Notebook
<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_  # noqa
"""

from __future__ import division, unicode_literals

from colour.models import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_RGB

__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'

__all__ = ['XYZ_to_sRGB', 'sRGB_to_XYZ']

[docs]def XYZ_to_sRGB(XYZ,
                illuminant=RGB_COLOURSPACES.get('sRGB').whitepoint,
                chromatic_adaptation_transform='CAT02',
                transfer_function=True):
    """
    Converts from *CIE XYZ* colourspace to *sRGB* colourspace.

    Parameters
    ----------
    XYZ : array_like, (3,)
        *CIE XYZ* colourspace matrix.
    illuminant : array_like, optional
        Source illuminant chromaticity coordinates.
    chromatic_adaptation_transform : unicode, optional
        {'CAT02', 'XYZ Scaling', 'Von Kries', 'Bradford', 'Sharp', 'Fairchild,
        'CMCCAT97', 'CMCCAT2000', 'CAT02_BRILL_CAT', 'Bianco', 'Bianco PC'},
        *Chromatic adaptation* transform.
    transfer_function : bool, optional
        Apply *sRGB* *transfer function*.

    Returns
    -------
    ndarray, (3,)
        *sRGB* colour matrix.

    Notes
    -----
    -   Input *CIE XYZ* colourspace matrix is in domain [0, 1].

    Examples
    --------
    >>> import numpy as np
    >>> XYZ = np.array([0.07049534, 0.1008, 0.09558313])
    >>> XYZ_to_sRGB(XYZ)  # doctest: +ELLIPSIS
    array([ 0.1750135...,  0.3881879...,  0.3216195...])
    """

    sRGB = RGB_COLOURSPACES.get('sRGB')
    return XYZ_to_RGB(XYZ,
                      illuminant,
                      sRGB.whitepoint,
                      sRGB.XYZ_to_RGB_matrix,
                      chromatic_adaptation_transform,
                      sRGB.transfer_function if transfer_function else None)

[docs]def sRGB_to_XYZ(RGB,
                illuminant=RGB_COLOURSPACES.get('sRGB').whitepoint,
                chromatic_adaptation_method='CAT02',
                inverse_transfer_function=True):
    """
    Converts from *sRGB* colourspace to *CIE XYZ* colourspace.

    Parameters
    ----------
    RGB : array_like, (3,)
        *sRGB* colourspace matrix.
    illuminant : array_like, optional
        Source illuminant chromaticity coordinates.
    chromatic_adaptation_method : unicode, optional
        {'CAT02', 'XYZ Scaling', 'Von Kries', 'Bradford', 'Sharp', 'Fairchild,
        'CMCCAT97', 'CMCCAT2000', 'Bianco', 'Bianco PC'},
        *Chromatic adaptation* method.
    inverse_transfer_function : bool, optional
        Apply *sRGB* *inverse transfer function*.

    Returns
    -------
    ndarray, (3,)
        *CIE XYZ* colour matrix.

    Notes
    -----
    -   Input *RGB* colourspace matrix is in domain [0, 1].

    Examples
    --------
    >>> import numpy as np
    >>> RGB = np.array([0.17501358, 0.38818795, 0.32161955])
    >>> sRGB_to_XYZ(RGB)  # doctest: +ELLIPSIS
    array([ 0.0704953...,  0.1008    ,  0.0955831...])
    """

    sRGB = RGB_COLOURSPACES.get('sRGB')
    return RGB_to_XYZ(RGB,
                      sRGB.whitepoint,
                      illuminant,
                      sRGB.RGB_to_XYZ_matrix,
                      chromatic_adaptation_method,
                      (sRGB.inverse_transfer_function
                       if inverse_transfer_function else None))

      Back to top

        © Copyright 2013 - 2015, Colour Developers.

      Created using Sphinx 1.2.2.


text:
class BrainWorkshop < Cask
  version '4.8.4'
  sha256 'b795220306862f55e79e3de9c8cf8b4e8667e7bb1b0e3f59604b4d5f29f3f623'

  url "https://downloads.sourceforge.net/project/brainworkshop/brainworkshop/Brain%20Workshop%204.8/brainworkshop-#{version}-MacOSX.zip"
  homepage 'http://brainworkshop.sourceforge.net/'

  app 'Brain Workshop.app'
end


text:
package com;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public interface MouseAdapterX extends MouseListener {
    default void mouseClicked(MouseEvent e) {}
    default void mousePressed(MouseEvent e) {}
    default void mouseReleased(MouseEvent e) {}
    default void mouseEntered(MouseEvent e) {}
    default void mouseExited(MouseEvent e) {}
}


text:
/********************************************************/
/* File: prepro.c                                       */
/* The preprocessor implementation for the WSC compiler */
/********************************************************/

#include "globals.h"
#include "scanner.h"
#include "parser.h"
#include "lib.h"

char *strrep( char *src, char *oldStr, char *newStr )
{
	tokenType token;

	while( (token = getToken()) != TK_EOF && token != TK_ERROR )
	{
		if( token == TK_ID || (token >= TK_IF && token <= TK_FLOAT) )
		{
			if( strcmp( tokenString, oldStr ) == 0 )
			{
				int pos = getPos();
				int diff = strlen( newStr ) - strlen( oldStr );
				int len = strlen( src );

				if( diff > 0 )
					src = (char *)realloc( src, len + diff + 1 );

				memmove( src + pos + diff, src + pos, len - pos );
				strncpy( src + pos - strlen( oldStr ), newStr, strlen( newStr ) );

				if( diff < 0 )
					src = (char *)realloc( src, len + diff + 1 );

				src[len + diff] = '\0';
				setScanner( src, lineno, pos + diff );
			}
		}
	}

	return src;
}

char *preprocessor( char *src, byteCodeInfo *info )
{
	tokenType token;
	int lineBegin, lineEnd; // to delete the preprocessor command

	setScanner( src, 1, 0 );

	while( (token = getToken()) != TK_EOF && token != TK_ERROR )
	{
		if( token == TK_POUND )
		{
			lineBegin = getPos() - 1;

			token = getToken();

			if( token == TK_ID )
			{
				if( strcmp( tokenString, "define" ) == 0 )
				{
					char s1[128], s2[128];
					char *pSrc, *pTar;

					token = getToken();
					if( token != TK_ID && (token < TK_IF || token > TK_FLOAT ) )
						throwError( lineno, "#define syntax :'%s' is no Identifier", tokenToStr[token] );

					strcpy( s1, tokenString );
					pSrc = src + getPos() + 1;
					pTar = s2;

					while( *pSrc && *pSrc != '\n'  )
					{
						*pTar = *pSrc;
						++pTar; ++pSrc;
					}
					*pTar = '\0';

					strcpy( src + lineBegin, pSrc ); // delete this line

					setScanner( src, lineno, lineBegin );
					src = strrep( src, s1, s2 );

					setScanner( src, lineno, lineBegin );
				}
				else if( strcmp( tokenString, "include" ) == 0 )
				{
					char *filename;

					if( (token = getToken()) != TK_LT )				// <
						throwError( lineno, "expect '<', buf found '%s'", tokenToStr[token] );
					if( (token = getToken()) != TK_ID )				// stdio.h
						throwError( lineno, "Expect a file name, buf found '%s'", tokenToStr[token] );
					else
						filename = copyString( tokenString );
					if( (token = getToken()) != TK_GT )				// >
						throwError( lineno, "Expect '>', buf found '%s'", tokenToStr[token] );

					lineEnd = getPos();
					strcpy( src + lineBegin, src + lineEnd ); // delete this line

					setScanner( src, lineno, lineBegin );
					loadLib( filename, &src, lineBegin );

					setScanner( src, lineno, lineBegin );
				}
				else if( strcmp( tokenString, "progma" ) == 0 )
				{
					token = getToken();

					if( strcmp( tokenString, "FORCE_BREAK" ) == 0 )
						info->forceBreak = TRUE;
					else if( strcmp( tokenString, "RAM_SIZE" ) == 0 )
					{
						if( (token = getToken()) == TK_NUM )
							sscanf( tokenString, "%d", &info->RAMSize );
						else if( token == TK_NUM_HEX )
							sscanf( tokenString, "%x", &info->RAMSize );
						else
							throwError( lineno, "Expect a number, buf found '%s'",
								tokenToStr[token] );
					}
					else if( strcmp( tokenString, "BIG_FONT" ) == 0 )
						info->bigFont = TRUE;
					else
						throwError( lineno, "Invalid progma command '%s'",
							tokenToStr[token] );

					lineEnd = getPos();
					strcpy( src + lineBegin, src + lineEnd ); // delete this line
					setScanner( src, lineno, lineBegin );
				}
				else
					throwError( lineno, "Invalid preprocessor command '%s'",
						tokenToStr[token] );
			}
			else
				throwError( lineno, "Invalid preprocessor command '%s'",
					tokenToStr[token] );
		}
	}

	return src;
}


text:
layout:     post
title:      "Jaiganesh Balasubramanian, Aniruddha Gokhale, Abhishek Dubey, Friedhelm Wolf, Chenyang Lu, Chris Gill, and Douglas Schmidt. Middleware for resource-aware deployment and configuration of fault-tolerant real-time systems. In RTAS 2010: Proceedings of the 2010 16th IEEE Real-Time and Embedded Technology and Applications Symposium, 69–78. Washington, DC, USA, 2010. IEEE Computer Society."
date:       2010-01-01 00:00:01
year:       2010
pub_type:       conference
link:       https://www.dre.vanderbilt.edu/~schmidt/PDF/RTAS-2010.pdf
doi:       DOI  http://dx.doi.org/10.1109/RTAS.2010.30
---


text:
module Slide {
    /**
      * Config
      */
    var moduleName = 'techRadar.infoslide';

    /**
      * Module
      */
    export var myModule;
    try {
        myModule = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        myModule = angular.module(moduleName, []);
    }

    /**
      * Directive to display a slide of information.
      */
    myModule.directive('infoslide', [
        '$window', '$compile',
        function ($window, $compile)  : ng.IDirective {
            return {
                terminal  : false,  // do not compile any other internal directives
                restrict  : 'E',    // E = elements, other options are A=attributes and C=classes
                scope     : {},     // isolated scope, separated from parent. Is however empty, as this directive is self contained by using the messagebus.
                //template  : slide.html,   // I use gulp automatian to compile the FeatureProperties.tpl.html to a simple TS file, FeatureProperties.tpl.ts, which contains the html as string. The advantage is that you can use HTML intellisence in the html file.
                templateUrl: 'directives/slide/slide.tpl.html',
                link: (scope: any, element, attrs) => {
                    // Deal with resizing the element list
                    scope.onResizeFunction = () => {
                        var filterHeight = 50;
                        var paginationCtrlHeight = 100;
                        var itemHeight = 60;
                        //scope.windowHeight          = $window.innerHeight;
                        //scope.windowWidth           = $window.innerWidth;
                        scope.numberOfItems = Math.floor(($window.innerHeight - filterHeight - paginationCtrlHeight) / itemHeight);
                    };

                    // Call to the function when the page is first loaded
                    scope.onResizeFunction();

                    angular.element($window).bind('resize', () => {
                        scope.onResizeFunction();
                        scope.$apply();
                    });
                },
                replace   : true,    // Remove the directive from the DOM
                transclude: true,    // Add elements and attributes to the template
                controller: SlideCtrl
            }
        }
    ]);
}


text:
local dpdk		= require "dpdk"
local memory	= require "memory"
local device	= require "device"
local ts		= require "timestamping"
local dpdkc		= require "dpdkc"
local filter	= require "filter"
local ffi		= require "ffi"

local incAndWrap = incAndWrap

-- set addresses here
local srcmac = "00:42:00:00:00:01"
local dstmac = "00:42:00:00:00:02"
local dstip = 0x0A000001
local srcip = 0x0A000002

function master(...)
	local txPort, rxPort, rate, flows, size = tonumberall(...)
	if not txPort or not rxPort then
		errorf("usage: txPort rxPort [rate [flows [size]]]")
	end
	flows = flows or 4
	rate = rate or 2000
	size = (size or 128) - 4 -- 4 bytes for CRC will be added by NIC
	local rxMempool = memory.createMemPool()
	if txPort == rxPort then
		txDev = device.config(txPort, rxMempool, 2, 2)
		rxDev = txDev
		txDev:wait()
	else
		txDev = device.config(txPort, rxMempool, 1, 2)
		rxDev = device.config(rxPort, rxMempool, 2, 1)
		device.waitForLinks()
	end
	txDev:getTxQueue(1):setRate(rate)
	dpdk.launchLua("timerSlave", txPort, rxPort, 0, 1, size, flows)
	dpdk.launchLua("loadSlave", txPort, 1, size, flows)
	dpdk.launchLua("counterSlave", rxPort, size)
	dpdk.waitForSlaves()
end

function loadSlave(port, queue, size, numFlows)
	local queue = device.get(port):getTxQueue(queue)
	local mempool = memory.createMemPool(function(buf)
		-- TODO: port this to new PTP/timestamping functions, ffi.cast in a userscript is not the point
		ts.fillPacket(buf, 1234, size)
		local data = ffi.cast("uint8_t*", buf.pkt.data)
		data[43] = 0x00 -- PTP version, set to 0 to disable timestamping for load packets
		local pkt = buf:getUdpPacket()
		pkt.eth.src:setString(srcmac)
		pkt.eth.dst:setString(dstmac)
		pkt.ip.dst:set(dstip)
	end)
	local lastPrint = dpdk.getTime()
	local totalSent = 0
	local lastTotal = 0
	local lastSent = 0
	local bufs = mempool:bufArray(128)
	local baseIP = srcip
	local counter = 0
	while dpdk.running() do
		bufs:alloc(size)
		for i, buf in ipairs(bufs) do
			local pkt = buf:getUdpPacket()
			pkt.ip.src:set(baseIP + counter)
			counter = incAndWrap(counter, numFlows)
		end
		-- UDP checksums are optional, so using just IPv4 checksums would be sufficient here
		bufs:offloadUdpChecksums()
		totalSent = totalSent + queue:send(bufs)
		local time = dpdk.getTime()
		if time - lastPrint > 1 then
			local mpps = (totalSent - lastTotal) / (time - lastPrint) / 10^6
			printf("Sent %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate", totalSent, mpps, mpps * (size + 4) * 8, mpps * (size + 24) * 8)
			lastTotal = totalSent
			lastPrint = time
		end
	end
	printf("Sent %d packets", totalSent)
end

function counterSlave(port)
	local dev = device.get(port)
	local total = 0
	while dpdk.running() do
		local time = dpdk.getTime()
		dpdk.sleepMillis(1000)
		local elapsed = dpdk.getTime() - time
		local pkts = dev:getRxStats(port)
		total = total + pkts
		printf("Received %d packets, current rate %.2f Mpps", total, pkts / elapsed / 10^6)
	end
	printf("Received %d packets", total)
end

function timerSlave(txPort, rxPort, txQueue, rxQueue, size, numFlows)
	local txDev = device.get(txPort)
	local rxDev = device.get(rxPort)
	local txQueue = txDev:getTxQueue(txQueue)
	local rxQueue = rxDev:getRxQueue(rxQueue)
	local mem = memory.createMemPool()
	local bufs = mem:bufArray(1)
	local rxBufs = mem:bufArray(128)
	txQueue:enableTimestamps()
	rxQueue:enableTimestamps(1234)
	rxDev:filterTimestamps(rxQueue)
	local hist = {}
	-- wait one second, otherwise we might start timestamping before the load is applied
	dpdk.sleepMillis(1000)
	local counter = 0
	local baseIP = dstip
	while dpdk.running() do
		bufs:alloc(size + 4)
		local pkt = bufs[1]:getUdpPacket()
		ts.fillPacket(bufs[1], 1234, size)
		pkt.eth.src:setString(srcmac)
		pkt.eth.dst:setString(dstmac)
		pkt.ip.src:set(baseIP + counter)
		pkt.ip.dst:set(dstip)
		counter = (counter + 1) % numFlows
		bufs:offloadUdpChecksums()
		-- sync clocks and send
		ts.syncClocks(txDev, rxDev)
		txQueue:send(bufs)
		-- increment the wait time when using large packets or slower links
		local tx = txQueue:getTimestamp(100)
		if tx then
			dpdk.sleepMicros(500) -- minimum latency to limit the packet rate
			-- sent was successful, try to get the packet back (max. 10 ms wait time before we assume the packet is lost)
			local rx = rxQueue:tryRecv(rxBufs, 10000)
			if rx > 0 then
				local numPkts = 0
				for i = 1, rx do
					if bit.bor(rxBufs[i].ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then
						numPkts = numPkts + 1
					end
				end
				local delay = (rxQueue:getTimestamp() - tx) * 6.4
				if numPkts == 1 then
					if delay > 0 and delay < 100000000 then
						hist[delay] = (hist[delay] or 0) + 1
					end
				end -- else: got more than one packet, so we got a problem
				-- TODO: use sequence numbers in the packets to avoid bugs here
				rxBufs:freeAll()
			end
		end
	end
	local sortedHist = {}
	for k, v in pairs(hist) do
		table.insert(sortedHist,  { k = k, v = v })
	end
	local sum = 0
	local samples = 0
	table.sort(sortedHist, function(e1, e2) return e1.k < e2.k end)
	print("Histogram:")
	for _, v in ipairs(sortedHist) do
		sum = sum + v.k * v.v
		samples = samples + v.v
		print(v.k, v.v)
	end
	print()
	print("Average: " .. (sum / samples) .. " ns, " .. samples .. " samples")
	print("----------------------------------------------")
end


text:
(function(Ventus) {
	document.addEventListener('DOMContentLoaded', function() {
		var wm = new Ventus.WindowManager();

		// Terminal App.
		var terminalWin = wm.createWindow.fromQuery('.terminal-app', {
			title: 'Terminal',
			classname: 'terminal-window',
			width: 600,
			height: 300,
			x: 50,
			y: 60
		});

		terminalWin.signals.on('click', function(win){
			terminal.display.focus();
		});

		var terminal = new Terminus('.terminal-app', {
			welcome: '

Terminus.js
 ' +
				Terminus.version +
				'
Copyright 2012-2013 Ramón Lamana.
' +
				'Press < tab > to see a list of available commands.'
		});
		terminal.shell.include([TestCommands, ShapeCommands]);

		terminal.display.events.on('prompt', function() {
			terminalWin.$content.el.scrollTo({
        top: terminalWin.view.find('.terminusjs').height,
        behavior: 'smooth'
      });
		});

    // Todo App.
		var todoWin = wm.createWindow.fromQuery('.todo-app', {
			title: 'Todo',
			width: 330,
			height: 400,
			x: 670,
			y: 60
		});

		var playerWin = wm.createWindow.fromQuery('.player-app', {
			title: 'Video Player',
			classname: 'player-window',
			width: 635,
			height: 300,
			x: 490,
			y: 320,
			resizable: false,
			opacity: 1 // To fix problems with chrome video on Linux
		});

    // About App.
		var aboutWin = wm.createWindow.fromQuery('.about-app', {
			title: 'About Ventus',
			width: 250,
			height: 280,
			x: 140,
			y: 380
		});

		// Hide loader when loaded.
		var loader = document.querySelector("#loading-screen");

		// For look & feel reasons.
		function openWithDelay(win, delay) {
			setTimeout(function(){win.open();}, delay);
		}

		function init() {
			loader.classList.add('hide');
			loader.addEventListener('animationend', function() {
				loader.style.display = 'none';

				// Open windows
				openWithDelay(terminalWin, 0);
				openWithDelay(todoWin, 200);
				openWithDelay(aboutWin, 400);
				openWithDelay(playerWin, 600);
			});
		}

		setTimeout(init, 3000);

		// Exposé test button.
		document.querySelector(".expose-button").addEventListener('click', function() {
			setTimeout(function() { wm.mode = 'expose' }, 100);
		}, false);
	});
})(Ventus);


text:
from django.core.management.base import BaseCommand, CommandError
from empous.models import EmpousUser

class Command(BaseCommand):
    args = ''
    help = 'This command updates the computed stats for each user. This includes the game list, wins, losses, and draws. This will NOT perform push notifications.'

    def handle(self, *args, **options):
		users = EmpousUser.objects.all()
		for user in users:
			user.game_updated(do_push=False);


text:
<?php
use utilities\Util;

class AdminUsuario extends Controller {

    private $usuariosRepo;

    function __construct()
    {
        $this->usuariosRepo = new UsuarioRepository();
        if(!Util::byPass("usuarios")){
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/news");
        }
    }

    public function showUsers()
    {

        if( isset( $_SESSION['admin'] ) ){
            $js = '
                    <!-- Libreria jquery-bootpag -->
                    <script src="/admin/js/vendors/bootstrap/jquery.bootpag.min.js"></script>
                    <!-- Libreria purl -->
                    <script src="/admin/js/vendors/purl/purl.min.js"></script>
                    <!-- Paginador con js -->
                    <script src="/assets/js/panel.paginador.js"></script>
                    <!-- Data Tables -->
                    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
            ';

            $css = '

                    <!-- panel_paginator CSS -->
                    <link href="/admin/css/panel.main.css" rel="stylesheet">
                    <!-- data tables bootstrap CSS -->
                    <link href="/admin/css/dataTables.bootstrap.css" rel="stylesheet">
                    <!-- Data Tables -->
                    <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
            ';

            $limit = isset( $_GET['numpp'] ) ? $_GET['numpp'] : 10;
            $page = isset( $_GET['page'] ) ? ( $_GET['page'] * $limit ) - $limit : 0;

            $getUsers = $this->usuariosRepo->showAllUsers();

            if( $getUsers->exito ){
                $users = $getUsers->rows;
                $count = $getUsers->count;
            }

            $this->header_admin('Usuarios - ', $css);
            require $this->adminviews . 'showUsersView.php';
            $this->footer_admin( $js );

        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }

    public function userDetail( $id )
    {
        if( isset( $_SESSION['admin'] ) ){

            $user = $this->usuariosRepo->get( $id );
            $tipoUsuarios = $this->usuariosRepo->getUsersTypes();

            $this->header_admin('Detalle de ' . $user['nombre'] . ' ' . $user['apellidos'] . ' - ');
            require $this->adminviews . 'userDetailView.php';
            $this->footer_admin( );

        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }

    public function editUser( $id )
    {
        if( isset( $_SESSION['admin'] ) ){

            $user = $this->usuariosRepo->get( $id );
            //$_POST['password'] = ( $_POST['password'] != '' ) ? md5( $_POST['password'] ) : $user['password'];
            $_POST['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);

            $_POST['activo'] = isset( $_POST['activo'] ) ? 1 : 0;
            $_POST['id'] = $id;

            $update = $this->usuariosRepo->edit( $_POST );

            $_SESSION['alerts']['usuario'] = $update;
            header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }

    public function createUser()
    {
        if( isset( $_SESSION['admin'] ) ){

            $tipoUsuarios = $this->usuariosRepo->getUsersTypes();

            $this->header_admin('Crear usuario - ');
            require $this->adminviews . 'createUserView.php';
            $this->footer_admin( );

        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }

    public function createUserAction()
    {
        if( isset( $_SESSION['admin'] ) ){

            $rules = [
                        'nombre'    => 'required',
                        'apellidos' => 'required',
                        'tel_casa'  => 'required',
                        'username'  => 'required',
                        'password'  => 'required',
                        'tipo_usuario' => 'required',
                     ];
            $_POST['activo'] = TRUE;
            //$_POST['password'] = md5( $_POST['password'] );
            $_POST['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);

            $user = $this->usuariosRepo->create( $_POST );

            $_SESSION['alerts']['usuarios'] = $user;
            header( 'Location: /panel/users' );

        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }

    /*joz*/
    public function deleteUser( $id )
    {
        if( isset( $_SESSION['admin'] ) ){
            $deleteUser = $this->usuariosRepo->deleteUser( $id );
            if ($deleteUser->exito) {
                $response->success = true;
                $response->message = "Usuario eliminado correctamente.";
            }
            else {
                $response->success = false;
                $response->error = json_encode($deleteUser);
                $response->message = "No se pudo eliminar al usuario, intentalo más tarde.";
            }
            header('Content-type: text/json');
            echo json_encode($response);
        }else{
            header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login");
        }
    }
    /*/joz*/

    private function validateForm( $data, $rules )
    {
        // Pendiente por crear
    }

    // TODO: @AdminUsuario Falta crear un nuevo usuario.
}


text:
package aes

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"github.com/goyy/crypto/v0/md5"
)

// Encrypt encrypts the first block in src into dst.
// Dst and src may point at the same memory.
func Encrypt(src, key []byte) (dst []byte, err error) {
	keytext := key
	keylen := len(key)
	if keylen != 16 || keylen != 24 || keylen != 32 {
		keytext, err = md5.Digest(key)
		if err != nil {
			return
		}
	}
	var block cipher.Block
	block, err = aes.NewCipher(keytext)
	if err != nil {
		return
	}
	dst = make([]byte, len(src))
	iv := keytext[:aes.BlockSize] // aes.BlockSize = 16
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(dst, src)
	return
}

// Decrypt decrypts the first block in src into dst.
// Dst and src may point at the same memory.
func Decrypt(src, key []byte) (dst []byte, err error) {
	keytext := key
	keylen := len(key)
	if keylen != 16 || keylen != 24 || keylen != 32 {
		keytext, err = md5.Digest(key)
		if err != nil {
			return
		}
	}
	var block cipher.Block
	block, err = aes.NewCipher(keytext)
	if err != nil {
		return
	}
	dst = make([]byte, len(src))
	iv := keytext[:aes.BlockSize] // aes.BlockSize = 16
	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(dst, src)
	return
}

// EncryptHex encrypts the first block in src into dst.
func EncryptHex(src, key string) (dst string, err error) {
	var ciphertext []byte
	ciphertext, err = Encrypt([]byte(src), []byte(key))
	if err != nil {
		return
	}
	dst = hex.EncodeToString(ciphertext)
	return
}

// DecryptHex decrypts the first block in src into dst.
func DecryptHex(src, key string) (dst string, err error) {
	var out, plaintext []byte
	plaintext, err = hex.DecodeString(src)
	if err != nil {
		return
	}
	out, err = Decrypt(plaintext, []byte(key))
	if err != nil {
		return
	}
	dst = string(out)
	return
}


text:
local v2 = require 'dokidoki.v2'

assert(player, 'missing player argument')
assert(turn_speed, 'missing turn_speed argument')
assert(accel, 'missing accel argument')
assert(hit_points, 'missing hit_points argument')

local max_hit_points = hit_points
self.sprite.color = {1.0, 1.0, 1.0}

if sprites_table then
  self.sprite.image = assert(game.resources[sprites_table][player])
end

velocity = v2(0, 0)

-- 1 for left, -1 for right
function turn(direction, amount)
  amount = amount or 1
  self.transform.facing =
    v2.norm(v2.rotate(self.transform.facing, turn_speed * direction * amount))
end

function thrust(amount)
  amount = amount or 1
  velocity = velocity + self.transform.facing * accel * amount
end

local function random_point_on_ship()
  -- assumes the ship is a rectangle
  local a = self.collision.poly.vertices[1]
  local ab = self.collision.poly.vertices[2] - a
  local ac = self.collision.poly.vertices[4] - a
  return self.transform.pos +
         v2.rotate_to(self.transform.facing,
                      a + ab * math.random() + ac * math.random())
end

function update()
  velocity = velocity * 0.97
  self.transform.pos = self.transform.pos + velocity
  if hit_points <= 0 then destruct() end

  if math.random() < v2.mag(velocity) / 10 then
    game.particles.add_bubble(random_point_on_ship())
  end

  -- debug
  game.tracing.trace_bar(self.transform.pos + v2(0, 10),
                         hit_points / max_hit_points)
end

local function go_towards_or_away(target_pos, force_thrust, is_away)
  local target_direction = target_pos - self.transform.pos
  if is_away then target_direction = -target_direction end

  if v2.cross(self.transform.facing, target_direction) > 0 then
    turn(1)
  else
    turn(-1)
  end
  if force_thrust or v2.dot(self.transform.facing, target_direction) > 0 then
    thrust()
  end
end

function health_percentage()
  return math.max(hit_points / max_hit_points, 0)
end

function damage(amount)
  hit_points = math.max(hit_points - amount, 0)
end

function destruct()
  if self.factory_ai then
    factory_destruct()
  else
    game.particles.explode(self)
    game.log.record_death(self.blueprint)
    self.dead = true
  end
end

local death_counter = 100
local next_explosion = 10
local opacity = 0.6

function factory_destruct()
  if death_counter > 0 then
    self.production.halt_production = true
    self.sprite.color = {self.sprite.color[1], self.sprite.color[2], self.sprite.color[3], math.max(0, opacity)}
    opacity = opacity - 0.006
    if death_counter % next_explosion == 0 then
      game.particles.explode(self, random_point_on_ship())
      next_explosion = math.random(6,15)
    end
    death_counter = death_counter - 1
  else
    for i = 1,5 do
      random = (v2.random() + v2.random()) * 20
      game.particles.explode(self, self.transform.pos + random)
    end
    game.log.record_death(self.blueprint)
    self.dead = true
  end
end

-- automatically thrusts and turns according to the target
function go_towards(target_pos, force_thrust)
  go_towards_or_away(target_pos, force_thrust, false)
end

function go_away(target_pos, force_thrust)
  go_towards_or_away(target_pos, force_thrust, true)
end


text:
package com.facebook.imagepipeline.bitmaps;

import java.util.ConcurrentModificationException;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

import com.facebook.common.references.CloseableReference;
import com.facebook.common.references.ResourceReleaser;
import com.facebook.common.soloader.SoLoaderShim;
import com.facebook.imagepipeline.memory.BitmapCounter;
import com.facebook.imagepipeline.memory.BitmapCounterProvider;
import com.facebook.imagepipeline.memory.PooledByteBuffer;
import com.facebook.imagepipeline.memory.SharedByteArray;
import com.facebook.imagepipeline.nativecode.Bitmaps;
import com.facebook.imagepipeline.testing.MockBitmapFactory;
import com.facebook.imagepipeline.testing.TrivialPooledByteBuffer;
import com.facebook.testing.robolectric.v2.WithTestDefaultsRunner;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;

/**
 * Tests for {@link DalvikBitmapFactory}.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@RunWith(WithTestDefaultsRunner.class)
@PrepareOnlyThisForTest({
    BitmapCounterProvider.class,
    BitmapFactory.class,
    Bitmaps.class})
public class DalvikBitmapFactoryTest {

  static {
    SoLoaderShim.setInTestMode();
  }

  private static final int IMAGE_SIZE = 5;
  private static final int LENGTH = 10;
  private static final long POINTER = 1000L;
  private static final int MAX_BITMAP_COUNT = 2;
  private static final int MAX_BITMAP_SIZE =
      MAX_BITMAP_COUNT * MockBitmapFactory.DEFAULT_BITMAP_SIZE;

  private SharedByteArray mSharedByteArray;

  private DalvikBitmapFactory mDalvikBitmapFactory;
  private CloseableReference<PooledByteBuffer> mInputImageRef;
  private byte[] mInputBuf;
  private byte[] mDecodeBuf;
  private CloseableReference<byte[]> mDecodeBufRef;
  private Bitmap mBitmap;
  private BitmapCounter mBitmapCounter;

  @Before
  public void setUp() {
    mSharedByteArray = mock(SharedByteArray.class);

    mBitmap = MockBitmapFactory.create();
    mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT, MAX_BITMAP_SIZE);

    mockStatic(BitmapCounterProvider.class);
    when(BitmapCounterProvider.get()).thenReturn(mBitmapCounter);

    mockStatic(BitmapFactory.class);
    when(BitmapFactory.decodeByteArray(
            any(byte[].class),
            anyInt(),
            anyInt(),
            any(BitmapFactory.Options.class)))
        .thenReturn(mBitmap);

    mInputBuf = new byte[LENGTH];
    PooledByteBuffer input = new TrivialPooledByteBuffer(mInputBuf, POINTER);
    mInputImageRef = CloseableReference.of(input);

    mDecodeBuf = new byte[LENGTH + 2];
    mDecodeBufRef = CloseableReference.of(mDecodeBuf, mock(ResourceReleaser.class));
    when(mSharedByteArray.get(Integer.valueOf(LENGTH))).thenReturn(mDecodeBufRef);

    mockStatic(Bitmaps.class);
    mDalvikBitmapFactory = new DalvikBitmapFactory(
        null,
        mSharedByteArray);
  }

  @Test
  public void testDecode_Jpeg_Detailed() {
    setUpJpegDecode();
    CloseableReference<Bitmap> result = mDalvikBitmapFactory.decodeJPEGFromPooledByteBuffer(
        mInputImageRef,
        IMAGE_SIZE);
    verifyDecodesJpeg(result);
  }

  @Test
  public void testDecodeJpeg_incomplete() {
    when(mSharedByteArray.get(IMAGE_SIZE + 2)).thenReturn(mDecodeBufRef);
    CloseableReference<Bitmap> result =
        mDalvikBitmapFactory.decodeJPEGFromPooledByteBuffer(mInputImageRef, IMAGE_SIZE);
    verify(mSharedByteArray).get(IMAGE_SIZE + 2);
    verifyStatic();
    BitmapFactory.decodeByteArray(
        same(mDecodeBuf),
        eq(0),
        eq(IMAGE_SIZE + 2),
        argThat(new BitmapFactoryOptionsMatcher()));
    assertEquals((byte) 0xff, mDecodeBuf[5]);
    assertEquals((byte) 0xd9, mDecodeBuf[6]);
    assertEquals(1, mInputImageRef.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
    assertEquals(mBitmap, result.get());
    assertTrue(result.isValid());
    assertEquals(1, mBitmapCounter.getCount());
    assertEquals(MockBitmapFactory.DEFAULT_BITMAP_SIZE, mBitmapCounter.getSize());
  }

  @Test(expected = TooManyBitmapsException.class)
  public void testHitBitmapLimit_static() {
    mBitmapCounter.increase(MockBitmapFactory.createForSize(MAX_BITMAP_SIZE));
    try {
      mDalvikBitmapFactory.decodeFromPooledByteBuffer(mInputImageRef);
    } finally {
      verify(mBitmap).recycle();
      assertEquals(1, mBitmapCounter.getCount());
      assertEquals(MAX_BITMAP_SIZE, mBitmapCounter.getSize());
    }
  }

  @Test(expected = ConcurrentModificationException.class)
  public void testPinBitmapFailure_static() {
    PowerMockito.doThrow(new ConcurrentModificationException()).when(Bitmaps.class);
    Bitmaps.pinBitmap(any(Bitmap.class));
    try {
      mDalvikBitmapFactory.decodeFromPooledByteBuffer(mInputImageRef);
    } finally {
      verify(mBitmap).recycle();
      assertEquals(0, mBitmapCounter.getCount());
      assertEquals(0, mBitmapCounter.getSize());
    }
  }

  private void verifyDecodesStatic(CloseableReference<Bitmap> result) {
    assertEquals(1, mInputImageRef.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
    assertEquals(mBitmap, result.get());
    assertTrue(result.isValid());
    assertEquals(1, mBitmapCounter.getCount());
    assertEquals(MockBitmapFactory.DEFAULT_BITMAP_SIZE, mBitmapCounter.getSize());
    verifyStatic();
    Bitmaps.pinBitmap(mBitmap);
    assertFalse(CloseableReference.isValid(mDecodeBufRef));
  }

  private void setUpJpegDecode() {
    mInputBuf[3] = (byte) 0xff;
    mInputBuf[4] = (byte) 0xd9;
    when(mSharedByteArray.get(IMAGE_SIZE + 2)).thenReturn(mDecodeBufRef);
  }

  private void verifyDecodesJpeg(CloseableReference<Bitmap> result) {
    verify(mSharedByteArray).get(IMAGE_SIZE + 2);
    verifyStatic();
    BitmapFactory.decodeByteArray(
        same(mDecodeBuf),
        eq(0),
        eq(IMAGE_SIZE),
        argThat(new BitmapFactoryOptionsMatcher()));
    assertEquals(1, mInputImageRef.getUnderlyingReferenceTestOnly().getRefCountTestOnly());
    assertEquals(mBitmap, result.get());
    assertTrue(result.isValid());
    assertEquals(1, mBitmapCounter.getCount());
    assertEquals(MockBitmapFactory.DEFAULT_BITMAP_SIZE, mBitmapCounter.getSize());
  }

  private static class BitmapFactoryOptionsMatcher
      extends ArgumentMatcher<BitmapFactory.Options> {
    @Override
    public boolean matches(Object argument) {
      if (argument == null) {
        return false;
      }
      BitmapFactory.Options options = (BitmapFactory.Options) argument;
      return options.inDither &&
          options.inPreferredConfig == Bitmaps.BITMAP_CONFIG &&
          options.inPurgeable;
    }
  }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/file_system_access/file_system_access_file_writer_impl.h"

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/services/quarantine/quarantine.h"
#include "content/browser/file_system_access/file_system_access_error.h"
#include "content/browser/file_system_access/file_system_access_manager_impl.h"
#include "content/browser/file_system_access/safe_move_helper.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "storage/browser/file_system/file_system_operation.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom.h"

using blink::mojom::FileSystemAccessStatus;
using storage::FileSystemOperation;
using storage::FileSystemOperationRunner;

namespace content {

struct FileSystemAccessFileWriterImpl::WriteState {
  WriteCallback callback;
  uint64_t bytes_written = 0;
};

FileSystemAccessFileWriterImpl::FileSystemAccessFileWriterImpl(
    FileSystemAccessManagerImpl* manager,
    base::PassKey<FileSystemAccessManagerImpl> pass_key,
    const BindingContext& context,
    const storage::FileSystemURL& url,
    const storage::FileSystemURL& swap_url,
    scoped_refptr<FileSystemAccessWriteLockManager::WriteLock> lock,
    const SharedHandleState& handle_state,
    mojo::PendingReceiver<blink::mojom::FileSystemAccessFileWriter> receiver,
    bool has_transient_user_activation,
    bool auto_close,
    download::QuarantineConnectionCallback quarantine_connection_callback)
    : FileSystemAccessHandleBase(manager, context, url, handle_state),
      receiver_(this, std::move(receiver)),
      swap_url_(swap_url),
      lock_(std::move(lock)),
      quarantine_connection_callback_(
          std::move(quarantine_connection_callback)),
      has_transient_user_activation_(has_transient_user_activation),
      auto_close_(auto_close) {
  DCHECK_EQ(swap_url.type(), url.type());
  DCHECK_EQ(lock_->type(),
            FileSystemAccessWriteLockManager::WriteLockType::kShared);
  receiver_.set_disconnect_handler(base::BindOnce(
      &FileSystemAccessFileWriterImpl::OnDisconnect, base::Unretained(this)));
}

FileSystemAccessFileWriterImpl::~FileSystemAccessFileWriterImpl() {
  if (should_purge_swap_file_on_destruction_) {
    manager()->DoFileSystemOperation(
        FROM_HERE, &FileSystemOperationRunner::RemoveFile,
        base::BindOnce(
            [](const storage::FileSystemURL& swap_url,
               base::File::Error result) {
              if (result != base::File::FILE_OK &&
                  result != base::File::FILE_ERROR_NOT_FOUND) {
                DLOG(ERROR) << "Error Deleting Swap File, status: "
                            << base::File::ErrorToString(result)
                            << " path: " << swap_url.path();
              }
            },
            swap_url()),
        swap_url());
  }
}

void FileSystemAccessFileWriterImpl::Write(
    uint64_t offset,
    mojo::ScopedDataPipeConsumerHandle stream,
    WriteCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  RunWithWritePermission(
      base::BindOnce(&FileSystemAccessFileWriterImpl::WriteImpl,
                     weak_factory_.GetWeakPtr(), offset, std::move(stream)),
      base::BindOnce([](blink::mojom::FileSystemAccessErrorPtr result,
                        WriteCallback callback) {
        std::move(callback).Run(std::move(result),
                                /*bytes_written=*/0);
      }),
      std::move(callback));
}

void FileSystemAccessFileWriterImpl::Truncate(uint64_t length,
                                              TruncateCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  RunWithWritePermission(
      base::BindOnce(&FileSystemAccessFileWriterImpl::TruncateImpl,
                     weak_factory_.GetWeakPtr(), length),
      base::BindOnce([](blink::mojom::FileSystemAccessErrorPtr result,
                        TruncateCallback callback) {
        std::move(callback).Run(std::move(result));
      }),
      std::move(callback));
}

void FileSystemAccessFileWriterImpl::Close(CloseCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  RunWithWritePermission(
      base::BindOnce(&FileSystemAccessFileWriterImpl::CloseImpl,
                     weak_factory_.GetWeakPtr()),
      base::BindOnce([](blink::mojom::FileSystemAccessErrorPtr result,
                        CloseCallback callback) {
        std::move(callback).Run(std::move(result));
      }),
      std::move(callback));
}

void FileSystemAccessFileWriterImpl::Abort(AbortCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  RunWithWritePermission(
      base::BindOnce(&FileSystemAccessFileWriterImpl::AbortImpl,
                     weak_factory_.GetWeakPtr()),
      base::BindOnce([](blink::mojom::FileSystemAccessErrorPtr result,
                        AbortCallback callback) {
        std::move(callback).Run(std::move(result));
      }),
      std::move(callback));
}

// Do not call this method if `close_callback_` is not set.
void FileSystemAccessFileWriterImpl::CallCloseCallbackAndDeleteThis(
    blink::mojom::FileSystemAccessErrorPtr result) {
  should_purge_swap_file_on_destruction_ =
      result->status != blink::mojom::FileSystemAccessStatus::kOk;
  std::move(close_callback_).Run(std::move(result));

  // `this` is deleted after this call.
  manager()->RemoveFileWriter(this);
}

void FileSystemAccessFileWriterImpl::OnDisconnect() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  receiver_.reset();

  if (is_close_pending())
    // Mojo connection lost while Close() in progress.
    return;

  if (auto_close_) {
    // Close the Writer. `this` is deleted via
    // CallCloseCallbackAndDeleteThis when Close() finishes.
    Close(base::BindOnce([](blink::mojom::FileSystemAccessErrorPtr result) {
      if (result->status != blink::mojom::FileSystemAccessStatus::kOk) {
        DLOG(ERROR) << "AutoClose failed with result:"
                    << base::File::ErrorToString(result->file_error);
      }
    }));
    return;
  }

  // Mojo connection severed before Close() called. Destroy `this`.
  manager()->RemoveFileWriter(this);
}

void FileSystemAccessFileWriterImpl::WriteImpl(
    uint64_t offset,
    mojo::ScopedDataPipeConsumerHandle stream,
    WriteCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(GetWritePermissionStatus(),
            blink::mojom::PermissionStatus::GRANTED);

  if (is_close_pending()) {
    std::move(callback).Run(
        file_system_access_error::FromStatus(
            FileSystemAccessStatus::kInvalidState,
            "An attempt was made to write to a closing writer."),
        /*bytes_written=*/0);
    return;
  }

  manager()->DoFileSystemOperation(
      FROM_HERE, &FileSystemOperationRunner::WriteStream,
      base::BindRepeating(&FileSystemAccessFileWriterImpl::DidWrite,
                          weak_factory_.GetWeakPtr(),
                          base::Owned(new WriteState{std::move(callback)})),
      swap_url(), std::move(stream), offset);
}

void FileSystemAccessFileWriterImpl::DidWrite(WriteState* state,
                                              base::File::Error result,
                                              int64_t bytes,
                                              bool complete) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  DCHECK(state);
  state->bytes_written += bytes;
  if (complete) {
    std::move(state->callback)
        .Run(file_system_access_error::FromFileError(result),
             state->bytes_written);
  }
}

void FileSystemAccessFileWriterImpl::TruncateImpl(uint64_t length,
                                                  TruncateCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(GetWritePermissionStatus(),
            blink::mojom::PermissionStatus::GRANTED);

  if (is_close_pending()) {
    std::move(callback).Run(file_system_access_error::FromStatus(
        FileSystemAccessStatus::kInvalidState,
        "An attempt was made to write to a closing writer."));
    return;
  }

  manager()->DoFileSystemOperation(
      FROM_HERE, &FileSystemOperationRunner::Truncate,
      base::BindOnce(
          [](TruncateCallback callback, base::File::Error result) {
            std::move(callback).Run(
                file_system_access_error::FromFileError(result));
          },
          std::move(callback)),
      swap_url(), length);
}

void FileSystemAccessFileWriterImpl::CloseImpl(CloseCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(GetWritePermissionStatus(),
            blink::mojom::PermissionStatus::GRANTED);
  if (is_close_pending()) {
    std::move(callback).Run(file_system_access_error::FromStatus(
        FileSystemAccessStatus::kInvalidState,
        "An attempt was made to close an already closing writer."));
    return;
  }

  close_callback_ = std::move(callback);

  auto safe_move_helper = std::make_unique<SafeMoveHelper>(
      manager()->AsWeakPtr(), context(),
      /*source_url=*/swap_url(),
      /*dest_url=*/url(),
      FileSystemOperation::CopyOrMoveOptionSet(
          FileSystemOperation::CopyOrMoveOption::
              kPreserveDestinationPermissions),
      std::move(quarantine_connection_callback_),
      has_transient_user_activation_);
  // Allows the unique pointer to be bound to the callback so the helper stays
  // alive until the operation completes.
  SafeMoveHelper* raw_helper = safe_move_helper.get();
  raw_helper->Start(
      base::BindOnce(&FileSystemAccessFileWriterImpl::DidReplaceSwapFile,
                     weak_factory_.GetWeakPtr(), std::move(safe_move_helper)));
}

void FileSystemAccessFileWriterImpl::AbortImpl(AbortCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (is_close_pending()) {
    std::move(callback).Run(file_system_access_error::FromStatus(
        FileSystemAccessStatus::kInvalidState,
        "An attempt was made to abort an already closing writer."));
    return;
  }

  auto_close_ = false;

  std::move(callback).Run(file_system_access_error::Ok());

  // `this` is deleted after this call.
  manager()->RemoveFileWriter(this);
}

void FileSystemAccessFileWriterImpl::DidReplaceSwapFile(
    std::unique_ptr<content::SafeMoveHelper> /*safe_move_helper*/,
    blink::mojom::FileSystemAccessErrorPtr result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (result->status != FileSystemAccessStatus::kOk) {
    DLOG(ERROR) << "Swap file move operation failed source: "
                << swap_url().path() << " dest: " << url().path()
                << " error: " << base::File::ErrorToString(result->file_error);
    CallCloseCallbackAndDeleteThis(std::move(result));
    return;
  }

  CallCloseCallbackAndDeleteThis(file_system_access_error::Ok());
}

base::WeakPtr<FileSystemAccessHandleBase>
FileSystemAccessFileWriterImpl::AsWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

}  // namespace content


text:
#include "WavefrontLoader.h"
#include "Environment.h"
#include "Logger.h"
#include "Platform.h"
#include "SceneLoadContext.h"
#include "mesh/MeshBase.h"

#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"

namespace PR {
WavefrontLoader::WavefrontLoader(const std::string& override_name)
	: mName(override_name)
	, mScale(1)
	, mFlipNormal(false)
{
}

WavefrontLoader::~WavefrontLoader()
{
}

void WavefrontLoader::load(const std::filesystem::path& file, SceneLoadContext& ctx)
{
	tinyobj::attrib_t attrib;
	std::vector<tinyobj::shape_t> shapes;
	std::vector<tinyobj::material_t> materials; // We ignore materials for now
	std::string warn;
	std::string err;

	std::ifstream stream;
	stream.open(file.c_str(), std::ios::in);
	if (!stream) {
		PR_LOG(L_ERROR) << "Wavefront file: Could not open file " << file << std::endl;
		return;
	}

	if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, &stream, nullptr /*material reader*/, true /*triangulate*/, false, true)) {
		PR_LOG(L_ERROR) << "Error reading Wavefront file: " << err << std::endl;
	} else {
		stream.close();

		if (!warn.empty()) {
			PR_LOG(L_WARNING) << "Wavefront file: " << warn << std::endl;
		}

		if (!err.empty()) {
			PR_LOG(L_ERROR) << "Wavefront file: " << err << std::endl;
		}

		if (shapes.empty()) {
			PR_LOG(L_ERROR) << "Wavefront file: No shape given!" << std::endl;
			return;
		}

		if (shapes.size() > 1) {
			PR_LOG(L_WARNING) << "Wavefront file: Contains multiple shapes. Will be combined to one " << std::endl;
		}

		if (attrib.vertices.empty()) {
			PR_LOG(L_ERROR) << "Wavefront file: No vertices given!" << std::endl;
			return;
		}

		// Check if vertex indices and normal indices are the same
		bool hasDiffNormalIndices = false;
		for (size_t sh = 0; sh < shapes.size(); ++sh) {
			for (const auto& index : shapes[sh].mesh.indices) {
				if (index.vertex_index != index.normal_index) {
					hasDiffNormalIndices = true;
					goto hasDiffCheckDone;
				}
			}
		}
	hasDiffCheckDone:

		// Check if vertex indices and texture coordinate indices are the same
		bool hasDiffTextureIndices = false;
		for (size_t sh = 0; sh < shapes.size(); ++sh) {
			for (const auto& index : shapes[sh].mesh.indices) {
				if (index.vertex_index != index.texcoord_index) {
					hasDiffTextureIndices = true;
					goto hasDiffCheckDone2;
				}
			}
		}
	hasDiffCheckDone2:

		// Scale if necessary
		if (mScale != 1.0f) {
			for (size_t i = 0; i < attrib.vertices.size(); ++i)
				attrib.vertices[i] *= mScale;
		}

		// Flip normals if necessary
		if (mFlipNormal) {
			for (size_t i = 0; i < attrib.normals.size(); ++i)
				attrib.normals[i] *= -1;
		}

		// Calculate general (vertex) information
		const size_t vertex_count = attrib.vertices.size();
		size_t indices_count	  = 0;
		for (size_t sh = 0; sh < shapes.size(); ++sh)
			indices_count += shapes[sh].mesh.indices.size();

		size_t face_count = 0;
		for (size_t sh = 0; sh < shapes.size(); ++sh)
			face_count += shapes[sh].mesh.num_face_vertices.size();

		// Setup vertex indices
		std::vector<uint32> indices;
		indices.reserve(indices_count);
		for (size_t sh = 0; sh < shapes.size(); ++sh) {
			const auto& m = shapes[sh].mesh;
			for (size_t i = 0; i < m.indices.size(); ++i)
				indices.push_back(std::max(0, m.indices.at(i).vertex_index));
		}

		auto mesh = std::make_unique<MeshBase>();
		mesh->setVertexComponent(MeshComponent::Vertex, std::move(attrib.vertices));
		mesh->setVertexComponentIndices(MeshComponent::Vertex, std::move(indices));

		// Calculate face vertex count
		std::vector<uint8> faceVertexCount;
		faceVertexCount.resize(face_count);
		size_t offset = 0;
		for (size_t sh = 0; sh < shapes.size(); ++sh) {
			const size_t k = shapes[sh].mesh.num_face_vertices.size();
			std::move(shapes[sh].mesh.num_face_vertices.begin(), shapes[sh].mesh.num_face_vertices.end(), faceVertexCount.begin() + offset);
			offset += k;
		}

		mesh->setFaceVertexCount(std::move(faceVertexCount));

		// Add normals if available
		if (!attrib.normals.empty()) {
			mesh->setVertexComponent(MeshComponent::Normal, std::move(attrib.normals));

			if (hasDiffNormalIndices) {
				std::vector<uint32> norm_indices;
				norm_indices.reserve(indices_count);
				for (size_t sh = 0; sh < shapes.size(); ++sh) {
					const auto& m = shapes[sh].mesh;
					for (size_t i = 0; i < m.indices.size(); ++i)
						norm_indices.push_back(std::max(0, m.indices.at(i).normal_index));
				}
				mesh->setVertexComponentIndices(MeshComponent::Normal, std::move(norm_indices));
			}
		}

		// Add texture coordinates if available
		if (!attrib.texcoords.empty()) {
			mesh->setVertexComponent(MeshComponent::Texture, std::move(attrib.texcoords));

			if (hasDiffTextureIndices) {
				std::vector<uint32> tex_indices;
				tex_indices.reserve(indices_count);
				for (size_t sh = 0; sh < shapes.size(); ++sh) {
					const auto& m = shapes[sh].mesh;
					for (size_t i = 0; i < m.indices.size(); ++i)
						tex_indices.push_back(std::max(0, m.indices.at(i).texcoord_index));
				}
				mesh->setVertexComponentIndices(MeshComponent::Texture, std::move(tex_indices));
			}
		}

		// Add weights if available
		if (attrib.vertex_weights.size() == vertex_count)
			mesh->setVertexComponent(MeshComponent::Weight, std::move(attrib.vertex_weights));

		// Material IDs if available
		// TODO

		// Give mesh a name (default is first shape name)
		std::string name = shapes[0].name;
		if (!mName.empty())
			name = mName;

		if (ctx.hasMesh(name))
			PR_LOG(L_ERROR) << "Mesh " << name << " already in use." << std::endl;

		std::string errMsg;
		if (!mesh->isValid(&errMsg)) {
			PR_LOG(L_WARNING) << "Obj file could not construct a valid mesh data: " << errMsg << std::endl;
			return;
		}

		PR_LOG(L_INFO) << "Added mesh '" << name << "' with " << mesh->triangleCount() << " triangles and " << mesh->quadCount() << " quads" << std::endl;
		ctx.addMesh(name, std::move(mesh));
	}
}
} // namespace PR


text:
@interface Book : NSObject<SJDBMapUseProtocol>

@property (nonatomic, assign) NSInteger bookID;

@property (nonatomic, strong) NSString *name;

@property (nonatomic) BOOL like;

//@property (nonatomic, strong) Book *BBBBB;

+ (instancetype)bookWithID:(NSInteger)bid name:(NSString *)name;
@end


text:
{- In this module, we adopt the following convetions:
        ascii   = an 8 bit character
        hexchar = a sequence of two hexadecimal digits represented by
                  two ascii characters. Example ['f','f'] = 255
        Octet   = Word8
-}

module Mercado.Internal.HMAC_SHA2 where

import Data.Digest.SHA2
import Data.HMAC

import Codec.Utils      (Octet)
import Numeric          (readHex, showHex)

type Hexchar = String

hmac_sha256 :: [Octet] -> [Octet] -> [Octet]
hmac_sha256 = hmac sha256_hm
  where sha256_hm = HashMethod (toOctets . sha256) 512

hmac_sha512 :: [Octet] -> [Octet] -> [Octet]
hmac_sha512 = hmac sha512_hm
  where sha512_hm = HashMethod (toOctets . sha512) 1024

hmac_sha256ToHexchars :: [Octet] -> [Octet] -> String
hmac_sha256ToHexchars key msg = octetsToHexchars $ hmac_sha256 key msg

hmac_sha512ToHexchars :: [Octet] -> [Octet] -> String
hmac_sha512ToHexchars key msg = octetsToHexchars $ hmac_sha512 key msg

octetsToHexchars :: [Octet] -> String
octetsToHexchars = concatMap (pad . flip showHex "")

hexcharsToOctets:: String -> Maybe [Octet]
hexcharsToOctets [] = Just []
-- two at a time
hexcharsToOctets (a:b:cs) = (:) <$> readByte a b <*> hexcharsToOctets cs
  where
    readByte :: Char -> Char -> Maybe Octet
    readByte h l = fst <$> safeHead (readHex (h:l:[]))
-- last pattern is only reached if list of Hexadecimal digits had odd number of digits
hexcharsToOctets (_a:[]) = Nothing

safeHead :: [a] -> Maybe a
safeHead []    = Nothing
safeHead (x:_) = Just x

-- Converts list of characters into list of Octets
-- Only works if we have a maximum value of 255 for a single char (so that it fits in an Octet).
asciisToOctets :: String -> [Octet]
asciisToOctets = map (fromIntegral . fromEnum)

-- needed for padding single digits output by showHex or it will truncate
-- left zeros. e.g. hex ['0','9'] becomes ['9']
pad :: String -> String
pad [d] = ['0', d]
pad  ds = ds

-- test cases from http://www.rfc-base.org/txt/rfc-4231.txt
-- sorry, hash ommitted.

--test case 2
--key :: [Octet]
--key = map ( fromIntegral . fromEnum ) "Jefe"
--msg = map ( fromIntegral . fromEnum ) "what do ya want for nothing?"

--test cases 3
--key :: [Octet]
--key = map ( fromIntegral . fromEnum ) (take 20 (repeat 170 ) )
--msg = map ( fromIntegral . fromEnum ) (take 50 (repeat 221 ) )

--test cases 6
--key :: [Octet]
--key = map ( fromIntegral . fromEnum ) (take 131 (repeat 170 ) )
--msg = map ( fromIntegral . fromEnum ) "Test Using Larger Than Block-Size Key - Hash Key First"

--test cases 7
--key :: [Octet]
--key = map ( fromIntegral . fromEnum ) (take 131 (repeat 170 ) )
-- msg = asciisToOctets ("This is a test using a larger than " ++
--                       "block-size key and a larger than block-size data. " ++
--                       "The key needs to be hashed before being used by the HMAC algorithm.")

--  HMAC-SHA-256 = 9b09ffa71b942fcb27635fbcd5b0e944
--                 bfdc63644f0713938a7f51535c3a35e2

--  HMAC-SHA-512 = e37b6a775dc87dbaa4dfa9f96e5e3ffd
--                 debd71f8867289865df5a32d20cdc944
--                 b6022cac3c4982b10d5eeb55c3e4de15
--                 134676fb6de0446065c97440fa8c6a58

--mac256 = hmac_sha256ToHexchars key msg
--mac512 = hmac_sha512ToHexchars key msg

---- example
--x :: Octet
--x = fromIntegral 5

--h = (toOctets . sha512) [x]

--a :: Octet
--a = fromIntegral $ fromEnum 'a'
--b :: Octet
--b = fromIntegral $ fromEnum 'b'
--c :: Octet
--c = fromIntegral $ fromEnum 'c'

--main = do
--        print "Hi 5!"
--        print h
--        print $ sha256Ascii "abc"
--        print $ sha256 [a,b,c]
--        print "----"
--        print mac256
--        print mac512


text:
<?php
/**
 * Install plugin administration panel.
 *
 * @package WordPress
 * @subpackage Administration
 */
// TODO route this pages via a specific iframe handler instead of the do_action below
if ( !defined( 'IFRAME_REQUEST' ) && isset( $_GET['tab'] ) && ( 'plugin-information' == $_GET['tab'] ) )
	define( 'IFRAME_REQUEST', true );

/** WordPress Administration Bootstrap */
require_once('./admin.php');

if ( ! current_user_can('install_plugins') )
	wp_die(__('You do not have sufficient permissions to install plugins on this site.'));

if ( is_multisite() && ! is_network_admin() ) {
	wp_redirect( network_admin_url( 'plugin-install.php' ) );
	exit();
}

$wp_list_table = _get_list_table('WP_Plugin_Install_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$wp_list_table->prepare_items();

$title = __('Install Plugins');
$parent_file = 'plugins.php';

wp_enqueue_style( 'plugin-install' );
wp_enqueue_script( 'plugin-install' );
if ( 'plugin-information' != $tab )
	add_thickbox();

$body_id = $tab;

do_action('install_plugins_pre_' . $tab); //Used to override the general interface, Eg, install or plugin information.

add_contextual_help($current_screen,
	'
' . sprintf(__('Plugins hook into WordPress to extend its functionality with custom features. Plugins are developed independently from WordPress core by thousands of developers all over the world. All plugins in the official WordPress.org Plugin Directory are compatible with the license WordPress uses. You can find new plugins to install by searching or browsing the Directory right here in your own Plugins section.'), 'http://wordpress.org/extend/plugins/') . '
' .
	'
' . __('If you know what you’re looking for, Search is your best bet. The Search screen has options to search the WordPress.org Plugin Directory for a particular Term, Author, or Tag. You can also search the directory by selecting a popular tags. Tags in larger type mean more plugins have been labeled with that tag.') . '
' .
	'
' . __('If you just want to get an idea of what’s available, you can browse Featured, Popular, Newest, and Recently Updated plugins by using the links in the upper left of the screen. These sections rotate regularly.') . '
' .
	'
' . __('If you want to install a plugin that you’ve downloaded elsewhere, click Upload in the upper left. You will be prompted to upload the .zip package, and once uploaded, you can activate the new plugin.') . '
' .
	'
' . __('For more information:') . '
' .
	'
' . __('Documentation on Installing Plugins') . '
' .
	'
' . __('Support Forums') . '
'
);

include(ABSPATH . 'wp-admin/admin-header.php');
?>

<?php screen_icon(); ?>

<?php echo esc_html( $title ); ?>

<?php $wp_list_table->views(); ?>

<?php do_action('install_plugins_' . $tab, $paged); ?>

<?php
include(ABSPATH . 'wp-admin/admin-footer.php');


text:
package cfvbaibai.cardfantasy.engine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cfvbaibai.cardfantasy.CardFantasyRuntimeException;

public class Field extends CardPile {

    private Player owner;
    public Field(Player owner) {
        this.owner = owner;
    }

    public Player getOwner() {
        return this.owner;
    }

    public List<CardInfo> getAliveCards() {
        List<CardInfo> result = new ArrayList<CardInfo>();
        for (CardInfo card : getCards()) {
            if (card != null) {
                result.add(card);
            }
        }
        return result;
    }

    public CardInfo getCard(int i) {
        if (i < 0) {
            throw new CardFantasyRuntimeException("Invalid parameter i: " + i + ". i must be a positive integer.");
        }
        if (i >= size()) {
            return null;
        } else {
            return this.getCards().get(i);
        }
    }

    public CardInfo expelCard(int i) {
        if (i < 0 || i >= getCards().size()) {
            throw new CardFantasyRuntimeException("Invalid parameter i: " + i + ". Card count = " + size());
        }
        CardInfo expelledCard = getCards().get(i);
        getCards().set(i, null);
        return expelledCard;
    }

    public void compact() {
        int i = 0;
        while (i < size()) {
            if (getCards().get(i) == null) {
                getCards().remove(i);
            } else {
                ++i;
            }
        }

        for (CardInfo card : getCards()) {
            card.refreshPosition();
        }
    }

    private static class HPCardComparator implements Comparator <CardInfo> {

        @Override
        public int compare(CardInfo card1, CardInfo card2) {
            return card1.getHP() - card2.getHP();
        }

    }

    public List<CardInfo> getCardsWithLowestHP(int targetCount) {
        List<CardInfo> aliveCards = this.getAliveCards();
        if (aliveCards.size() <= targetCount) {
            return aliveCards;
        }
        Collections.sort(aliveCards, new HPCardComparator());
        return aliveCards.subList(0, targetCount);
    }
}


text:
from IPython import get_ipython

class LanternException(Exception):
    pass

def in_ipynb():
    ip = get_ipython()
    if ip:
        cfg = ip.config
        if cfg.get('IPKernelApp', False):
            return True
        return False
    return False

def download(df):
    from IPython.display import HTML
    import base64
    csv = base64.b64encode(df.reset_index().to_csv().encode()).decode()
    html = 'Download'.format(payload=csv)
    return HTML(html)