text:
layout: archive
title: Tags
permalink: /tags/
excerpt: "An archive of posts sorted by tag."
author_profile: true
---

{% include group-by-array collection=site.posts field="tags" %}

  {% for tag in group_names %}
    {% assign posts = group_items[forloop.index0] %}

{{ tag }}  ({{ posts.size }})

  {% endfor %}

{% for tag in group_names %}
  {% assign posts = group_items[forloop.index0] %}

{{ tag }}

  {% for post in posts %}
    {% include archive-single.html %}
  {% endfor %}
{% endfor %}


text:
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()

class Referrable(object):
    __slots__ = ['_tab']

    @classmethod
    def GetRootAsReferrable(cls, buf, offset):
        n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
        x = Referrable()
        x.Init(buf, n + offset)
        return x

    @classmethod
    def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
        return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)

    # Referrable
    def Init(self, buf, pos):
        self._tab = flatbuffers.table.Table(buf, pos)

    # Referrable
    def Id(self):
        o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
        if o != 0:
            return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
        return 0

def ReferrableStart(builder): builder.StartObject(1)
def ReferrableAddId(builder, id): builder.PrependUint64Slot(0, id, 0)
def ReferrableEnd(builder): return builder.EndObject()

class ReferrableT(object):

    # ReferrableT
    def __init__(self):
        self.id = 0  # type: int

    @classmethod
    def InitFromBuf(cls, buf, pos):
        referrable = Referrable()
        referrable.Init(buf, pos)
        return cls.InitFromObj(referrable)

    @classmethod
    def InitFromObj(cls, referrable):
        x = ReferrableT()
        x._UnPack(referrable)
        return x

    # ReferrableT
    def _UnPack(self, referrable):
        if referrable is None:
            return
        self.id = referrable.Id()

    # ReferrableT
    def Pack(self, builder):
        ReferrableStart(builder)
        ReferrableAddId(builder, self.id)
        referrable = ReferrableEnd(builder)
        return referrable

redpajama_set_name: RedPajamaGithub


text:
"""
This module contains a dictionary mapping the identifiers to the fsi-classes
"""
from stash.system.shcommon import _STASH_EXTENSION_FSI_PATH
from stashutils.fsi.local import LocalFSI
from stashutils.fsi.FTP import FTPFSI
from stashutils.fsi.DropBox import DropboxFSI
from stashutils.fsi.zip import ZipfileFSI
from stashutils.core import load_from_dir

# map type -> FSI_class
FILESYSTEM_TYPES = {
	"local": LocalFSI,
	"Local": LocalFSI,
	"FTP": FTPFSI,
	"ftp": FTPFSI,
	"dropbox": DropboxFSI,
	"DropBox": DropboxFSI,
	"Dropbox": DropboxFSI,
	"zip": ZipfileFSI,
	"Zip": ZipfileFSI,
	"ZIP": ZipfileFSI,
	"zipfile": ZipfileFSI,
}

# update with extensions
extensions = load_from_dir(
	dirpath=_STASH_EXTENSION_FSI_PATH, varname="FSIS",
	)
for ext in extensions:
	if not isinstance(ext, dict):
		continue
	else:
		FILESYSTEM_TYPES.update(ext)

# alias used by mc
INTERFACES = FILESYSTEM_TYPES


text:
A *workspace* is a collection of one or more packages that share common
dependency resolution (with a shared `Cargo.lock`), output directory, and
various settings such as profiles. Packages that are part of a workspaces are
called *workspace members*. There are two flavours of workspaces: as root
package or as virtual manifest.

### Root package

