text:
"""Test descriptor wallet function."""

from test_framework.blocktools import COINBASE_MATURITY
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    assert_raises_rpc_error
)

class WalletDescriptorTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1
        self.extra_args = [['-keypool=100']]
        self.wallet_names = []

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()
        self.skip_if_no_sqlite()

    def run_test(self):
        if self.is_bdb_compiled():
            # Make a legacy wallet and check it is BDB
            self.nodes[0].createwallet(wallet_name="legacy1", descriptors=False)
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(wallet_info['format'], 'bdb')
            self.nodes[0].unloadwallet("legacy1")
        else:
            self.log.warning("Skipping BDB test")

        # Make a descriptor wallet
        self.log.info("Making a descriptor wallet")
        self.nodes[0].createwallet(wallet_name="desc1", descriptors=True)

        # A descriptor wallet should have 100 addresses * 4 types = 400 keys
        self.log.info("Checking wallet info")
        wallet_info = self.nodes[0].getwalletinfo()
        assert_equal(wallet_info['format'], 'sqlite')
        assert_equal(wallet_info['keypoolsize'], 400)
        assert_equal(wallet_info['keypoolsize_hd_internal'], 400)
        assert 'keypoololdest' not in wallet_info

        # Check that getnewaddress works
        self.log.info("Test that getnewaddress and getrawchangeaddress work")
        addr = self.nodes[0].getnewaddress("", "legacy")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('pkh(')
        assert_equal(addr_info['hdkeypath'], 'm/44\'/1\'/0\'/0/0')

        addr = self.nodes[0].getnewaddress("", "p2sh-segwit")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('sh(wpkh(')
        assert_equal(addr_info['hdkeypath'], 'm/49\'/1\'/0\'/0/0')

        addr = self.nodes[0].getnewaddress("", "bech32")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('wpkh(')
        assert_equal(addr_info['hdkeypath'], 'm/84\'/1\'/0\'/0/0')

        # Check that getrawchangeaddress works
        addr = self.nodes[0].getrawchangeaddress("legacy")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('pkh(')
        assert_equal(addr_info['hdkeypath'], 'm/44\'/1\'/0\'/1/0')

        addr = self.nodes[0].getrawchangeaddress("p2sh-segwit")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('sh(wpkh(')
        assert_equal(addr_info['hdkeypath'], 'm/49\'/1\'/0\'/1/0')

        addr = self.nodes[0].getrawchangeaddress("bech32")
        addr_info = self.nodes[0].getaddressinfo(addr)
        assert addr_info['desc'].startswith('wpkh(')
        assert_equal(addr_info['hdkeypath'], 'm/84\'/1\'/0\'/1/0')

        # Make a wallet to receive coins at
        self.nodes[0].createwallet(wallet_name="desc2", descriptors=True)
        recv_wrpc = self.nodes[0].get_wallet_rpc("desc2")
        send_wrpc = self.nodes[0].get_wallet_rpc("desc1")

        # Generate some coins
        self.generatetoaddress(self.nodes[0], COINBASE_MATURITY + 1, send_wrpc.getnewaddress())

        # Make transactions
        self.log.info("Test sending and receiving")
        addr = recv_wrpc.getnewaddress()
        send_wrpc.sendtoaddress(addr, 10)

        # Make sure things are disabled
        self.log.info("Test disabled RPCs")
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.importprivkey, "cVpF924EspNh8KjYsfhgY96mmxvT6DgdWiTYMtMjuM74hJaU5psW")
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.importpubkey, send_wrpc.getaddressinfo(send_wrpc.getnewaddress()))
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.importaddress, recv_wrpc.getnewaddress())
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.importmulti, [])
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.addmultisigaddress, 1, [recv_wrpc.getnewaddress()])
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.dumpprivkey, recv_wrpc.getnewaddress())
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.dumpwallet, 'wallet.dump')
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.importwallet, 'wallet.dump')
        assert_raises_rpc_error(-4, "Only legacy wallets are supported by this command", recv_wrpc.rpc.sethdseed)

        self.log.info("Test encryption")
        # Get the master fingerprint before encrypt
        info1 = send_wrpc.getaddressinfo(send_wrpc.getnewaddress())

        # Encrypt wallet 0
        send_wrpc.encryptwallet('pass')
        send_wrpc.walletpassphrase('pass', 10)
        addr = send_wrpc.getnewaddress()
        info2 = send_wrpc.getaddressinfo(addr)
        assert info1['hdmasterfingerprint'] != info2['hdmasterfingerprint']
        send_wrpc.walletlock()
        assert 'hdmasterfingerprint' in send_wrpc.getaddressinfo(send_wrpc.getnewaddress())
        info3 = send_wrpc.getaddressinfo(addr)
        assert_equal(info2['desc'], info3['desc'])

        self.log.info("Test that getnewaddress still works after keypool is exhausted in an encrypted wallet")
        for _ in range(500):
            send_wrpc.getnewaddress()

        self.log.info("Test that unlock is needed when deriving only hardened keys in an encrypted wallet")
        send_wrpc.walletpassphrase('pass', 10)
        send_wrpc.importdescriptors([{
            "desc": "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/*h)#y4dfsj7n",
            "timestamp": "now",
            "range": [0,10],
            "active": True
        }])
        send_wrpc.walletlock()
        # Exhaust keypool of 100
        for _ in range(100):
            send_wrpc.getnewaddress(address_type='bech32')
        # This should now error
        assert_raises_rpc_error(-12, "Keypool ran out, please call keypoolrefill first", send_wrpc.getnewaddress, '', 'bech32')

        self.log.info("Test born encrypted wallets")
        self.nodes[0].createwallet('desc_enc', False, False, 'pass', False, True)
        enc_rpc = self.nodes[0].get_wallet_rpc('desc_enc')
        enc_rpc.getnewaddress() # Makes sure that we can get a new address from a born encrypted wallet

        self.log.info("Test blank descriptor wallets")
        self.nodes[0].createwallet(wallet_name='desc_blank', blank=True, descriptors=True)
        blank_rpc = self.nodes[0].get_wallet_rpc('desc_blank')
        assert_raises_rpc_error(-4, 'This wallet has no available keys', blank_rpc.getnewaddress)

        self.log.info("Test descriptor wallet with disabled private keys")
        self.nodes[0].createwallet(wallet_name='desc_no_priv', disable_private_keys=True, descriptors=True)
        nopriv_rpc = self.nodes[0].get_wallet_rpc('desc_no_priv')
        assert_raises_rpc_error(-4, 'This wallet has no available keys', nopriv_rpc.getnewaddress)

        self.log.info("Test descriptor exports")
        self.nodes[0].createwallet(wallet_name='desc_export', descriptors=True)
        exp_rpc = self.nodes[0].get_wallet_rpc('desc_export')
        self.nodes[0].createwallet(wallet_name='desc_import', disable_private_keys=True, descriptors=True)
        imp_rpc = self.nodes[0].get_wallet_rpc('desc_import')

        addr_types = [('legacy', False, 'pkh(', '44\'/1\'/0\'', -13),
                      ('p2sh-segwit', False, 'sh(wpkh(', '49\'/1\'/0\'', -14),
                      ('bech32', False, 'wpkh(', '84\'/1\'/0\'', -13),
                      ('legacy', True, 'pkh(', '44\'/1\'/0\'', -13),
                      ('p2sh-segwit', True, 'sh(wpkh(', '49\'/1\'/0\'', -14),
                      ('bech32', True, 'wpkh(', '84\'/1\'/0\'', -13)]

        for addr_type, internal, desc_prefix, deriv_path, int_idx in addr_types:
            int_str = 'internal' if internal else 'external'

            self.log.info("Testing descriptor address type for {} {}".format(addr_type, int_str))
            if internal:
                addr = exp_rpc.getrawchangeaddress(address_type=addr_type)
            else:
                addr = exp_rpc.getnewaddress(address_type=addr_type)
            desc = exp_rpc.getaddressinfo(addr)['parent_desc']
            assert_equal(desc_prefix, desc[0:len(desc_prefix)])
            idx = desc.index('/') + 1
            assert_equal(deriv_path, desc[idx:idx + 9])
            if internal:
                assert_equal('1', desc[int_idx])
            else:
                assert_equal('0', desc[int_idx])

            self.log.info("Testing the same descriptor is returned for address type {} {}".format(addr_type, int_str))
            for i in range(0, 10):
                if internal:
                    addr = exp_rpc.getrawchangeaddress(address_type=addr_type)
                else:
                    addr = exp_rpc.getnewaddress(address_type=addr_type)
                test_desc = exp_rpc.getaddressinfo(addr)['parent_desc']
                assert_equal(desc, test_desc)

            self.log.info("Testing import of exported {} descriptor".format(addr_type))
            imp_rpc.importdescriptors([{
                'desc': desc,
                'active': True,
                'next_index': 11,
                'timestamp': 'now',
                'internal': internal
            }])

            for i in range(0, 10):
                if internal:
                    exp_addr = exp_rpc.getrawchangeaddress(address_type=addr_type)
                    imp_addr = imp_rpc.getrawchangeaddress(address_type=addr_type)
                else:
                    exp_addr = exp_rpc.getnewaddress(address_type=addr_type)
                    imp_addr = imp_rpc.getnewaddress(address_type=addr_type)
                assert_equal(exp_addr, imp_addr)

if __name__ == '__main__':
    WalletDescriptorTest().main ()


text:
package com.lordrhys.mod.block;

import javax.swing.Icon;

import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.BlockFluidClassic;

import com.lordrhys.mod.LordRhysModMain;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockLightLiquid extends BlockFluidClassic
{
   @SideOnly(Side.CLIENT)
   protected static IIcon[] theIcon;

   public BlockLightLiquid()
   {
	  super(LordRhysModMain.lightFluid, Material.water);
	  this.setCreativeTab(LordRhysModMain.energyTab);
   }

   @SideOnly(Side.CLIENT)
   public IIcon getIcon(int side, int metadata)
   {
	   return side != 0 && side != 1 ? this.theIcon[1] : this.theIcon[0];
   }

   @SideOnly(Side.CLIENT)
   public void registerBlockIcons(IIconRegister iconRegister)
   {
       this.theIcon = new IIcon[] {iconRegister.registerIcon(LordRhysModMain.modid + ":liquidLight_still"), iconRegister.registerIcon(LordRhysModMain.modid + ":liquidLight_flow")};

   }

   @SideOnly(Side.CLIENT)
   public static IIcon getFluidIcon(String par0Str)
   {
       return par0Str == "liquidLight_still" ? theIcon[0] : (par0Str == "liquidLight_flow" ? theIcon[1] :  null);
   }
}

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.json.bvt.serializer.filters;

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

import org.junit.Assert;
import junit.framework.TestCase;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class PropertyFilter_byte extends TestCase {

    public void test_0() throws Exception {
        PropertyFilter filter = new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                return false;
            }
        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(filter);

        A a = new A();
        serializer.write(a);

        String text = out.toString();
        Assert.assertEquals("{}", text);
    }

    public void test_1() throws Exception {
        PropertyFilter filter = new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                if ("id".equals(name)) {
                    Assert.assertTrue(value instanceof Byte);
                    return true;
                }
                return false;
            }
        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(filter);

        A a = new A();
        serializer.write(a);

        String text = out.toString();
        Assert.assertEquals("{\"id\":0}", text);
    }

    public void test_2() throws Exception {
        PropertyFilter filter = new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                if ("name".equals(name)) {
                    return true;
                }
                return false;
            }
        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(filter);

        A a = new A();
        a.setName("chennp2008");
        serializer.write(a);

        String text = out.toString();
        Assert.assertEquals("{\"name\":\"chennp2008\"}", text);
    }

    public void test_3() throws Exception {
        PropertyFilter filter = new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                if ("name".equals(name)) {
                    return true;
                }
                return false;
            }
        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(filter);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "chennp2008");
        serializer.write(map);

        String text = out.toString();
        Assert.assertEquals("{\"name\":\"chennp2008\"}", text);
    }

    public void test_4() throws Exception {
        PropertyFilter filter = new PropertyFilter() {

            public boolean apply(Object source, String name, Object value) {
                if ("name".equals(name)) {
                    return false;
                }
                return true;
            }
        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getPropertyFilters().add(filter);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 3);
        map.put("name", "chennp2008");
        serializer.write(map);

        String text = out.toString();
        Assert.assertEquals("{\"id\":3}", text);
    }

    public static class A {

        private byte    id;
        private String name;

        public byte getId() {
            return id;
        }

        public void setId(byte id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }
}


text:
sf-lynx is a simple log viewer for records from Salesforce.com.

Provies two ways to fetch the data:
1. Data that resides in Heroku connect / Postgres DB
2. Data fetch using Streaming API from a push topic

### Data that resides in Heroku connect / Postgres DB
<TODO>

### Data fetch using Streaming API from a push topic
Needs STREAMING_TOPIC_NAME environment var


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Crap Engine 2: crap::DirectoryListener Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Crap Engine 2

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

crap

DirectoryListener

Public Types |
Public Member Functions |
List of all members

crap::DirectoryListener Class Reference

#include <directorylistener.h>

Public Types

typedef crap::delegate< void(const char *) > 	DirectoryFunction

typedef array< DirectoryFunction > 	FunctionArray

typedef array_map< string_hash, uint64_t > 	FileMap

Public Member Functions

 	DirectoryListener (uint32_t max_functions, uint32_t max_files, const string256 &path, bool recursive=false)

 	~DirectoryListener (void)

template<class C , void(C::*)(const char *) F>

void 	addCallback (C *instance)

template<void(*)(const char *) F>

void 	addCallback (void)

template<class C , void(C::*)(const char *) F>

void 	removeCallback (C *instance)

template<void(*)(const char *) F>

void 	removeCallback (void)

CRAP_INLINE void 	init (void)

bool 	update (uint32_t deltatime)

Detailed Description

Definition at line 36 of file directorylistener.h.

Member Typedef Documentation

          typedef crap::delegate< void (const char*) > crap::DirectoryListener::DirectoryFunction

Definition at line 40 of file directorylistener.h.

          typedef array_map< string_hash, uint64_t > crap::DirectoryListener::FileMap

Definition at line 42 of file directorylistener.h.

          typedef array<DirectoryFunction> crap::DirectoryListener::FunctionArray

Definition at line 41 of file directorylistener.h.

Constructor & Destructor Documentation

          crap::DirectoryListener::DirectoryListener
          (
          uint32_t
          max_functions,

          uint32_t
          max_files,

          const string256 &
          path,

          bool
          recursive = false

          )

Definition at line 19 of file directorylistener.cpp.

          crap::DirectoryListener::~DirectoryListener
          (
          void
          	)

Definition at line 29 of file directorylistener.cpp.

Member Function Documentation

template<class C , void(C::*)(const char *) F>

          void crap::DirectoryListener::addCallback
          (
          C *
          instance	)

Definition at line 77 of file directorylistener.h.

template<void(*)(const char *) F>

          void crap::DirectoryListener::addCallback
          (
          void
          	)

Definition at line 85 of file directorylistener.h.

          CRAP_INLINE void crap::DirectoryListener::init
          (
          void
          	)

inline

Definition at line 60 of file directorylistener.h.

template<class C , void(C::*)(const char *) F>

          void crap::DirectoryListener::removeCallback
          (
          C *
          instance	)

Definition at line 93 of file directorylistener.h.

template<void(*)(const char *) F>

          void crap::DirectoryListener::removeCallback
          (
          void
          	)

Definition at line 105 of file directorylistener.h.

          bool crap::DirectoryListener::update
          (
          uint32_t
          deltatime	)

Definition at line 94 of file directorylistener.cpp.

The documentation for this class was generated from the following files:

/mnt/windows/data/programming/crapengine2/source/engine/include/directorylistener.h

/mnt/windows/data/programming/crapengine2/source/engine/source/directorylistener.cpp

<address class="footer">
Generated on Wed Jan 7 2015 21:59:10 for Crap Engine 2 by

 1.8.9.1
</address>


text:
puts 'Give me your first name.'
first_name = gets.chomp
puts 'And your middle name.'
middle_name = gets.chomp
puts 'And your last name.'
last_name = gets.chomp
puts 'Cool. Your name is ' + first_name + ' ' + middle_name + ' ' + last_name + '.'

# Bigger, better favorite number: Write a program that asks for a person's favorite number. Have your program add 1 to the number, and then suggest the result as a bigger and better number.

puts 'Give me your favorite number.'
favnum = gets.chomp
bigger_num = favnum.to_i + 1
puts 'Are you sure you don\'t prefer ' + bigger_num.to_s + '?'

=begin

4.3.1 Return a Formatted Address: https://github.com/nataliecodes/phase-0/blob/master/week-4/address/my_solution.rb
4.3.2 Defining Math Methods: https://github.com/nataliecodes/phase-0/blob/master/week-4/define-method/my_solution.rb

How do you define a local variable?

  You type in the name of the variable (must start with a lowercase letter or an underscore) and set it equal to a value. That value can be any letters and numbers you want. Make sure you put the variable on the lefthand side of the equal sign, and the value to the right.

How do you define a method?

  Defining a new method has to have at least these parts: "def" + "[name of method]" + [code (or you can leave this part empty)] + "end". Any method needs an "object," which can be a string, integer, etc. with other methods inside of it (like puts or gets.chomp).

What is the difference between a local variable and a method?

  A local variable is an assigned value and can be a string, integer, float, etc. A method uses variables as objects. i.e. the "puts" method will output a string if you code "puts 'this is a string'"

How do you run a ruby program from the command line?

  Type in "ruby [name of file].rb" and hit enter. You want to navigate to the directory of that file in order to run it (you may have files named the same thing in different folders).

How do you run an RSpec file from the command line?

  Type in "rspec [name of file].rb" and hit enter. Again, you want to be sure you've navigated to the directory of that file first.

What was confusing about this material? What made sense?

  Confusing: I didn't realize that I had to put a period at the end of the address string. It took me a while to figure it out. I think that it's important to really know what each variable means so that when you get an error, you can go back to the basics and check those first. You have to spell out every. single. instruction. for the computer.

  Sensical: Once I researched things and found a solution, they did make sense and my confusion lifted. I also think that strings, floats and integers and the 10 methods we've learned (puts, gets, =, etc.) all make sense.

=end


text:
package lahija.papelprenshija.factory;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

import javax.imageio.ImageIO;

import lahija.papelprenshija.model.FrontPage;
import lahija.papelprenshija.model.exception.SystemException;
import lahija.papelprenshija.model.params.FrontPageInstanceParams;
import lahija.papelprenshija.model.template.INewspaperTemplate;
import lahija.papelprenshija.model.template.components.BackgroundTemplate;
import lahija.papelprenshija.model.template.components.TextSection;
import lahija.papelprenshija.model.template.components.TextSectionFont;
import lahija.papelprenshija.model.template.components.abstractions.TwoDimensionsValues;

/**
 * Front page image representation factory for a giving Newspaper template and params.
 *
 * @author rsilva
 *
 */
public class FrontPageImageRepresentationFactory {

   /** news paper template to create front pages from */
   private final INewspaperTemplate template;

   /** Convenient/handy instance variable. Is the same as it comes inside {@link #template} */
   private final BackgroundTemplate backgroundTemplate;

   /** Front Page Instance parameters*/
   private final FrontPageInstanceParams params;

   /** awt java object calculated when create a front page. It is needed to do all the awt magic stuff */
   private Graphics2D frontPageGraphics;

   /**
    *
    * @param frontPage to build from
    */
   public FrontPageImageRepresentationFactory(final FrontPage frontPage) {
      this.params = frontPage.getInstanceParams();
      this.template = frontPage.getNewspaperTemplate();
      this.backgroundTemplate = this.template.getBackgroundTemplate();
   }

   /**
    *
    * @return
    * @throws IOException
    */
   public BufferedImage createFrontPageImageRepresentation() {
      final BufferedImage frontPageImageRepresentation = this.getFrontPageImageRepresentation();
      this.createGraphics(frontPageImageRepresentation);
      this.paintImage(this.params);
      this.writeTitle(this.params);
      this.writeSubtitle(this.params);
      if (this.template.hasImageCaption()) {
         this.writeCaption(this.params);
      }

      return frontPageImageRepresentation;
   }