A workspace can be created by adding a [`[workspace]`
section](#the-workspace-section) to `Cargo.toml`. This can be added to a
`Cargo.toml` that already defines a `[package]`, in which case the package is
the *root package* of the workspace. The *workspace root* is the directory
where the workspace's `Cargo.toml` is located.

### Virtual manifest

Alternatively, a `Cargo.toml` file can be created with a `[workspace]` section
but without a [`[package]` section][package]. This is called a *virtual
manifest*. This is typically useful when there isn't a "primary" package, or
you want to keep all the packages organized in separate directories.

### Key features

The key points of workspaces are:

* All packages share a common `Cargo.lock` file which resides in the
  *workspace root*.
* All packages share a common [output directory], which defaults to a
  directory named `target` in the *workspace root*.
* The [`[patch]`][patch], [`[replace]`][replace] and [`[profile.*]`][profiles]
  sections in `Cargo.toml` are only recognized in the *root* manifest, and
  ignored in member crates' manifests.

### The `[workspace]` section

The `[workspace]` table in `Cargo.toml` defines which packages are members of
the workspace:

```toml
[workspace]
members = ["member1", "path/to/member2", "crates/*"]
exclude = ["crates/foo", "path/to/other"]
```

All [`path` dependencies] residing in the workspace directory automatically
become members. Additional members can be listed with the `members` key, which
should be an array of strings containing directories with `Cargo.toml` files.

The `members` list also supports [globs] to match multiple paths, using
typical filename glob patterns like `*` and `?`.

The `exclude` key can be used to prevent paths from being included in a
workspace. This can be useful if some path dependencies aren't desired to be
in the workspace at all, or using a glob pattern and you want to remove a
directory.

An empty `[workspace]` table can be used with a `[package]` to conveniently
create a workspace with the package and all of its path dependencies.

### Workspace selection

When inside a subdirectory within the workspace, Cargo will automatically
search the parent directories for a `Cargo.toml` file with a `[workspace]`
definition to determine which workspace to use. The [`package.workspace`]
manifest key can be used in member crates to point at a workspace's root to
override this automatic search. The manual setting can be useful if the member
is not inside a subdirectory of the workspace root.

### Package selection

In a workspace, package-related cargo commands like [`cargo build`] can use
the `-p` / `--package` or `--workspace` command-line flags to determine which
packages to operate on. If neither of those flags are specified, Cargo will
use the package in the current working directory. If the current directory is
a virtual workspace, it will apply to all members (as if `--workspace` were
specified on the command-line).

The optional `default-members` key can be specified to set the members to
operate on when in the workspace root and the package selection flags are not
used:

```toml
[workspace]
members = ["path/to/member1", "path/to/member2", "path/to/member3/*"]
default-members = ["path/to/member2", "path/to/member3/foo"]
```

When specified, `default-members` must expand to a subset of `members`.

### The `workspace.metadata` table

The `workspace.metadata` table is ignored by Cargo and will not be warned
about. This section can be used for tools that would like to store workspace
configuration in `Cargo.toml`. For example:

```toml
[workspace]
members = ["member1", "member2"]

[workspace.metadata.webcontents]
root = "path/to/webproject"
tool = ["npm", "run", "build"]
# ...
```

There is a similar set of tables at the package level at
[`package.metadata`][package-metadata]. While cargo does not specify a
format for the content of either of these tables, it is suggested that
external tools may wish to use them in a consistent fashion, such as referring
to the data in `workspace.metadata` if data is missing from `package.metadata`,
if that makes sense for the tool in question.

[package]: manifest.md#the-package-section
[package-metadata]: manifest.md#the-metadata-table
[output directory]: ../guide/build-cache.md
[patch]: overriding-dependencies.md#the-patch-section
[replace]: overriding-dependencies.md#the-replace-section
[profiles]: profiles.md
[`path` dependencies]: specifying-dependencies.md#specifying-path-dependencies
[`package.workspace`]: manifest.md#the-workspace-field
[globs]: https://docs.rs/glob/0.3.0/glob/struct.Pattern.html
[`cargo build`]: ../commands/cargo-build.md


text:
namespace chrono {

struct MPM_Settings {
    float dt, kernel_radius, inv_radius, bin_edge;
    float inv_bin_edge, max_velocity, mu, lambda;
    float hardening_coefficient, theta_c, theta_s, alpha_flip;
    float h0, h1, h2, h3;
    float youngs_modulus, poissons_ratio;
    int num_mpm_markers;
    int num_mpm_nodes;
    float mass;
    float yield_stress, p2, p3;
    int num_iterations;
    int bins_per_axis_x;
    int bins_per_axis_y;
    int bins_per_axis_z;
};

}


text:
// Copyright 2015 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.

'use strict';

/**
 * Runs a test to ensure slideshow traverses images automatically
 *
 * @param {string} testVolumeName Test volume name passed to the addEntries
 *     function. Either 'drive' or 'local'.
 * @param {VolumeManagerCommon.VolumeType} volumeType Volume type.
 * @return {Promise} Promise to be fulfilled on success.
 */
function slideshowTraversal(testVolumeName, volumeType) {
  // Setup
  var testEntries = [ENTRIES.desktop, ENTRIES.image3];
  var launchedPromise = launch(
      testVolumeName, volumeType, testEntries, testEntries.slice(0, 1));
  var appId;
  return launchedPromise.then(function(args) {
    appId = args.appId;
    return gallery.waitForElement(appId, '.gallery[mode="slide"]');
  }).then(function() {
    return gallery.waitForSlideImage(appId, 800, 600, 'My Desktop Background');
  }).then(function() {
    // Check: There is a pause / play button
    return gallery.waitForElement(appId, '.slideshow-play:not([hidden])');
  }).then(function() {
    // Start slideshow.
    return gallery.waitAndClickElement(appId, '.slideshow.icon-button');
  }).then(function() {
    // Image will change automatically.
    return gallery.waitForSlideImage(appId, 640, 480, 'image3');
  }).then(function() {
    // Will rollover to the start again.
    return gallery.waitForSlideImage(appId, 800, 600, 'My Desktop Background');
  });
}

/**
 * Runs a test to ensure pausing slideshow stops images rolling
 *
 * @param {string} testVolumeName Test volume name passed to the addEntries
 *     function. Either 'drive' or 'local'.
 * @param {VolumeManagerCommon.VolumeType} volumeType Volume type.
 * @return {Promise} Promise to be fulfilled on success.
 */
function stopStartSlideshow(testVolumeName, volumeType) {
  var testEntries = [ENTRIES.desktop, ENTRIES.image3];
  var launchedPromise = launch(
      testVolumeName, volumeType, testEntries, testEntries.slice(0, 1));
  var appId;
  return launchedPromise.then(function(args) {
    appId = args.appId;
    return gallery.waitForElement(appId, '.gallery[mode="slide"]');
  }).then(function() {
    return gallery.waitForSlideImage(appId, 800, 600, 'My Desktop Background');
  }).then(function() {
    // Start slideshow.
    return gallery.waitAndClickElement(appId, '.slideshow.icon-button');
  }).then(function() {
    // Image will change automatically.
    return gallery.waitForSlideImage(appId, 640, 480, 'image3');
  }).then(function() {
    // Pause.
    return gallery.waitAndClickElement(appId, '.slideshow-play');
  }).then(function() {
    // Wait some time.
    return wait(3000);
  }).then(function() {
    // Check image is the same.
    return gallery.waitForSlideImage(appId, 640, 480, 'image3');
  }).then(function() {
    // Play.
    return gallery.waitAndClickElement(appId, '.slideshow-play');
  }).then(function() {
    // Check image changes.
    return gallery.waitForSlideImage(appId, 800, 600, 'My Desktop Background');
  });
}

/**
 * Runs a test to ensure there is not a play/pause button when one image
 * is selected.
 *
 * @param {string} testVolumeName Test volume name passed to the addEntries
 *     function. Either 'drive' or 'local'.
 * @param {VolumeManagerCommon.VolumeType} volumeType Volume type.
 * @return {Promise} Promise to be fulfilled on success.
 */
function oneImageSlideshowNoPauseButton(testVolumeName, volumeType) {
  const testEntries = [ENTRIES.desktop];
  const launchedPromise = launch(
      testVolumeName, volumeType, testEntries);
  let appId;
  return launchedPromise.then(args => {
    appId = args.appId;
    return gallery.waitForElement(appId, '.gallery[mode="slide"]');
  }).then(() => {
    return gallery.waitForSlideImage(appId, 800, 600, 'My Desktop Background');
  }).then(() => {
    // Start slideshow.
    return gallery.waitAndClickElement(appId, '.slideshow.icon-button');
  }).then(() => {
    // Check: There is no pause / play button
    return gallery.waitForElement(appId, '.slideshow-play[hidden]');
  });
}

/**
 * The slideshowTraversal test for Downloads.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.slideshowTraversalOnDownloads = function() {
  return slideshowTraversal('local', 'downloads');
};

/**
 * The slideshowTraversal test for Drive.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.slideshowTraversalOnDrive = function() {
 return slideshowTraversal('drive', 'drive');
};

/**
 * The stopStartSlideshow test for Downloads.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.stopStartSlideshowOnDownloads = function() {
  return stopStartSlideshow('local', 'downloads');
};

/**
 * The stopStartSlideshow test for Drive.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.stopStartSlideshowOnDrive = function() {
  return stopStartSlideshow('drive', 'drive');
};

/**
 * The oneImageSlideshowNoPauseButton test for Downloads.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.oneImageSlideshowNoPauseButtonOnDownloads = () => {
  return oneImageSlideshowNoPauseButton('local', 'downloads');
};

/**
 * The oneImageSlideshowNoPauseButton test for Drive.
 * @return {Promise} Promise to be fulfilled on success.
 */
testcase.oneImageSlideshowNoPauseButtonOnDrive = () => {
  return oneImageSlideshowNoPauseButton('drive', 'drive');
};


text:
module OauthWrap::WebApp::Helpers

  def parse_body(response)
    result = {}

    response.body.split("&").each do |l|
      k, v = *(l.split("=", 2))
      result[k.to_sym] = v
    end

    # extend request result
    def response.parsed_body; @parsed_body; end
    def response.parsed_body=(v); @parsed_body = v; end

    response.parsed_body = result
  end

  def wrap_response?(response)
    return false if response.code.to_i != OauthWrap::WebApp::UNAUTHORIZED_STATUS_CODE
    auth_header = response.headers["www-authenticate"]
    auth_header and auth_header.include? "WRAP"
  end

end


text:
#ifndef _SEGMENT_H_INCLUDED
#define _SEGMENT_H_INCLUDED

#include <lio/segment.h>

gop_op_generic_t *segment_put_gop(gop_thread_pool_context_t *tpc, data_attr_t *da, lio_segment_rw_hints_t *rw_hints, FILE *fd, lio_segment_t *dest_seg, ex_off_t dest_offset, ex_off_t len, ex_off_t bufsize, char *buffer, int do_truncate, int timeout);
gop_op_generic_t *segment_get_gop(gop_thread_pool_context_t *tpc, data_attr_t *da, lio_segment_rw_hints_t *rw_hints, lio_segment_t *src_seg, FILE *fd, ex_off_t src_offset, ex_off_t len, ex_off_t bufsize, char *buffer, int timeout);
lio_segment_t *load_segment(lio_service_manager_t *ess, ex_id_t id, lio_exnode_exchange_t *ex);

// Preprocessor macros
#define lio_segment_type(s) (s)->header.type
#define segment_clone(s, da, clone_ex, mode, attr, to) \
    ((lio_segment_vtable_t *)(s)->obj.vtable)->clone(s, da, clone_ex, mode, attr, to)
#define segment_deserialize(s, id, exp) ((lio_segment_vtable_t *)(s)->obj.vtable)->deserialize(s, id, exp)
#define segment_get_gop_header(seg) &((seg)->header)
#define segment_lock(s) apr_thread_mutex_lock((s)->lock)
#define segment_remove(s, da, to) ((lio_segment_vtable_t *)(s)->obj.vtable)->remove(s, da, to)
#define segment_serialize(s, exp) ((lio_segment_vtable_t *)(s)->obj.vtable)->serialize(s, exp)
#define segment_set_header(seg, new_head) (seg)->header = *(new_head)
#define segment_unlock(s) apr_thread_mutex_unlock((s)->lock)

#endif


text:
import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    nestedAction() {
      this.attrs.nestedAction();
    }
  }
});