   /**
    * Reads background image template or newspaper image template.
    *
    * @return
    * @throws IOException
    */
   private BufferedImage getFrontPageImageRepresentation() {
      try {
         return ImageIO.read(new File(this.backgroundTemplate.getPath()));
      } catch (final IOException e) {
         throw new SystemException("Application Error. Fail to read background file at: " + this.backgroundTemplate.getPath() + " Try to "
                  + "reinstall the application from scratch.", e);
      }
   }

   /**
    * Creates internal graphics {@link #frontPageGraphics} and configures it.
    *
    * @param frontPage buffered image to creates graphics from.
    *
    */
   private void createGraphics(final BufferedImage frontPage) {
      this.frontPageGraphics = frontPage.createGraphics();
      this.frontPageGraphics.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
               RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
      this.frontPageGraphics.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,
               RenderingHints.VALUE_RENDER_QUALITY));
   }

   /**
    * Writes title section
    *
    * @param params
    */
   private void writeTitle(final FrontPageInstanceParams params) {
      final Font font = this.calculateTitleFont(params);
      final TextSection titleSection = this.template.getTitleSection();
      this.writeTextTo(params.getTile(), font, titleSection.getTextCoordinates(), titleSection.getTextWidth(),
               titleSection.getTextLeading());
   }

   /**
    * Calculates best font to use for title section.
    *
    * @param params
    * @return
    */
   private Font calculateTitleFont(final FrontPageInstanceParams params) {
      final Integer fontSize = this.calculateTitleFontSize(params.getTile());
      final TextSectionFont textFont = this.template.getTitleSection().getTextFont();

      return new Font(textFont.getFontName(), textFont.getFontStyle(), fontSize);
   }

   /**
    * Returns font size to use for title given text title. It "tests" writing text and checking how many lines was made.
    *
    * @return
    */
   private Integer calculateTitleFontSize(final String title) {
      final TextSection titleSection = this.template.getTitleSection();
      final TextSectionFont textFont = titleSection.getTextFont();
      final Font testingFont = new Font(textFont.getFontName(), textFont.getFontStyle(), textFont.getSmallSize());

      final Double linesUsingBigFontSize =
               testingFont.getStringBounds(title, this.frontPageGraphics.getFontRenderContext()).getWidth()
                        / titleSection.getTextWidth();
      if (linesUsingBigFontSize > 2) {
         return textFont.getSmallSize();
      } else {
         return textFont.getBigSize();
      }
   }

   /**
    * Writes caption section.
    *
    * @param params
    */
   private void writeCaption(final FrontPageInstanceParams params) {
      this.writeToSectionUsingSmallFont(this.template.getImageCaption(), params.getCaption());
   }

   /**
    * Write subtitle section
    *
    * @param params
    */
   private void writeSubtitle(final FrontPageInstanceParams params) {
      this.writeToSectionUsingSmallFont(this.template.getSubtitleSection(), params.getSubtitle());
   }

   /**
    * Writes text on specific {@link TextSection} using {@link TextSection} small font only
    * @param section
    * @param text
    */
   private void writeToSectionUsingSmallFont(final TextSection section, final String text) {
      final TextSectionFont textFont = section.getTextFont();
      final Font font = new Font(textFont.getFontName(), textFont.getFontStyle(), textFont.getSmallSize());
      this.writeTextTo(text, font, section.getTextCoordinates(), section.getTextWidth(), section.getTextLeading());
   }

   /**
    * Prints image in background template.
    *
    * @param params
    */
   private void paintImage(final FrontPageInstanceParams params) {
      final BufferedImage image = params.getImage();
      final TwoDimensionsValues pictureScale = this.backgroundTemplate.getPictureScale();
      final TwoDimensionsValues pictureCoordinates = this.backgroundTemplate.getPictureCoordinates();
      final Image scaledPhoto = image.getScaledInstance(pictureScale.getX(), pictureScale.getY(), Image.SCALE_SMOOTH);

      this.frontPageGraphics.drawImage(scaledPhoto, pictureCoordinates.getX(), pictureCoordinates.getY(), null);
   }

   /**
    * Writes text to given coordinates
    *
    * @param inputText text to write
    * @param font to use
    * @param coordinates where write
    * @param width horizontal boundaries
    * @param leading text leading property
    */
   private void writeTextTo(final String inputText, final Font font, final TwoDimensionsValues coordinates, final int width,
            final int leading) {
      final AttributedString as = new AttributedString(inputText);
      as.addAttribute(TextAttribute.FONT, font);
      as.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);

      final AttributedCharacterIterator characterIterator = as.getIterator();
      final FontRenderContext fontRenderContext = this.frontPageGraphics.getFontRenderContext();
      final LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, fontRenderContext);

      int verticalTempCoordinate = coordinates.getY();
      while (measurer.getPosition() < characterIterator.getEndIndex()) {
         final TextLayout textLayout = measurer.nextLayout(width);
         verticalTempCoordinate += textLayout.getAscent() + leading;
         textLayout.draw(this.frontPageGraphics, coordinates.getX(), verticalTempCoordinate);
         verticalTempCoordinate += textLayout.getDescent() + leading;
      }
   }

}


text:
A offline music player for Windows Phone 8+

# Build and Run
If there are reference errors please re-include the references.
All reference library for this project are inside package folder.


text:
@implementation NSString (cppstring_additions)

#if TARGET_RT_BIG_ENDIAN
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32BE);
#else
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32LE);
#endif

+(NSString*) stringWithwstring:(const std::wstring&)ws
{
    char* data = (char*)ws.data();
    unsigned size = ws.size() * sizeof(wchar_t);

    NSString* result = [[NSString alloc] initWithBytes:data length:size encoding:kEncoding_wchar_t];
    return result;
}
+(NSString*) stringWithstring:(const std::string&)s
{
    NSString* result = [[NSString alloc] initWithUTF8String:s.c_str()];
    return result;
}

-(std::wstring) getwstring
{
    NSData* asData = [self dataUsingEncoding:kEncoding_wchar_t];
    return std::wstring((wchar_t*)[asData bytes], [asData length] / sizeof(wchar_t));
}
-(std::string) getstring
{
    return [self UTF8String];
}

@end


text:
package scouter.client.maria.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import scouter.client.maria.views.DbRealtimeTotalResponseView;
import scouter.client.util.ConsoleProxy;

public class OpenDbRealtimeResponseAction extends Action {

	final private int serverId;

	public OpenDbRealtimeResponseAction(int serverId) {
		this.serverId = serverId;
		setText("Response Time");
	}