text:
'''
Created on 29 sept. 2013

@author: Aristote Diasonama
'''

"""
Python Module handling daily notification sent to user about event taking place daily
"""
import logging
from vendors.sendgrid import sender
import memcache
from market.handlers.base import BaseHandler, jinja_environment
from market.handlers.main import MainHandler
from google.appengine.ext import ndb
from google.appengine.api import taskqueue
from market.lib.event import EventManager
from market.lib.user import UserManager
from market.lib.attendance import AttendanceManager

from shop.models.user  import EmailNotificationsSettings as NotifSettings

class StartDailyNotificationHandler(BaseHandler):
    """
    This class executes a cron job whose mere purpose is to add the
    CreateWeeklyNotificationHandler to the taskqueue
    """
    def get(self):
        today_events = EventManager.get_event_list(filtered_by = 'today')
        if today_events:
            task = taskqueue.add(url='/tasks/notification/daily/start')
        self.render_template('ebdigest.html', {'event_list': today_events})

class CreateDailyNotificationHandler(BaseHandler):
    """
    This class create a list of task that the daily notifier queue must execute
    """
    def post(self):
        self.add_task()
        events = EventManager.get_event_list(filtered_by='today')
        self.render_template('ebdigest.html', {'event_list': events})

    def add_task(self):
        """
        add tasks to the given event
        """
        user_event_dict = self.get_user_event_dict()
        if user_event_dict:
            for user_id in user_event_dict.keys():
                queue = taskqueue.Queue('daily-notifier')
                queue.add(taskqueue.Task(url='/tasks/notification/daily',
                          params={'user_id':user_id,
                                  'email':user_event_dict[user_id]['email'],
                                  'events':user_event_dict[user_id]['events']
                                  }))

    def get_user_event_dict(self):
        """
        Get a dict of user_id as key and dict of list of events they are attending today and their email as value
        """
        events = EventManager.get_event_list(filtered_by='today')
        user_event_dict = {}
        already_in_dict = []
        no_send = []

        for event in events:
            event_key = ndb.Key(urlsafe=event['key'])
            user_ids = AttendanceManager.get_users_id_attending(event_key)
            if user_ids:
                for an_id in user_ids:
                    if an_id in already_in_dict:
                        user_event_dict[an_id]['events'].append(event['key'])
                    else:
                        if not an_id in no_send:
                            user_notif = NotifSettings.get_settings_for(user_id=an_id)
                            if user_notif.daily_alert:
                                user_event_dict[an_id] = {}
                                user_event_dict[an_id]['email'] = user_notif.email_to_use
                                user_event_dict[an_id]['events'] = [event['key']]
                                already_in_dict.append(an_id)
                            else:
                                no_send.append(an_id)

        return user_event_dict