	public void run() {
		try {
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(DbRealtimeTotalResponseView.ID, ""+serverId, IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e) {
			ConsoleProxy.errorSafe(e.toString());
		}
	}
}


text:
/**
 *
 */
package com.filelocker.encryption;

/** *********************************************************************************
 * TITLE        : THE CLASS TO CREATE THE AES PASSWORD ENCRYPTION LOGIC
 * AUTHOR       : RK10R04A01;11000527;ANUBHAV ARUN GUPTA
 * DATE/TIME    : AD 2013.07.30.13.12
 * IDE       	: Kepler Release Build id: 20130614-0229
 * JAVA VERSION : 1.7.0_25
 * JRE          : java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b16)
 * ************************************************************************************* */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class AES_Encryption
{
	String vPassword = null;
	public final static int SALT_LEN = 8;
	byte [] vInitVec = null;
	byte [] vSalt = null;
	Cipher vEcipher = null;
	Cipher vDecipher = null;
	private final int KEYLEN_BITS = 128;
	private final int ITERATIONS = 65536;
	private final int MAX_FILE_BUF = 1024;

	/**
	 * create an object with just the passphrase from the user.
	 * @param password
	 */
	public AES_Encryption (String password)
	{
		vPassword = password;
	}

	/**
	 * return the generated salt for this object
	 * @return
	 */
	public byte [] getSalt ()
	{
		return (vSalt);
	}

	/**
	 * return the initialization vector created from setupEncryption
	 * @return
	 */
	public byte [] getInitVec ()
	{
		return (vInitVec);
	}

	/**
	 * debug/print messages
	 * @param msg
	 */
	private void Db (String msg)
	{
		System.out.println ("** Crypt ** " + msg);
	}

	/**
	 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
	 * and generates the salt bytes using secureRandom().  The encryption secret key is created
	 * along with the initialization vectory. The member variable vEcipher is created to be used
	 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
	 * to be written to disk.
	 *
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 * @throws NoSuchPaddingException
	 * @throws InvalidParameterSpecException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidKeyException
	 */
	public void setupEncrypt () throws NoSuchAlgorithmException,
	InvalidKeySpecException,
	NoSuchPaddingException,
	InvalidParameterSpecException,
	IllegalBlockSizeException,
	BadPaddingException,
	UnsupportedEncodingException,
	InvalidKeyException
	{
		SecretKeyFactory factory = null;
		SecretKey tmp = null;

		// crate secureRandom salt and store  as member var for later use
		vSalt = new byte [SALT_LEN];
		SecureRandom rnd = new SecureRandom ();
		rnd.nextBytes (vSalt);
		Db ("generated salt :" + Hex.encodeHexString (vSalt));

		factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

		/* Derive the key, given password and salt.
		 *
		 * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
		 * The end user must also install them (not compiled in) so beware.
		 * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
		 */
		KeySpec spec = new PBEKeySpec (vPassword.toCharArray (), vSalt, ITERATIONS, KEYLEN_BITS);
		tmp = factory.generateSecret (spec);
		SecretKey secret = new SecretKeySpec (tmp.getEncoded(), "AES");

		/* Create the Encryption cipher object and store as a member variable
		 */
		vEcipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
		vEcipher.init (Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = vEcipher.getParameters ();

		// get the initialization vectory and store as member var
		vInitVec = params.getParameterSpec (IvParameterSpec.class).getIV();

		Db ("vInitVec is :" + Hex.encodeHexString (vInitVec));
	}

	/**
	 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
	 * We have the password from initializing the class. pass the iv and salt here which is
	 * obtained when encrypting the file initially.
	 *
	 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 * @throws InvalidAlgorithmParameterException
	 * @throws DecoderException
	 * @throws IOException
	 */
	public void setupDecrypt (File inFile) throws NoSuchAlgorithmException,
	InvalidKeySpecException,
	NoSuchPaddingException,
	InvalidKeyException,
	InvalidAlgorithmParameterException,
	DecoderException,
	IOException
	{
		SecretKeyFactory factory = null;
		SecretKey tmp = null;
		SecretKey secret = null;

		byte[] vSalt = new byte[8];
		byte[] vInitVec = new byte[16];

		RandomAccessFile vFile = new RandomAccessFile(inFile,"rw");

		//The last 8 bits are salt so seek to length of file minus 9 bits
		vFile.seek(vFile.length()-8);
		vFile.readFully(vSalt);

		//The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
		//Thus to seek to length of file minus 24 bits
		vFile.seek(vFile.length()-24);
		vFile.readFully(vInitVec);
		vFile.seek(0);

		File tmpFile = new File(inFile.getAbsolutePath()+".tmpEncryption.file");

		RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile,"rw");

		for(int i=0; i<(vFile.length()-24);++i)
		{
			vTmpFile.write(vFile.readByte());
		}
		vFile.close();
		vTmpFile.close();

		inFile.delete();
		tmpFile.renameTo(inFile);

		Db ("got salt " + Hex.encodeHexString (vSalt));

		Db ("got initvector :" + Hex.encodeHexString (vInitVec));

		/* Derive the key, given password and salt. */
		// in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
		// The end user must also install them (not compiled in) so beware.
		// see here:
		// http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
		// PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
		//found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

		factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		KeySpec spec = new PBEKeySpec(vPassword.toCharArray (), vSalt, ITERATIONS, KEYLEN_BITS);

		tmp = factory.generateSecret(spec);
		secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		// Decrypt the message, given derived key and initialization vector.
		vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
	}

	/**
	 * This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
	 * Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
	 *
	 * @param input - the cleartext file to be encrypted
	 * @param output - the encrypted data file
	 * @throws IOException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public void WriteEncryptedFile (File input, File output) throws
	IOException,
	IllegalBlockSizeException,
	BadPaddingException
	{
		FileInputStream fin;
		FileOutputStream fout;
		long totalread = 0;
		int nread = 0;
		byte [] inbuf = new byte [MAX_FILE_BUF];

		fout = new FileOutputStream (output);
		fin = new FileInputStream (input);

		while ((nread = fin.read (inbuf)) > 0 )
		{
			Db ("read " + nread + " bytes");
			totalread += nread;

			// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
			// and results in full blocks of MAX_FILE_BUF being written.
			byte [] trimbuf = new byte [nread];
			for (int i = 0; i < nread; i++)
				trimbuf[i] = inbuf[i];

			// encrypt the buffer using the cipher obtained previously
			byte [] tmp = vEcipher.update (trimbuf);

			// I don't think this should happen, but just in case..
			if (tmp != null)
				fout.write (tmp);
		}

		// finalize the encryption since we've done it in blocks of MAX_FILE_BUF
		byte [] finalbuf = vEcipher.doFinal ();
		if (finalbuf != null)
			fout.write (finalbuf);

		fout.write(vInitVec);
		fout.write(vSalt);
		fout.flush();
		fin.close();
		fout.close();
		fout.close();

		Db ("wrote " + totalread + " encrypted bytes");
		Db ("Encryption Complete File Locked");
	}

	/**
	 * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
	 * to disk as (output) File.
	 *
	 * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
	 *  and still have a correctly decrypted file in the end. Seems to work so left it in.
	 *
	 * @param input - File object representing encrypted data on disk
	 * @param output - File object of cleartext data to write out after decrypting
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws IOException
	 */
	public void ReadEncryptedFile (File input, File output) throws
	IllegalBlockSizeException,
	BadPaddingException,
	IOException
	{
		FileInputStream fin;
		FileOutputStream fout;
		CipherInputStream cin;
		long totalread = 0;
		int nread = 0;
		byte [] inbuf = new byte [MAX_FILE_BUF];

		fout = new FileOutputStream (output);
		fin = new FileInputStream (input);

		// creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
		cin = new CipherInputStream (fin, vDecipher);

		while ((nread = cin.read (inbuf)) > 0 )
		{
			Db ("read " + nread + " bytes");
			totalread += nread;

			// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
			byte [] trimbuf = new byte [nread];
			for (int i = 0; i < nread; i++)
				trimbuf[i] = inbuf[i];

			// write out the size-adjusted buffer
			fout.write (trimbuf);
		}

		fout.flush();
		cin.close();
		fin.close ();
		fout.close();

		Db ("wrote " + totalread + " dencrypted bytes");
		Db ("Decryption Complete File Unlocked");
	}

}


text:
@class WFDistanceFormatter;

@interface WFHeightPicker : UIPickerView <UIPickerViewDataSource, UIPickerViewDelegate>
{
    id <WFHeightPickerDelegate> _heightDelegate;
    WFDistanceFormatter *_feetFormatter;
    WFDistanceFormatter *_inchesFormatter;
    double _height;
}

@property(retain, nonatomic) WFDistanceFormatter *inchesFormatter; // @synthesize inchesFormatter=_inchesFormatter;
@property(retain, nonatomic) WFDistanceFormatter *feetFormatter; // @synthesize feetFormatter=_feetFormatter;
@property(nonatomic) __weak id <WFHeightPickerDelegate> heightDelegate; // @synthesize heightDelegate=_heightDelegate;
@property(nonatomic) double height; // @synthesize height=_height;
- (void).cxx_destruct;
- (id)pickerView:(id)arg1 titleForRow:(int)arg2 forComponent:(int)arg3;
- (int)pickerView:(id)arg1 numberOfRowsInComponent:(int)arg2;
- (int)numberOfComponentsInPickerView:(id)arg1;
- (void)pickerView:(id)arg1 didSelectRow:(int)arg2 inComponent:(int)arg3;
- (id)init;

@end


text:
rejourn is a static site generator for programmers. Just write an
article in a markup language of your choice, and some metadata
information like author/ date; rejourn takes care of the rest.

## Dependencies
* Mako Python bindings
* Markdown Python bindings [optional: for markdown rendering]
* Nose [optional: for running included tests]

## Features
* Markdown and Asciidoc. It can easily be extended to support more
  markup languages- simply write a tranform function and add it to the
  'htransform_mapper' in 'util.py'.
* Dependencies handled by Makefile. This means that an output HTML
  file will not be built unless and until the corresponding input file
  changes.
* Drafts. The 'draft' metadata header controls whether the output
  should be built.
* Static pages. For pages in the toplevel index like "About
  me". Controlled by 'static' metadata header.
* Configurable views. The template to render with the given content is
  controlled by a simple 'view_mapper' in 'util.py'.
* Tags. You can assign associate multiple freeform tags to a single
  article, and view all articles with a certain tag. Controlled by
  'tags' metadata header.
* Cache. No article is ever unnecessarily rebuilt- the content is
  hashed and stored in the 'cache' subdirectory to recall at a later
  time. This is especially useful when the site has many tags.
* RSS 2.0 feed. Built by default- no extra configuration required.

## Available metadata headers
* title: The title.
* author: The author.
* snip: A short description of the article.  Appears in index.
* view: The design view to use.  Can be single, index, or rss.
* htransform: The filter to pass the content through.  Can be
  "markdown", "asciidoc", or "html".
* tags: The tags the post should be associated with.
* static: A boolean specifying whether the page should appear in the
  index.  Useful for "about" pages.
* draft: A boolean specifying whether the page should be built.
* permalink: The permalink.  Automatically written when built.
* pubdate: The date of publishing.  Automatically written when built.

## Usage
Copy core.cfg.example as core.cfg and modify it to set the indir, outdir and
possibly other options. Run the `configure` script to generate the Makefile;
then run `make` to produce the actual HTML pages in outdir. Run `make test` to
run the included tests.

When an existing input file is modified, run `make` to update the
output file. When the Makefile needs to be regenerated to build new
input files, run the `configure` script to regenerate it.

Use Apache's mod_rewrite (or the corresponding feature in your
webserver) to append '.html' at the end of URLs to access the
corresponding physical files. All links generated by rejourn assume
this configuration.

## Contributing
Simply fork the project on GitHub and send pull requests.