class SendDailyNotificationHandler(MainHandler):
    """
    This class will send daily notification to a user about the event he has to attend
    """
    def post(self):
        user_id = int(self.request.get('user_id'))
        event_keys = self.request.get('events', allow_multiple=True)
        email = self.request.get('email')

        already_sent = memcache.get_daily_sent_ids()

        if not user_id or not email:
            logging.debug('NO POST DATAS PROVIDED')
            return

        if user_id in already_sent:
            return

        events = filter(lambda event: event['key'] in event_keys, EventManager.get_event_list(filtered_by='today'))
        print(events)
        user = UserManager.get_user_friendly(id =user_id)

        if not user_id or not email:
            logging.debug('NO POST DATAS PROVIDED')
            return
        html_email = self.get_html_email(user, events)
        subject = self.get_subject(user)
        non_html_email = self.get_non_html_email(user)

        from main import debug
        if not debug:
            sender.send('EventBuck Rappel','reminder@eventbuck.com', subject, text=non_html_email, html=html_email,
                        receiver_email=email, receiver_name=user['fullname'])
            memcache.add_daily_sent(user_id)

    def get_html_email(self, user, events):
        return jinja_environment.get_template('ebdigest.html').render({'event_list': events,
                                                                       'user':user,
                                                                       'subject':self.get_subject(user)
                                                                       })
    def get_non_html_email(self, user):

        email = u"""
    {}, Visites ce lien pour voir les events qui auront lieu cette semaine sur EventBuck!

        www.eventbuck.com

    """.format(user['firstname'] if user['type']=='student' else user['fullname'])

        return email
    def get_subject(self, user):
        return u"{}, Rappel des events à participer!".format(user['firstname'] if user['type']=='student' else user['fullname'])