text:
class Boost159 < Formula
  desc "Collection of portable C++ source libraries"
  homepage "http://www.boost.org"
  url "https://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.bz2"
  sha256 "727a932322d94287b62abb1bd2d41723eec4356a7728909e38adb65ca25241ca"

  bottle do
    cellar :any
    sha256 "0eed018a20e25f55ff029376a899f3b73817d9a49fafae0c9488689d27cd3643" => :el_capitan
    sha256 "7d90dac3983b8ae5e844396d0baf43e365b79b4040829fdbaa925c5916649654" => :yosemite
    sha256 "a7f928a08e8add78570ab19ab54d78211c754ed0947ee5aa9d6896b10cdccb04" => :mavericks
  end

  keg_only "Conflicts with boost in main repository."

  option :universal
  option "with-icu4c", "Build regexp engine with icu support"
  option "without-single", "Disable building single-threading variant"
  option "without-static", "Disable building static library variant"
  option "with-mpi", "Build with MPI support"
  option :cxx11

  if build.cxx11?
    depends_on "icu4c" => [:optional, "c++11"]
    depends_on "open-mpi" => "c++11" if build.with? "mpi"
  else
    depends_on "icu4c" => :optional
    depends_on mpi: [:cc, :cxx, :optional]
  end

  # Fixed compilation of operator<< into a record ostream, when
  # the operator right hand argument is not directly supported by
  # formatting_ostream. Fixed https://svn.boost.org/trac/boost/ticket/11549
  # from https://github.com/boostorg/log/commit/7da193f.patch
  patch do
    url "https://raw.githubusercontent.com/Homebrew/formula-patches/2ccb6715b3/boost/boost159-questionable-operator.patch"
    sha256 "a49fd7461d9f3b478d2bddac19adca93fe0fabab71ee67e8f140cbd7d42d6870"
  end

  # Fixed missing symbols in libboost_log_setup (on mac/clang)
  # from https://github.com/boostorg/log/commit/870284ed31792708a6139925d00a0aadf46bf09f
  patch do
    url "https://raw.githubusercontent.com/Homebrew/formula-patches/2ccb6715b3/boost/boost159-missing-symbols.patch"
    sha256 "2c3a3bae1691df5f8fce8fbd4e5727d57bd4dd813748b70d7471c855c4f19d1c"
  end

  fails_with :llvm do
    build 2335
    cause "Dropped arguments to functions when linking with boost"
  end

  needs :cxx11 if build.cxx11?

  def install
    # https://svn.boost.org/trac/boost/ticket/8841
    if build.with?("mpi") && build.with?("single")
      raise <<-EOS.undent
        Building MPI support for both single and multi-threaded flavors
        is not supported.  Please use "--with-mpi" together with
        "--without-single".
      EOS
    end

    ENV.universal_binary if build.universal?

    # Force boost to compile with the desired compiler
    open("user-config.jam", "a") do |file|
      file.write "using darwin : : #{ENV.cxx} ;\n"
      file.write "using mpi ;\n" if build.with? "mpi"
    end

    # libdir should be set by --prefix but isn't
    bootstrap_args = ["--prefix=#{prefix}", "--libdir=#{lib}"]

    if build.with? "icu4c"
      icu4c_prefix = Formula["icu4c"].opt_prefix
      bootstrap_args << "--with-icu=#{icu4c_prefix}"
    else
      bootstrap_args << "--without-icu"
    end

    # Handle libraries that will not be built.
    without_libraries = ["python"]

    # The context library is implemented as x86_64 ASM, so it
    # won't build on PPC or 32-bit builds
    # see https://github.com/Homebrew/homebrew/issues/17646
    if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
      without_libraries << "context"
      # The coroutine library depends on the context library.
      without_libraries << "coroutine"
    end

    # Boost.Log cannot be built using Apple GCC at the moment. Disabled
    # on such systems.
    without_libraries << "log" if ENV.compiler == :gcc || ENV.compiler == :llvm
    without_libraries << "mpi" if build.without? "mpi"

    bootstrap_args << "--without-libraries=#{without_libraries.join(",")}"

    # layout should be synchronized with boost-python
    args = ["--prefix=#{prefix}",
            "--libdir=#{lib}",
            "-d2",
            "-j#{ENV.make_jobs}",
            "--layout=tagged",
            "--user-config=user-config.jam",
            "install"]

    if build.with? "single"
      args << "threading=multi,single"
    else
      args << "threading=multi"
    end

    if build.with? "static"
      args << "link=shared,static"
    else
      args << "link=shared"
    end

    args << "address-model=32_64" << "architecture=x86" << "pch=off" if build.universal?

    # Trunk starts using "clang++ -x c" to select C compiler which breaks C++11
    # handling using ENV.cxx11. Using "cxxflags" and "linkflags" still works.
    if build.cxx11?
      args << "cxxflags=-std=c++11"
      if ENV.compiler == :clang
        args << "cxxflags=-stdlib=libc++" << "linkflags=-stdlib=libc++"
      end
    end

    system "./bootstrap.sh", *bootstrap_args
    system "./b2", "headers"
    system "./b2", *args
  end

  def caveats
    s = ""
    # ENV.compiler doesn't exist in caveats. Check library availability
    # instead.
    if Dir["#{lib}/libboost_log*"].empty?
      s += <<-EOS.undent

      Building of Boost.Log is disabled because it requires newer GCC or Clang.
      EOS
    end

    if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
      s += <<-EOS.undent

      Building of Boost.Context and Boost.Coroutine is disabled as they are
      only supported on x86_64.
      EOS
    end

    s
  end

  test do
    (testpath/"test.cpp").write <<-EOS.undent
      #include <boost/algorithm/string.hpp>
      #include <string>
      #include <vector>
      #include <assert.h>
      using namespace boost::algorithm;
      using namespace std;

      int main()
      {
        string str("a,b");
        vector<string> strVec;
        split(strVec, str, is_any_of(","));
        assert(strVec.size()==2);
        assert(strVec[0]=="a");
        assert(strVec[1]=="b");
        return 0;
      }
    EOS
    system ENV.cxx, "test.cpp", "-std=c++1y", "-I#{include}", "-L#{lib}",
                                "-lboost_system", "-o", "test"
    system "./test"
  end
end


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**uid** | **String** | User ID | [optional]
**access_token** | **String** | User token from initial upgrade path request | [optional]
**did** | **String** | Device ID | [optional]


text:
module load cuda/toolkit
module load libxml2
module load cmake

# build and run openacc benchmarks
cd ${HOME}/belief-propagation/src/openacc_benchmark
cmake . -DCMAKE_BUILD_TYPE=Release
make clean && make
rm -f *csv
nvprof --analysis-metrics -o openacc_loopy_edge.nvprof ./openacc_loopy_edge_benchmark


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Sandbox.ModAPI;
using VRage.Game;
using VRage.Game.ModAPI;
using VRage.Utils;

namespace Digi
{
    public static class Log // v1.4
    {
        public static string modName = "UNNAMED";
        public static string modFolder = "UNNAMED";
        public static ulong workshopId = 0;
        public const string LOG_FILE = "info.log";

        private static TextWriter writer = null;
        private static IMyHudNotification notify = null;
        private static readonly StringBuilder cache = new StringBuilder(64);
        private static readonly List<string> preInitMessages = new List<string>(0);
        private static int indent = 0;

        public static void SetUp(string modName, ulong workshopId, string modFolder = null)
        {
            Log.modName = modName;
            Log.modFolder = (modFolder == null ? modName : modFolder);
            Log.workshopId = workshopId;
        }

        public static void Init()
        {
            if(MyAPIGateway.Utilities == null)
            {
                MyLog.Default.WriteLineAndConsole(modName + " Log.Init() called before API was ready!");
                return;
            }

            if(writer != null)
                Close();

            writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(LOG_FILE, typeof(Log));

            if(preInitMessages.Count > 0)
            {
                foreach(var msg in preInitMessages)
                {
                    Log.Error(msg);
                }

                preInitMessages.Clear();
            }

            Info("Initialized");

            cache.Clear();
            cache.Append("DS=").Append(MyAPIGateway.Utilities.IsDedicated);
            cache.Append("; defined=");

#if STABLE
            cache.Append("STABLE, ");
#endif

#if UNOFFICIAL
            cache.Append("UNOFFICIAL, ");
#endif

#if DEBUG
            cache.Append("DEBUG, ");
#endif

#if BRANCH_STABLE
            cache.Append("BRANCH_STABLE, ");
#endif

#if BRANCH_DEVELOP
            cache.Append("BRANCH_DEVELOP, ");
#endif

#if BRANCH_UNKNOWN
            cache.Append("BRANCH_UNKNOWN, ");
#endif

            Info(cache.ToString());
            cache.Clear();
        }

        public static void Close()
        {
            if(writer != null)
            {
                Log.Info("Unloaded.");

                writer.Flush();
                writer.Close();
                writer = null;
            }

            indent = 0;
            cache.Clear();
        }

        public static void IncreaseIndent()
        {
            indent++;
        }

        public static void DecreaseIndent()
        {
            if(indent > 0)
                indent--;
        }

        public static void ResetIndent()
        {
            indent = 0;
        }

        public static void Error(Exception e)
        {
            Error(e.ToString());
        }

        public static void Error(Exception e, string printText)
        {
            Error(e.ToString(), printText);
        }

        public static void Error(string msg)
        {
            Error(msg, modName + " error - open %AppData%/SpaceEngineers/Storage/" + workshopId + "_" + modFolder + "/" + LOG_FILE + " for details");
        }

        public static void Error(string msg, string printText)
        {
            Info("ERROR: " + msg);

            try
            {
                MyLog.Default.WriteLineAndConsole(modName + " error/exception: " + msg);

                if(MyAPIGateway.Session != null)
                {
                    if(notify == null)
                    {
                        notify = MyAPIGateway.Utilities.CreateNotification(printText, 10000, MyFontEnum.Red);
                    }
                    else
                    {
                        notify.Text = printText;
                        notify.ResetAliveTime();
                    }

                    notify.Show();
                }
            }
            catch(Exception e)
            {
                Info("ERROR: Could not send notification to local client: " + e);
                MyLog.Default.WriteLineAndConsole(modName + " error/exception: Could not send notification to local client: " + e);
            }
        }

        public static void Info(string msg)
        {
            Write(msg);
        }

        private static void Write(string msg)
        {
            try
            {
                cache.Clear();
                cache.Append(DateTime.Now.ToString("[HH:mm:ss] "));

                if(writer == null)
                    cache.Append("(PRE-INIT) ");

                for(int i = 0; i < indent; i++)
                {
                    cache.Append("\t");
                }

                cache.Append(msg);

                if(writer == null)
                {
                    preInitMessages.Add(cache.ToString());
                }
                else
                {
                    writer.WriteLine(cache);
                    writer.Flush();
                }

                cache.Clear();
            }
            catch(Exception e)
            {
                MyLog.Default.WriteLineAndConsole(modName + " had an error while logging message='" + msg + "'\nLogger error: " + e.Message + "\n" + e.StackTrace);
            }
        }
    }
}


text:
from distutils.core import setup

with open('README.md') as file:
    long_description = file.read()

__version__ = '0.1.1'

setup(
    name='ssh_tunneler',
    version=__version__,
    long_description=long_description,
    description='Tool for setting up SSH tunnels.',
    url='http://www.github.com/rfaulkner/tunneler',
    author="Wikimedia Foundation",
    author_email="rfaulkner@wikimedia.org",
    scripts=['run_ssh_tunnels'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    data_files=[('readme', ['README.md'])]
)


text:
package me.alivecode.algs4;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;

/**
 * The {@code KruskalMST} class implements the Kruskal algorithm
 * for determining minimum spanning tree.
 */
public class KruskalMST {
    private Queue<Edge> mst;
    private double weight;

    /**
     * Determines the minimum spanning tree of the specified
     * edge weighted graph {@code G}.
     *
     * @param G the graph.
     */
    public KruskalMST(EdgeWeightedGraph G) {
        mst = new Queue<>();

        //edu.princeton.cs.algs4.MinPQ<Edge> pq = new edu.princeton.cs.algs4.MinPQ<Edge>();
        MinPQ<Edge> pq = new MinPQ<>();
        for(Edge e: G.edges()) {
            pq.insert(e);
        }
        UF uf = new UF(pq.size());
        while(!pq.isEmpty() && mst.size() < G.V() - 1) {
            Edge e = pq.delMin();
            int v = e.either();
            int w = e.other(v);
            if (!uf.connected(v, w)) {
                mst.enqueue(e);
                weight += e.weight();
                uf.union(v, w);
            }
        }
    }

    /**
     * Returns the minimum spanning tree.
     *
     * @return the minimum spanning tree
     */
    public Iterable<Edge> edges() {
        return mst;
    }

    /**
     * Returns the weight of the mst.
     *
     * @return the weight of the mst
     */
    public double weight() {
        return weight;
    }

    // unit test code
    public static void main(String[] args) {
        In in = new In(args[0]);
        EdgeWeightedGraph G = new EdgeWeightedGraph(in);
        KruskalMST mst = new KruskalMST(G);

        StdOut.println("mst: ");
        for(Edge e: mst.edges()){
            StdOut.println(e);
        }
        StdOut.println(mst.weight());
        //StdOut.printf("%.5f\n", mst.weight());
    }

}


text:
( function( $ ) {

	function optimizelyResultsPage( apiToken, projectId ) {
		var optly = new OptimizelyAPI( apiToken );

		// Fetch only Wordpress experiments from project
		optly.get( 'projects/' + projectId + '/experiments/', function( response ) {
			optly.wordpressExps = [];
			var resultsArray = [];

			for ( i = 0; i < response.length; i++ ) {
				if ( response[ i ].description.indexOf( 'Wordpress' ) > -1
					&& 'Archived' != response[ i ].status
					&& 'Not started' != response[ i ].status
					&& 'Draft' != response[ i ].status ) {
					resultsArray.push( response[ i ] );
				}
			}

			if ( resultsArray.length > 0 ) {
				for ( i = 0; i < resultsArray.length; i++ ) {
					getWPExpResults( resultsArray[ i ],function( exp ) {
						displayResultsList( exp,i,function() {
							showGoalSelected( exp.id );
							addSelectChange( exp.id );
						});
					});
				}
			} else {
				$( '#noresults' ).show();
				$( '#loading' ).hide();
				$( '#ready' ).hide();
			}
		});

		// Pause experiment when pause button is pressed
		$( 'html' ).delegate( '.pause', 'click', function() {
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			pauseExperiment( expID );
		});

		// Start experiment when play button is pressed
		$( 'html' ).delegate( '.play', 'click', function() {
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			startExperiment( expID );
		});

		// Archive experiment when archive button is pressed
		$( 'html' ).delegate( '.archive', 'click', function() {
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			archiveExperiment( expID );
		});

		$( 'html' ).delegate( '.edit', 'click', function() {
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			window.open( 'https://app.optimizely.com/edit?experiment_id=' + parseInt( expID ) );
		});

		$( 'html' ).delegate( '.fullresults', 'click', function() {
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			window.open( 'https://app.optimizely.com/results2?experiment_id=' + parseInt( expID ) );
		});

		// Launch winning variation when Launch button is clicked
		$( 'html' ).delegate( '.launch', 'click', function() {
			var winningVarName = $( this ).parents( 'td' ).siblings( '.first' ).children( 'a' ).text();
			var expID = $( this ).parents( '.opt_results' ).attr( 'data-exp-id' );
			var expTitle = $( this ).parents( '.opt_results' ).attr( 'data-exp-title' );
			launchWinner( expID, expTitle, winningVarName );
		});

		// Changes the results for the goal selected
		function addSelectChange( expId ) {
			$( '#goal_' + expId ).bind( 'change', function() {
				showGoalSelected( expId );
			});
		}

		// Simple compare function to sort goals by name
		function compare( a,b ) {
			if ( a.goal_name < b.goal_name ) {
				 return -1;
			}

			if ( a.goal_name > b.goal_name ) {
				return 1;
			}

			return 0;
		}

		// Gets the results for the experiment
		function getWPExpResults( expObj,cb ) {
			expObj.results = [];
			optly.get( 'experiments/' + expObj.id + '/stats', function( response ) {
				var goalNameArray = [];
				response.sort( compare );
				expObj.results = response;
				expObj.avgVisitorCount = getAverageVisitor( expObj.results );
				cb( expObj );
			});
		}

		// AJAX function that updates the title in Wordpress
		function launchWinner( expID, expTitle, winningVarName ) {
			// Get the ID of the Wordpress post
			var wpPostID = expTitle.substring( 11, expTitle.indexOf( ']' ) );
			var data = {
				action: 'update_post_title',
				post_id: wpPostID,
				title: winningVarName
			};

			$.post( wpAjaxUrl, data, function() {
				$( '#exp_' + expID ).fadeOut( 1000, function() {
					$message = $( '<h3>' ).text( 'You have succesfully launched the new headline' );
					$old = $( '<p>' ).text( 'Old Headline: ' + expTitle );
					$new = $( '<p>' ).text( 'New Headline: ' + winningVarName );

					$( '#successMessage' )
						.html( '' )
						.append( $message )
						.append( $old )
						.append( $new )
						.show();

					// Archive the Experiement
					archiveExperiment( expID );
				});
			});
		}

		// Pause Experiment
		function pauseExperiment( experimentID ) {
			optly.patch( 'experiments/' + experimentID, { 'status': 'Paused' }, function( response ) {
				$( '.opt_results[data-exp-id=' + experimentID + ']' )
					.find( '.pause' )
					.removeClass( 'pause' )
					.addClass( 'play' );

				$( '.opt_results[data-exp-id=' + experimentID + ']' )
					.find( '.fa-pause' )
					.removeClass( 'fa-pause' )
					.addClass( 'fa-play' );
			});
		}

		// Start Experiment
		function startExperiment( experimentID ) {
			optly.patch( 'experiments/' + experimentID, { 'status': 'Running' }, function( response ) {
				$( '.opt_results[data-exp-id=' + experimentID + ']' )
					.find( '.play' )
					.removeClass( 'play' )
					.addClass( 'pause' );

				$( '.opt_results[data-exp-id=' + experimentID + ']' )
					.find( '.fa-play' )
					.removeClass( 'fa-play' )
					.addClass( 'fa-pause' );
			});
		}

		// Archive Experiment
		function archiveExperiment( experimentID ) {
			optly.patch( 'experiments/'+ experimentID, { 'status': 'Archived' }, function( response ) {
				$( '.opt_results[data-exp-id=' + experimentID + ']' ).hide();
			});
		}

		// Will display the resutls and build the HTML
		function displayResultsList( exp, i, cb ) {
			$( '.loading' ).hide();
			var data = buildResultsModuleData( exp );
			var tpl = _.template( $( '#optimizely_results' ).html() );
			if ( data.isSignificant ) {
				$( '#ready' ).append( tpl( data ) );
				$( '#ready' ).show();
			} else {
				$( '#stillwaiting' ).append( tpl( data ) );
				$( '#stillwaiting' ).show();
			}
			cb();
		}

		// Loops through the variations and gets an average of the visitor count for powered testing
		function getAverageVisitor( results ) {
			var totalVisitors = 0;
			for ( var i=0; i < results.length; i++ ) {
				totalVisitors += results[ i ].visitors;
			}

			return totalVisitors/results.length;
		}

		// Used to convert the value returned by the results API to a rounded percentage
		function getRoundedPercentage( num ) {
			return ( num*100 ).toFixed( 2 ) + '%';
		}

		// Changes the goal results based on what is selcted
		function showGoalSelected( expID ) {
			$( '#exp_' + expID ).find( '.variationrow' ).hide();
			var goalClass = $( '#goal_' + expID ).val();
			$( '#exp_' + expID ).find( '.'+goalClass ).show();

		}

		// Main function that builds the HTML for each results block
		function buildResultsModuleData( exp ) {
			// Set the checkbox html
			var statusClass = 'play';

			if ( 'Running' == exp.status ) {
				statusClass = 'pause';
			}

			var expTitle = exp.description;
			expTitle = expTitle.substring( expTitle.indexOf( ']:' ) + 3 );
			if ( expTitle.length > 73 ) {
				expTitle = expTitle.substring( 0, 72 ) + '...';
			}

			var goalIdArray = [];
			var goalOptions = [];
			for ( var i = 0; i < exp.results.length; i++ ) {
				var result = exp.results[ i ];
				var selected = '';
				if ( goalIdArray.indexOf( result.goal_id ) == -1 ) {
					if ( result.goal_name == 'Views to page' ) {
						selected = 'selected';
					} else {
						selected = '';
					}

					goalOptions.push({
						id: result.goal_id,
						selected: selected,
						name: result.goal_name
					});

					goalIdArray.push( result.goal_id );
				}
			}

			var variations = [];
			var isSignificant = false;
			for ( i = exp.results.length -1; i >= 0; i-- ) {
				var result = exp.results[ i ],
					improvement,
					conversion_rate,
					avgVisitors = getAverageVisitor( exp.results ),
					confidence,
					vistitorsRemaining,
					status,
					rowColor;

				if ( 'baseline' == result.status ) {
					improvement = 'baseline';
					confidence = '-';
					vistitorsRemaining = '-';
					status = 'baseline';
				} else {
					confidence = getRoundedPercentage( result.statistical_significance );
					improvement = getRoundedPercentage( result.improvement );
					vistitorsRemaining = result.visitors_until_statistically_significant;
					if(result.status == 'inconclusive') {
						// results are inconclusive determine if the variation is winning or loosing
						if(result.improvement > 0) {
							status = 'winning';
						} else {
							status = 'losing';
						}
					} else {
						isSignificant = true;
						status = result.status;
					}
				}

				var conversionRate = getRoundedPercentage( result.conversion_rate );

				variations.push({
					expID: exp.id,
					status: status,
					goalId: result.goal_id,
					variationId: result.variation_id,
					variationName: result.variation_name,
					editUrl: exp.edit_url,
					visitors: result.visitors,
					conversions: result.conversions,
					conversionRate: conversionRate,
					improvement: improvement,
					confidence: confidence,
					vistitorsRemaining: vistitorsRemaining
				});
			}

			data = {
				id: exp.id,
				isSignificant: isSignificant,
				description: exp.description,
				title: expTitle,
				goalOptions: goalOptions,
				statusClass: statusClass,
				variations: variations
			};

			return data;
		}
	}

	$( document ).ready(function() {
		if (typeof pagenow != 'undefined' && 'toplevel_page_optimizely-config' == pagenow && '' != optimizelySettings.token && '' != optimizelySettings.projectId ) {
			optimizelyResultsPage( optimizelySettings.token, optimizelySettings.projectId );
		} else {
			$( '#loading' ).hide();
		}
	});
})(	jQuery	);


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>Operating System Utilities — Python 3.5.2 documentation</title>

    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.5.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.5.2 documentation" href="../contents.html" />
    <link rel="up" title="Utilities" href="utilities.html" />
    <link rel="next" title="Importing Modules" href="import.html" />
    <link rel="prev" title="Utilities" href="utilities.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

Python/C API Reference Manual »

Utilities »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

Operating System Utilities¶

int Py_FdIsInteractive(FILE *fp, const char *filename)¶

Return true (nonzero) if the standard I/O file fp with name filename is
deemed interactive.  This is the case for files for which isatty(fileno(fp))
is true.  If the global flag Py_InteractiveFlag is true, this function
also returns true if the filename pointer is NULL or if the name is equal to
one of the strings '<stdin>' or '???'.

void PyOS_AfterFork()¶

Function to update some internal state after a process fork; this should be
called in the new process if the Python interpreter will continue to be used.
If a new executable is loaded into the new process, this function does not need
to be called.

int PyOS_CheckStack()¶

Return true when the interpreter runs out of stack space.  This is a reliable
check, but is only available when USE_STACKCHECK is defined (currently
on Windows using the Microsoft Visual C++ compiler).  USE_STACKCHECK
will be defined automatically; you should never change the definition in your
own code.

PyOS_sighandler_t PyOS_getsig(int i)¶

Return the current signal handler for signal i.  This is a thin wrapper around
either sigaction() or signal().  Do not call those functions
directly! PyOS_sighandler_t is a typedef alias for void
(*)(int).

PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)¶

Set the signal handler for signal i to be h; return the old signal handler.
This is a thin wrapper around either sigaction() or signal().  Do
not call those functions directly!  PyOS_sighandler_t is a typedef
alias for void (*)(int).

wchar_t* Py_DecodeLocale(const char* arg, size_t *size)¶

Decode a byte string from the locale encoding with the surrogateescape
error handler: undecodable bytes are decoded as
characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a
surrogate character, escape the bytes using the surrogateescape error
handler instead of decoding them.

Return a pointer to a newly allocated wide character string, use
PyMem_RawFree() to free the memory. If size is not NULL, write
the number of wide characters excluding the null character into *size

Return NULL on decoding error or memory allocation error. If size is
not NULL, *size is set to (size_t)-1 on memory error or set to
(size_t)-2 on decoding error.

Decoding errors should never happen, unless there is a bug in the C
library.

Use the Py_EncodeLocale() function to encode the character string
back to a byte string.

See also

The PyUnicode_DecodeFSDefaultAndSize() and
PyUnicode_DecodeLocaleAndSize() functions.

New in version 3.5.

char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)¶

Encode a wide character string to the locale encoding with the
surrogateescape error handler: surrogate characters
in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

Return a pointer to a newly allocated byte string, use PyMem_Free()
to free the memory. Return NULL on encoding error or memory allocation
error

If error_pos is not NULL, *error_pos is set to the index of the
invalid character on encoding error, or set to (size_t)-1 otherwise.

Use the Py_DecodeLocale() function to decode the bytes string back
to a wide character string.

See also

The PyUnicode_EncodeFSDefault() and
PyUnicode_EncodeLocale() functions.

New in version 3.5.

System Functions¶

These are utility functions that make functionality from the sys module
accessible to C code.  They all work with the current interpreter thread’s
sys module’s dict, which is contained in the internal thread state structure.

PyObject *PySys_GetObject(const char *name)¶

Return value: Borrowed reference.
Return the object name from the sys module or NULL if it does
not exist, without setting an exception.

int PySys_SetObject(const char *name, PyObject *v)¶

Set name in the sys module to v unless v is NULL, in which
case name is deleted from the sys module. Returns 0 on success, -1
on error.

void PySys_ResetWarnOptions()¶

Reset sys.warnoptions to an empty list.

void PySys_AddWarnOption(wchar_t *s)¶

Append s to sys.warnoptions.

void PySys_AddWarnOptionUnicode(PyObject *unicode)¶

Append unicode to sys.warnoptions.

void PySys_SetPath(wchar_t *path)¶

Set sys.path to a list object of paths found in path which should
be a list of paths separated with the platform’s search path delimiter
(: on Unix, ; on Windows).

void PySys_WriteStdout(const char *format, ...)¶

Write the output string described by format to sys.stdout.  No
exceptions are raised, even if truncation occurs (see below).

format should limit the total size of the formatted output string to
1000 bytes or less – after 1000 bytes, the output string is truncated.
In particular, this means that no unrestricted “%s” formats should occur;
these should be limited using “%.<N>s” where <N> is a decimal number
calculated so that <N> plus the maximum size of other formatted text does not
exceed 1000 bytes.  Also watch out for “%f”, which can print hundreds of
digits for very large numbers.

If a problem occurs, or sys.stdout is unset, the formatted message
is written to the real (C level) stdout.

void PySys_WriteStderr(const char *format, ...)¶

As PySys_WriteStdout(), but write to sys.stderr or stderr
instead.

void PySys_FormatStdout(const char *format, ...)¶

Function similar to PySys_WriteStdout() but format the message using
PyUnicode_FromFormatV() and don’t truncate the message to an
arbitrary length.

New in version 3.2.

void PySys_FormatStderr(const char *format, ...)¶

As PySys_FormatStdout(), but write to sys.stderr or stderr
instead.

New in version 3.2.

void PySys_AddXOption(const wchar_t *s)¶

Parse s as a set of -X options and add them to the current
options mapping as returned by PySys_GetXOptions().

New in version 3.2.

PyObject *PySys_GetXOptions()¶

Return value: Borrowed reference.
Return the current dictionary of -X options, similarly to
sys._xoptions.  On error, NULL is returned and an exception is
set.

New in version 3.2.

Process Control¶

void Py_FatalError(const char *message)¶

Print a fatal error message and kill the process.  No cleanup is performed.
This function should only be invoked when a condition is detected that would
make it dangerous to continue using the Python interpreter; e.g., when the
object administration appears to be corrupted.  On Unix, the standard C library
function abort() is called which will attempt to produce a core
file.

void Py_Exit(int status)¶

Exit the current process.  This calls Py_Finalize() and then calls the
standard C library function exit(status).

int Py_AtExit(void (*func)())¶

Register a cleanup function to be called by Py_Finalize().  The cleanup
function will be called with no arguments and should return no value.  At most
32 cleanup functions can be registered.  When the registration is successful,
Py_AtExit() returns 0; on failure, it returns -1.  The cleanup
function registered last is called first. Each cleanup function will be called
at most once.  Since Python’s internal finalization will have completed before
the cleanup function, no Python APIs should be called by func.

Table Of Contents

Operating System Utilities

System Functions

Process Control

Previous topic

Utilities

Next topic

Importing Modules

This Page

Report a Bug

Show Source

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.5.2
          Documentation  »

Python/C API Reference Manual »

Utilities »

        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

         |

    © Copyright 2001-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Dec 08, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Shouldly;
using Xunit;

namespace Alba.Testing.Acceptance
{
    public class assertions_against_the_querystring : ScenarioContext
    {
        [Fact]
        public Task using_scenario_with_QueryString_should_set_query_string_parameter()
        {
            router.Handlers["/one"] = c =>
            {
                c.Response.StatusCode = 200;
                return c.Response.WriteAsync(c.Request.Query["test"]);
            };

            return host.Scenario(_ =>
            {
                _.Get.Url("/one").QueryString("test", "value");

                _.ConfigureHttpContext(c =>
                {
                    c.Request.Query["test"].ToString().ShouldBe("value");
                });
            });
        }
    }
}


text:
package org.fife.rsta.ac.js.ast;

import org.fife.rsta.ac.js.ast.type.TypeDeclaration;

public class JavaScriptFunctionDeclaration extends JavaScriptDeclaration {

	private TypeDeclaration typeDec;

	private String functionName;

	public JavaScriptFunctionDeclaration(String name, int offset, CodeBlock block, TypeDeclaration typeDec) {
		super(name, offset, block);
		this.typeDec = typeDec;
	}

	public TypeDeclaration getTypeDeclaration() {
		return typeDec;
	}

	public void setFunctionName(String functionName) {
		this.functionName = functionName;
	}

	public String getFunctionName()
	{
		return functionName;
	}

}


text:
"""
@package mi.dataset.parser
@file marine-integrations/mi/dataset/parser/dosta_abcdjm_cspp.py
@author Mark Worden
@brief Parser for the dosta_abcdjm_cspp dataset driver
Release notes:

initial release
"""

import numpy

from mi.core.log import get_logger
from mi.core.common import BaseEnum
from mi.core.instrument.dataset_data_particle import DataParticle
from mi.dataset.parser.common_regexes import INT_REGEX, FLOAT_REGEX, MULTIPLE_TAB_REGEX, END_OF_LINE_REGEX
from mi.dataset.parser.cspp_base import CsppParser, Y_OR_N_REGEX, CsppMetadataDataParticle, MetadataRawDataKey, \
    encode_y_or_n
log = get_logger()

__author__ = 'Mark Worden'
__license__ = 'Apache 2.0'

# A regular expression for special characters that could exist in a data record preceding the model
SPECIAL_CHARS_REGEX = r'(?:[\?][%])?'

# A regular expression that should match a dosta_abcdjm data record
# NOTE the group names must match the string literals in the ParticleKey below
# strings used here instead of enumerated constants for readability
DATA_REGEX = r'(?P<profiler_timestamp>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX   # Profiler Timestamp
DATA_REGEX += '(?P<pressure_depth>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX   # Depth
DATA_REGEX += '(?P<suspect_timestamp>' + Y_OR_N_REGEX + ')' + MULTIPLE_TAB_REGEX  # Suspect Timestamp
DATA_REGEX += SPECIAL_CHARS_REGEX + '(?P<product_number>' + INT_REGEX + ')' + MULTIPLE_TAB_REGEX  # Model Number
DATA_REGEX += '(?P<serial_number>' + INT_REGEX + ')' + MULTIPLE_TAB_REGEX    # Serial Number
DATA_REGEX += '(?P<estimated_oxygen_concentration>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # oxygen content
# relative air saturation
# Note: relative air saturation is missing in some early deployments.  If not present match group will be None.
DATA_REGEX += '(?:(?P<estimated_oxygen_saturation>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX + ')?'
DATA_REGEX += '(?P<optode_temperature>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # ambient temperature
DATA_REGEX += '(?P<calibrated_phase>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # calibrated phase
DATA_REGEX += '(?P<temp_compensated_phase>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # temperature compensated phase
DATA_REGEX += '(?P<blue_phase>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # phase with blue excitation
DATA_REGEX += '(?P<red_phase>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # phase with red excitation
DATA_REGEX += '(?P<blue_amplitude>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # amplitude with blue excitation
DATA_REGEX += '(?P<red_amplitude>' + FLOAT_REGEX + ')' + MULTIPLE_TAB_REGEX  # amplitude with red excitation
DATA_REGEX += '(?P<raw_temperature>' + FLOAT_REGEX + ')' + END_OF_LINE_REGEX   # raw temperature, voltage

class DataParticleType(BaseEnum):
    """
    The data particle types that a dosta_abcdjm_cspp parser could generate
    """
    METADATA_RECOVERED = 'dosta_abcdjm_cspp_metadata_recovered'
    INSTRUMENT_RECOVERED = 'dosta_abcdjm_cspp_instrument_recovered'
    METADATA_TELEMETERED = 'dosta_abcdjm_cspp_metadata'
    INSTRUMENT_TELEMETERED = 'dosta_abcdjm_cspp_instrument'

class DostaAbcdjmCsppParserDataParticleKey(BaseEnum):
    """
    The data particle keys associated with dosta_abcdjm_cspp data particle parameters
    """
    PRODUCT_NUMBER = 'product_number'
    SERIAL_NUMBER = 'serial_number'
    PROFILER_TIMESTAMP = 'profiler_timestamp'
    PRESSURE = 'pressure_depth'
    SUSPECT_TIMESTAMP = 'suspect_timestamp'
    ESTIMATED_OXYGEN_CONCENTRATION = 'estimated_oxygen_concentration'
    ESTIMATED_OXYGEN_SATURATION = 'estimated_oxygen_saturation'
    OPTODE_TEMPERATURE = 'optode_temperature'
    CALIBRATED_PHASE = 'calibrated_phase'
    TEMP_COMPENSATED_PHASE = 'temp_compensated_phase'
    BLUE_PHASE = 'blue_phase'
    RED_PHASE = 'red_phase'
    BLUE_AMPLITUDE = 'blue_amplitude'
    RED_AMPLITUDE = 'red_amplitude'
    RAW_TEMPERATURE = 'raw_temperature'

def float_or_none(float_val):
    if float_val is None:
        return None
    return float(float_val)

# A group of non common metadata particle encoding rules used to simplify encoding using a loop
NON_COMMON_METADATA_PARTICLE_ENCODING_RULES = [
    (DostaAbcdjmCsppParserDataParticleKey.PRODUCT_NUMBER, int),
    (DostaAbcdjmCsppParserDataParticleKey.SERIAL_NUMBER, str)
]

# A group of instrument data particle encoding rules used to simplify encoding using a loop
INSTRUMENT_PARTICLE_ENCODING_RULES = [
    (DostaAbcdjmCsppParserDataParticleKey.PROFILER_TIMESTAMP, numpy.float),
    (DostaAbcdjmCsppParserDataParticleKey.PRESSURE, float),
    (DostaAbcdjmCsppParserDataParticleKey.SUSPECT_TIMESTAMP, encode_y_or_n),
    (DostaAbcdjmCsppParserDataParticleKey.ESTIMATED_OXYGEN_CONCENTRATION, float),
    (DostaAbcdjmCsppParserDataParticleKey.ESTIMATED_OXYGEN_SATURATION, float_or_none),
    (DostaAbcdjmCsppParserDataParticleKey.OPTODE_TEMPERATURE, float),
    (DostaAbcdjmCsppParserDataParticleKey.CALIBRATED_PHASE, float),
    (DostaAbcdjmCsppParserDataParticleKey.TEMP_COMPENSATED_PHASE, float),
    (DostaAbcdjmCsppParserDataParticleKey.BLUE_PHASE, float),
    (DostaAbcdjmCsppParserDataParticleKey.RED_PHASE, float),
    (DostaAbcdjmCsppParserDataParticleKey.BLUE_AMPLITUDE, float),
    (DostaAbcdjmCsppParserDataParticleKey.RED_AMPLITUDE, float),
    (DostaAbcdjmCsppParserDataParticleKey.RAW_TEMPERATURE, float),
]

class DostaAbcdjmCsppMetadataDataParticle(CsppMetadataDataParticle):
    """
    Class for building a dosta_abcdjm_cspp metadata particle
    """

    def _build_parsed_values(self):
        """
        Take something in the data format and turn it into
        an array of dictionaries defining the data in the particle
        with the appropriate tag.
        """

        # Set the base metadata parsed values to the results to return
        results = self._build_metadata_parsed_values()

        data_match = self.raw_data[MetadataRawDataKey.DATA_MATCH]

        # Process each of the non common metadata particle parameters
        for (name, encoding) in NON_COMMON_METADATA_PARTICLE_ENCODING_RULES:
            results.append(self._encode_value(name, data_match.group(name), encoding))

        # Set the internal timestamp
        internal_timestamp_unix = numpy.float(data_match.group(
            DostaAbcdjmCsppParserDataParticleKey.PROFILER_TIMESTAMP))
        self.set_internal_timestamp(unix_time=internal_timestamp_unix)

        return results

class DostaAbcdjmCsppMetadataRecoveredDataParticle(DostaAbcdjmCsppMetadataDataParticle):
    """
    Class for building a dosta_abcdjm_cspp recovered metadata particle
    """

    _data_particle_type = DataParticleType.METADATA_RECOVERED

class DostaAbcdjmCsppMetadataTelemeteredDataParticle(DostaAbcdjmCsppMetadataDataParticle):
    """
    Class for building a dosta_abcdjm_cspp telemetered metadata particle
    """

    _data_particle_type = DataParticleType.METADATA_TELEMETERED

class DostaAbcdjmCsppInstrumentDataParticle(DataParticle):
    """
    Class for building a dosta_abcdjm_cspp instrument data particle
    """

    def _build_parsed_values(self):
        """
        Take something in the data format and turn it into
        an array of dictionaries defining the data in the particle
        with the appropriate tag.
        """

        results = []

        # Process each of the instrument particle parameters
        for (name, encoding) in INSTRUMENT_PARTICLE_ENCODING_RULES:
            results.append(self._encode_value(name, self.raw_data.group(name), encoding))

        # # Set the internal timestamp
        internal_timestamp_unix = numpy.float(self.raw_data.group(
            DostaAbcdjmCsppParserDataParticleKey.PROFILER_TIMESTAMP))
        self.set_internal_timestamp(unix_time=internal_timestamp_unix)

        return results

class DostaAbcdjmCsppInstrumentRecoveredDataParticle(DostaAbcdjmCsppInstrumentDataParticle):
    """
    Class for building a dosta_abcdjm_cspp recovered instrument data particle
    """

    _data_particle_type = DataParticleType.INSTRUMENT_RECOVERED

class DostaAbcdjmCsppInstrumentTelemeteredDataParticle(DostaAbcdjmCsppInstrumentDataParticle):
    """
    Class for building a dosta_abcdjm_cspp telemetered instrument data particle
    """

    _data_particle_type = DataParticleType.INSTRUMENT_TELEMETERED

class DostaAbcdjmCsppParser(CsppParser):

    def __init__(self,
                 config,
                 stream_handle,
                 exception_callback):
        """
        This method is a constructor that will instantiate an DostaAbcdjmCsppParser object.
        @param config The configuration for this DostaAbcdjmCsppParser parser
        @param stream_handle The handle to the data stream containing the dosta_abcdjm_cspp data
        @param exception_callback The function to call to report exceptions
        """

        # Call the superclass constructor
        super(DostaAbcdjmCsppParser, self).__init__(config,
                                                    stream_handle,
                                                    exception_callback,
                                                    DATA_REGEX)


text:
#import "CXDurationPickerDate.h"
#import "CXDurationPickerUtils.h"

@implementation CXDurationPickerUtils

+ (NSDateComponents *)dateComponentsFromPickerDate:(CXDurationPickerDate)pickerDate {
    NSDateComponents *components = [NSDateComponents new];

    components.year = pickerDate.year;
    components.month = pickerDate.month;
    components.day = pickerDate.day;

    return components;
}

+ (NSDate *)dateFromPickerDate:(CXDurationPickerDate)pickerDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];

    return [calendar dateFromComponents:[CXDurationPickerUtils dateComponentsFromPickerDate:pickerDate]];
}

+ (BOOL)isPickerDate:(CXDurationPickerDate)date1 equalTo:(CXDurationPickerDate)date2 {
    return date1.year == date2.year
    && date1.month == date2.month
    && date1.day == date2.day;
}

+ (CXDurationPickerDate)pickerDateFromDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar
                                    components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                    fromDate:date];

    return (CXDurationPickerDate) {
        components.year,
        components.month,
        components.day
    };
}

+ (CXDurationPickerDate)pickerDateShiftedByDays:(NSUInteger)days fromPickerDate:(CXDurationPickerDate)pickerDate {
    NSDate *startDate = [CXDurationPickerUtils dateFromPickerDate:pickerDate];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [NSDateComponents new];

    components.day = days;

    NSDate *shiftedDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

    return [CXDurationPickerUtils pickerDateFromDate:shiftedDate];
}

+ (NSString *)stringFromPickerDate:(CXDurationPickerDate)pickerDate {
    NSDate *date = [CXDurationPickerUtils dateFromPickerDate:pickerDate];

    NSDateFormatter *formatter = [NSDateFormatter new];

    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];

    return [formatter stringFromDate:date];
}

+ (NSDate *)today {
    NSDate *date = [NSDate date];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                               fromDate:date];

    return [calendar dateFromComponents:components];
}

+ (BOOL)isPickerDateYesterday:(CXDurationPickerDate)pickerDate {
    NSDate *today = [self today];
    NSDate *date = [self dateFromPickerDate:pickerDate];

    NSTimeInterval interval = [date timeIntervalSinceDate:today];

    // 86400 seconds = 24hrs
    if ( interval >= -86400 && interval < 0) {
        return YES;
    }

    return NO;
}

@end