text:
# VITTokenSale

Source file [../../contracts/VITTokenSale.sol](../../contracts/VITTokenSale.sol).

```javascript
// BK Ok
pragma solidity 0.4.18;

// BK Next 3 Ok
import "zeppelin-solidity/contracts/math/Math.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
import "zeppelin-solidity/contracts/ownership/Claimable.sol";

// BK Ok
import "./VITToken.sol";

/// @title VITToken sale contract.
// BK Ok
contract VITTokenSale is Claimable {
    // BK Ok
    using Math for uint256;
    // BK Ok
    using SafeMath for uint256;

    // VIT token contract.
    // BK Ok
    VITToken public vitToken;

    // Received funds are forwarded to this address.
    // BK Ok
    address public fundingRecipient;

    // VIT token unit.
    // BK Ok
    uint256 public constant TOKEN_UNIT = 10 ** 18;

    // Maximum tokens offered in the sale: 2B.
    // BK Ok
    uint256 public constant MAX_TOKENS_SOLD = 2 * 10 ** 9 * TOKEN_UNIT;

    // VIT to 1 wei ratio.
    // BK Ok
    uint256 public vitPerWei;

    // Sale start and end timestamps.
    // BK Ok
    uint256 public constant RESTRICTED_PERIOD_DURATION = 1 days;
    // BK Ok
    uint256 public startTime;
    // BK Ok
    uint256 public endTime;

    // Refund data and state.
    // BK Ok
    uint256 public refundEndTime;
    // BK Ok
    mapping (address => uint256) public refundableEther;
    // BK Ok
    mapping (address => uint256) public claimableTokens;
    // BK Ok
    uint256 public totalClaimableTokens = 0;
    // BK Ok
    bool public finalizedRefund = false;

    // Amount of tokens sold until now in the sale.
    // BK Ok
    uint256 public tokensSold = 0;

    // Accumulated amount each participant has contributed so far.
    // BK Ok
    mapping (address => uint256) public participationHistory;

    // Maximum amount that each participant is allowed to contribute (in WEI), during the restricted period.
    // BK Ok
    mapping (address => uint256) public participationCaps;

    // Initial allocations.
    // BK Ok
    address[20] public strategicPartnersPools;
    // BK Ok
    uint256 public constant STRATEGIC_PARTNERS_POOL_ALLOCATION = 100 * 10 ** 6 * TOKEN_UNIT; // 100M

    // BK Next 5 Ok - Events
    event TokensIssued(address indexed to, uint256 tokens);
    event EtherRefunded(address indexed from, uint256 weiAmount);
    event TokensClaimed(address indexed from, uint256 tokens);
    event Finalized();
    event FinalizedRefunds();

    /// @dev Reverts if called when not during sale.
    // BK Ok - Modifier
    modifier onlyDuringSale() {
        // BK Ok
        require(!saleEnded() && now >= startTime);

        // BK Ok
        _;
    }

    /// @dev Reverts if called before the sale ends.
    // BK Ok - Modifier
    modifier onlyAfterSale() {
        // BK Ok
        require(saleEnded());

        // BK Ok
        _;
    }

    /// @dev Reverts if called not doing the refund period.
    // BK Ok - Modifier
    modifier onlyDuringRefund() {
        // BK Ok
        require(saleDuringRefundPeriod());

        // BK Ok
        _;
    }

    // BK Ok - Modifier
    modifier onlyAfterRefund() {
        // BK Ok
        require(saleAfterRefundPeriod());

        // BK Ok
        _;
    }

    /// @dev Constructor that initializes the sale conditions.
    /// @param _fundingRecipient address The address of the funding recipient.
    /// @param _startTime uint256 The start time of the token sale.
    /// @param _endTime uint256 The end time of the token sale.
    /// @param _refundEndTime uint256 The end time of the refunding period.
    /// @param _vitPerWei uint256 The exchange rate of VIT for one ETH.
    /// @param _strategicPartnersPools address[20] The addresses of the 20 strategic partners pools.
    // BK Ok - Constructor
    function VITTokenSale(address _fundingRecipient, uint256 _startTime, uint256 _endTime, uint256 _refundEndTime,
        uint256 _vitPerWei, address[20] _strategicPartnersPools) public {
        // BK Ok
        require(_fundingRecipient != address(0));
        // BK Ok
        require(_startTime > now && _startTime < _endTime && _endTime < _refundEndTime);
        // BK Ok
        require(_startTime.add(RESTRICTED_PERIOD_DURATION) < _endTime);
        // BK Ok
        require(_vitPerWei > 0);

        // BK Ok
        for (uint i = 0; i < _strategicPartnersPools.length; ++i) {
            // BK Ok
            require(_strategicPartnersPools[i] != address(0));
        }

        // BK Ok
        fundingRecipient = _fundingRecipient;
        // BK Next 4 Ok
        startTime = _startTime;
        endTime = _endTime;
        refundEndTime = _refundEndTime;
        vitPerWei = _vitPerWei;
        // BK Ok
        strategicPartnersPools = _strategicPartnersPools;

        // Deploy new VITToken contract.
        // BK Ok
        vitToken = new VITToken();

        // Grant initial token allocations.
        // BK Ok
        grantInitialAllocations();
    }

    /// @dev Fallback function that will delegate the request to create().
    // BK Ok - Anyone can call this fallback function during the sale period to contribute ETH
    function () external payable onlyDuringSale {
        // BK Ok
        address recipient = msg.sender;

        // BK Ok
        uint256 cappedWeiReceived = msg.value;
        // BK Ok
        uint256 weiAlreadyParticipated = participationHistory[recipient];

        // If we're during the restricted period, then only the white-listed participants are allowed to participate,
        // BK Ok
        if (saleDuringRestrictedPeriod()) {
            // BK Ok
            uint256 participationCap = participationCaps[recipient];
            // BK Ok
            cappedWeiReceived = Math.min256(cappedWeiReceived, participationCap.sub(weiAlreadyParticipated));
        }

        // BK Ok
        require(cappedWeiReceived > 0);

        // Calculate how much tokens can be sold to this participant.
        // BK Ok
        uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold);
        // BK Ok
        uint256 weiLeftInSale = tokensLeftInSale.div(vitPerWei);
        // BK Ok
        uint256 weiToParticipate = Math.min256(cappedWeiReceived, weiLeftInSale);
        // BK Ok
        participationHistory[recipient] = weiAlreadyParticipated.add(weiToParticipate);

        // Issue tokens and transfer to recipient.
        // BK Ok
        uint256 tokensToIssue = weiToParticipate.mul(vitPerWei);
        // BK Ok
        if (tokensLeftInSale.sub(tokensToIssue) < vitPerWei) {
            // If purchase would cause less than vitPerWei tokens left then nobody could ever buy them, so we'll gift
            // them to the last buyer.
            // BK Ok
            tokensToIssue = tokensLeftInSale;
        }

        // Record the both the participate ETH and tokens for future refunds.
        // BK Ok
        refundableEther[recipient] = refundableEther[recipient].add(weiToParticipate);
        // BK Ok
        claimableTokens[recipient] = claimableTokens[recipient].add(tokensToIssue);

        // Update token counters.
        // BK Ok
        totalClaimableTokens = totalClaimableTokens.add(tokensToIssue);
        // BK Ok
        tokensSold = tokensSold.add(tokensToIssue);

        // Issue the tokens to the token sale smart contract itself, which will hold them for future refunds.
        // BK Ok
        issueTokens(address(this), tokensToIssue);

        // Partial refund if full participation not possible, e.g. due to cap being reached.
        // BK Ok
        uint256 refund = msg.value.sub(weiToParticipate);
        // BK Ok
        if (refund > 0) {
            // BK Ok - Exit point for ETH, but only to the max of the ETH sent by the participant
            msg.sender.transfer(refund);
        }
    }

    /// @dev Set restricted period participation caps for a list of addresses.
    /// @param _participants address[] The list of participant addresses.
    /// @param _cap uint256 The cap amount (in ETH).
    // BK Ok - Only owner can set the caps
    function setRestrictedParticipationCap(address[] _participants, uint256 _cap) external onlyOwner {
        // BK Ok
        for (uint i = 0; i < _participants.length; ++i) {
            // BK Ok
            participationCaps[_participants[i]] = _cap;
        }
    }

    /// @dev Finalizes the token sale event, by stopping token minting.
    // BK Ok - Anyone can call this function only after the sale period or the max funding is reached
    function finalize() external onlyAfterSale {
        // Issue any unsold tokens back to the company.
        // BK Ok
        if (tokensSold < MAX_TOKENS_SOLD) {
            // BK Ok
            issueTokens(fundingRecipient, MAX_TOKENS_SOLD.sub(tokensSold));
        }

        // Finish minting. Please note, that if minting was already finished - this call will revert().
        // BK Ok
        vitToken.finishMinting();

        // BK Ok - Log event
        Finalized();
    }

    // BK Ok - Only owner can execute after the refund period
    function finalizeRefunds() external onlyAfterRefund {
        // BK Ok
        require(!finalizedRefund);

        // BK Ok
        finalizedRefund = true;

        // Transfer all the Ether to the beneficiary of the funding.
        // BK Ok
        fundingRecipient.transfer(this.balance);

        // BK Ok - Log event
        FinalizedRefunds();
    }

    /// @dev Reclaim all ERC20 compatible tokens, but not more than the VIT tokens which were reserved for refunds.
    /// @param token ERC20Basic The address of the token contract.
    // BK Ok - Only owner can execute
    function reclaimToken(ERC20Basic token) external onlyOwner {
        // BK Ok
        uint256 balance = token.balanceOf(this);
        // BK Ok
        if (token == vitToken) {
            // BK Ok
            balance = balance.sub(totalClaimableTokens);
        }

        // BK Ok
        assert(token.transfer(owner, balance));
    }

    /// @dev Allows participants to claim their tokens, which also transfers the Ether to the funding recipient.
    /// @param _tokensToClaim uint256 The amount of tokens to claim.
    // BK Ok - Any participants who contributed can claim their tokens after the sale period, and during or after the refund period
    function claimTokens(uint256 _tokensToClaim) public onlyAfterSale {
        // BK Ok
        require(_tokensToClaim != 0);

        // BK Ok
        address participant = msg.sender;
        // BK Ok
        require(claimableTokens[participant] > 0);

        // BK Ok
        uint256 claimableTokensAmount = claimableTokens[participant];
        // BK Ok
        require(_tokensToClaim <= claimableTokensAmount);

        // BK Ok
        uint256 refundableEtherAmount = refundableEther[participant];
        // BK Ok
        uint256 etherToClaim = _tokensToClaim.mul(refundableEtherAmount).div(claimableTokensAmount);
        // BK Ok
        assert(etherToClaim > 0);

        // BK Ok
        refundableEther[participant] = refundableEtherAmount.sub(etherToClaim);
        // BK Ok
        claimableTokens[participant] = claimableTokensAmount.sub(_tokensToClaim);
        // BK Ok
        totalClaimableTokens = totalClaimableTokens.sub(_tokensToClaim);

        // Transfer the tokens from the token sale smart contract to the participant.
        // BK Ok
        assert(vitToken.transfer(participant, _tokensToClaim));

        // Transfer the Ether to the beneficiary of the funding (as long as the refund hasn't finalized yet).
        // BK Ok
        if (!finalizedRefund) {
            // BK Ok - Exit point for ETH, but only to the crowdsale wallet
            fundingRecipient.transfer(etherToClaim);
        }

        // BK Ok - Log event
        TokensClaimed(participant, _tokensToClaim);
    }

    /// @dev Allows participants to claim all their tokens.
    // BK Ok - Participants who contributed can execute, after the sale period
    function claimAllTokens() public onlyAfterSale {
        // BK Ok
        uint256 claimableTokensAmount = claimableTokens[msg.sender];
        // BK Ok
        claimTokens(claimableTokensAmount);
    }

    /// @dev Allows participants to claim refund for their purchased tokens.
    /// @param _etherToClaim uint256 The amount of Ether to claim.
    // BK Ok - Any participants who contributed can claim a refund of their ETH during the refund period
    function refundEther(uint256 _etherToClaim) public onlyDuringRefund {
        // BK Ok
        require(_etherToClaim != 0);

        // BK Ok
        address participant = msg.sender;

        // BK Ok
        uint256 refundableEtherAmount = refundableEther[participant];
        // BK Ok
        require(_etherToClaim <= refundableEtherAmount);

        // BK Ok
        uint256 claimableTokensAmount = claimableTokens[participant];
        // BK Ok
        uint256 tokensToClaim = _etherToClaim.mul(claimableTokensAmount).div(refundableEtherAmount);
        // BK Ok
        assert(tokensToClaim > 0);

        // BK Ok
        refundableEther[participant] = refundableEtherAmount.sub(_etherToClaim);
        // BK Ok
        claimableTokens[participant] = claimableTokensAmount.sub(tokensToClaim);
        // BK Ok
        totalClaimableTokens = totalClaimableTokens.sub(tokensToClaim);

        // Transfer the tokens to the beneficiary of the funding.
        // BK Ok
        assert(vitToken.transfer(fundingRecipient, tokensToClaim));

        // Transfer the Ether to the participant.
        // BK Ok - Exit point for ETH to the participant's wallet
        participant.transfer(_etherToClaim);

        // BK Ok - Log event
        EtherRefunded(participant, _etherToClaim);
    }

    /// @dev Allows participants to claim refund for all their purchased tokens.
    // BK Ok - Participants who contributed can execute, during the refund period
    function refundAllEther() public onlyDuringRefund {
        // BK Ok
        uint256 refundableEtherAmount = refundableEther[msg.sender];
        // BK Ok
        refundEther(refundableEtherAmount);
    }

    /// @dev Initialize token grants.
    // BK Ok - Only owner can execute. Called only by the constructor
    function grantInitialAllocations() private onlyOwner {
        // BK Ok
        for (uint i = 0; i < strategicPartnersPools.length; ++i) {
            // BK Ok
            issueTokens(strategicPartnersPools[i], STRATEGIC_PARTNERS_POOL_ALLOCATION);
        }
    }

    /// @dev Issues tokens for the recipient.
    /// @param _recipient address The address of the recipient.
    /// @param _tokens uint256 The amount of tokens to issue.
    // BK Ok
    function issueTokens(address _recipient, uint256 _tokens) private {
        // Request VIT token contract to mint the requested tokens for the buyer.
        // BK NOTE - mint function logs `Transfer(address(0), _to, _amount)` events
        // BK Ok
        assert(vitToken.mint(_recipient, _tokens));

        // BK Ok - Log event
        TokensIssued(_recipient, _tokens);
    }

    /// @dev Returns whether the sale has ended.
    /// @return bool Whether the sale has ended or not.
    // BK Ok - View function
    function saleEnded() private view returns (bool) {
        // BK Ok
        return tokensSold >= MAX_TOKENS_SOLD || now >= endTime;
    }

    /// @dev Returns whether the sale is during its restricted period, where only white-listed participants are allowed
    /// to participate.
    /// @return bool Whether the sale is during its restricted period, where only white-listed participants are allowed
    /// to participate.
    // BK NOTE - Used with another check that the period is after startTime
    // BK Ok - View function
    function saleDuringRestrictedPeriod() private view returns (bool) {
        // BK Ok
        return now <= startTime.add(RESTRICTED_PERIOD_DURATION);
    }

    /// @dev Returns whether the sale is during its refund period.
    /// @return bool whether the sale is during its refund period.
    // BK Ok - View function
    function saleDuringRefundPeriod() private view returns (bool) {
        // BK Ok
        return saleEnded() && now <= refundEndTime;
    }

    // BK NOTE - Comment 'during' should be 'after'
    /// @dev Returns whether the sale is during its refund period.
    /// @return bool whether the sale is during its refund period.
    // BK Ok - View function
    function saleAfterRefundPeriod() private view returns (bool) {
        // BK Ok
        return saleEnded() && now > refundEndTime;
    }
}

```

gha_language: JavaScript


text:
# drawBinaryTree

This is a short C pogram that prints a binary tree.
It's not designed with efficency in mind, it's intended as a quick way to visualize examples while studying.

  * the data field is an integer
  * non complete trees are allowed

## Sample output

```
              08

      04              12

  02      06      10      14

01  03  05  07  09  11  13  15
```
```
            +832

    -012            +003

+499    ____    +006    -007

```

```
              00

      -2              +2

  -4      __      +1      +4

-6  __  __  __  __  __  +3  +6
```

license: MIT

repository: rtjk/drawBinaryTree

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: rtjk/drawBinaryTree


text:
---
layout: post
title:  "A Note From The Future"
date:   2014-09-11 13:11:40
image:
  teaser: bertrand.jpg
---
I decided to take a moment and write out a letter that I hope to craft if I
manage to live until I'm 95. It's based loosely on the prologue to Bertrand
Russel's autobiography, which can be found
[here](http://users.drew.edu/jlenz/br-prolog.html). I wrote it to give myself
a clearer outlook on some of the things I'm going through right now, and as a
way to figure out the kind of person I would like to be as I grow older.

####What I Have Lived For####

Coming on my 95th year, I'd like to take a chance and reflect back on my life.
95 is longer than I ever thought I would live, but I'm glad to still be
cognizant enough to be a part of my great grandchildren's childhoods and write
short letters such as this. When I think back, I can see that my life has
mostly been guided by two things, making others happy and raising my family.

It's really easy to live your life to please only yourself, just doing what
you want when you want to. It's much harder to try and make others in your
life happy. When I was young and foolish, I tried to make everyone happy, even
complete strangers... With the wisdom of age, I realize now that you can never
make everyone happy, no matter how hard you try. Down that road lies only
depression and regret. Instead of making others happy, I found people that
have truly enriched my life and I've done my best to enrich theirs as well.
It's not about an equal trade, it's about doing good because it's the right
thing to do. When you find others who have that same value, it's easy to grow
together and become the best version of yourself while helping them do the
same.

Few people in this world are worth sacrificing your own well being for. When
it came down to it, I decided to dedicate myself to my family and close
friends. It was a hard decision to try and have kids and raise a family, but
I'm glad that's the decision we made. At first, I was hesitant. I had spent so
long trying to avoid the drama of my parents household, I didn't want to bring
about exactly what I was trying to avoid in my own household. It's different,
though, being a parent rather than a sibling. There is something magical about
bringing another human being into the world and passing on all of the
knowledge you yourself have learned over the years. I couldn't be more proud
of my children, my grand children, and the great things they've gone on to
accomplish. The opportunities that lay before the generations that came after
me are mind blowing, and I'm glad that we were able to tear down the barriers
that lay before them and let them become such amazing people.

There are many parts of my life that I didn't understand and that hurt me as I
went through them. Looking back, I realize now that they were simply
challenges for me to overcome, things to help strengthen me into the father I
needed to be and the grandfather I wanted to be. I've lived a full life now,
and I can think fondly of it without any regrets.

repository: BastionFennell/bastions-musings

extension: markdown

repo_name: BastionFennell/bastions-musings


text:
unicode
=======

A kichen knife tool for unicode.  The features are below for example.

- Reading string, with or without normalizing.
- Display charactors of unicode specified.
- Showing categories and charactors.

```
% unicode.py show -nN 'SMILING FACE WITH OPEN MOUTH' | unicode.py read -l
No.  Chr    EAA SZ CP   Name
==== ====== === == ==== ==========
  1: [😃 ] W   2: 0001F603 SMILING FACE WITH OPEN MOUTH
  2: [😄 ] W   2: 0001F604 SMILING FACE WITH OPEN MOUTH AND SMILING EYES
  3: [😅 ] W   2: 0001F605 SMILING FACE WITH OPEN MOUTH AND COLD SWEAT
  4: [😆 ] W   2: 0001F606 SMILING FACE WITH OPEN MOUTH AND TIGHTLY-CLOSED EYES
```

## Reading String

It decodes the input string into Unicode and to show the encoded string.
Usually, it normalizes with NFC to show the string.
So, you can normalize a decomposed string like below.

```
% cat sample/hoge.nfd.txt
ほげはげ

% cat sample/hoge.nfd.txt | unicode.py read
ほげはげ
```

If you want to see a decomposed string, you can use the -n NFD option.

```
% echo ほげはげ | unicode.py read -n NFD
ほげはげ
```

With the -l option, you can see the charactors in detail.

```
cat sample/hoge.nfd.txt | unicode read -n NFD -l
No.  Chr    EAA SZ CP   Name
==== ====== === == ==== ==========
  1: [ほ ] W   2: 307B HIRAGANA LETTER HO
  2: [け ] W   2: 3051 HIRAGANA LETTER KE
  3: [゙ ] W   2: 3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  4: [は ] W   2: 306F HIRAGANA LETTER HA
  5: [け ] W   2: 3051 HIRAGANA LETTER KE
  6: [゙ ] W   2: 3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  7: ['\n'] N   1: 000A None
```

More examples.

```
unicode.py read -f sample/hoge.nfd.txt
unicode.py read -f sample/hoge.nfc.txt -o output.txt
unicode.py read -f sample/hoge.nfc.txt -n NFD -l
```

Usage.

```
% unicode.py read -h
usage: unicode.py read [-h] [-f INPUT_FILE] [-o OUTPUT_FILE] [-l] [-c] [-E]
                       [-n NORMALIZE_MODE]

optional arguments:
  -h, --help            show this help message and exit
  -f INPUT_FILE         specify the filename for input.default is stdin.
  -o OUTPUT_FILE        specify the filename for output.default is stdout.
  -l                    show the unicode name for each charactor.
  -c                    add the number of charactors to the tail.
  -E                    disable to handle the input text as EAA.
  -n NORMALIZE_MODE, --normalize-mode NORMALIZE_MODE
                        specify a mode to normalize. valid mode is: ['NFC',
                        'NFKC', 'NFD', 'NFKD']
```

## Displaying Charactors from Unicode Code Points, or Unicode name.

Examples.

```
% unicode.py show 1F64b 1f3fb
🙋🏻
% unicode.py show 307B 3051 3099
ほげ
% unicode.py show 845B e0100
葛
```

You can find the unicode name of each code point.

```
% unicode.py show 307B 3051 3099 -l
  307B: ほ : HIRAGANA LETTER HO
  3051: け : HIRAGANA LETTER KE
  3099: ゙ : COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
```

With the -s option,
you can see the characors of a range of two code points.

```
% unicode.py show 3041 304F -s
ぁあぃいぅうぇえぉおかがきぎく
```

If you want to specify the code points in integer,
you can use the -i option.
So, below commands result same output.

```
% unicode.py show 12353 12367 -s -i
ぁあぃいぅうぇえぉおかがきぎく
```

You can see the charactors from a part of or full Unicode name.

```
% unicode.py show -n 'SMILING FACE WITH OPEN MOUTH'
😃😄😅😆
```

Usage.

```
% unicode.py show -h
usage: unicode.py show [-h] [-s] [-l] [-i] [-n] [-x] [-N] arg [arg ...]

positional arguments:
  arg               a code point in hex.

optional arguments:
  -h, --help        show this help message and exit
  -s                indicate to show a series of the chars specified by the
                    two code points.
  -l                show the chars in virtical with the unicode name.
  -i                specify that the arg is a code point in integer.
  -n                specify that the arg is a part of a unicode name.
  -x                disable to show a unicode name of the option -l.
  -N, --no-newline  disable to add a newline.
```

## Listing Unicode Charactors.

You can see the charactors in a category you specified.
Below command, you can see a list of categories in the 1st level.

```
% unicode.py list
0: European Scripts
1: Modifier Letters
2: Combining Marks
3: African Scripts
4: Middle Eastern Scripts
5: Central Asian Scripts
6: South Asian Scripts
7: Southeast Asian Scripts
8: Indonesia & Oceania Scripts
9: East Asian Scripts
10: American Scripts
11: Other
12: Notational Systems
13: Punctuation
14: Alphanumeric Symbols
15: Technical Symbols
16: Numbers & Digits
17: Mathematical Symbols
18: Emoji & Pictographs
19: Other Symbols
20: Specials
21: Private Use
22: Surrogates
23: Noncharacters in Charts
```

You can pick one of them to see.  Let's see Emoji and Pictographs.
With the -c option, you can see a list of subcategories under the category.

```
% unicode.py list -c 'Emoji & Pictographs'
## Emoji & Pictographs
0: 'Dingbats'
1: 'Ornamental Dingbats'
2: 'Emoticons'
3: 'Miscellaneous Symbols'
4: 'Miscellaneous Symbols And Pictographs'
5: 'Supplemental Symbols and Pictographs'
6: 'Symbols and Pictographs Extended-A'
7: 'Transport and Map Symbols'
```

You can specify a case insensitive part of the name, or the number of the index.
Below two commands result same output.

```
% unicode.py list -c emoji
% unicode.py list -c 18
```

Now, you can see a list of the charactores in 'Emoticons'

```
% unicode.py list -c 'Emoji & Pictographs' -k Emoticons
Emoticons 1F600-1F64F 80
      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
   0 😔 😕 😖 😗 😘 😙 😚 😛 😜 😝 😞 😟 😠 😡 😢 😣 😤 😥 😦 😧
   1 😨 😩 😪 😫 😬 😭 😮 😯 😰 😱 😲 😳 😴 😵 😶 😷 😸 😹 😺 😻
   2 😼 😽 😾 😿 🙀 🙁 🙂 🙃 🙄 🙅 🙆 🙇 🙈 🙉 🙊 🙋 🙌 🙍 🙎 🙏
```

You can use the -k option as same as the -c option.
So, below two commands result same output.

```
% unicode list -c emoji -k 2
% unicode list -c 18 -k emoti
```

Or, you can just specify 'emoti' as it can search with the entire db.

```
% unicode.py list -k emoti
Emoticons 1F600-1F64F 80
      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19
   0 😔 😕 😖 😗 😘 😙 😚 😛 😜 😝 😞 😟 😠 😡 😢 😣 😤 😥 😦 😧
   1 😨 😩 😪 😫 😬 😭 😮 😯 😰 😱 😲 😳 😴 😵 😶 😷 😸 😹 😺 😻
   2 😼 😽 😾 😿 🙀 🙁 🙂 🙃 🙄 🙅 🙆 🙇 🙈 🙉 🙊 🙋 🙌 🙍 🙎 🙏
```

With the -a option, you can see the entire charactors under the Emoji and Pictgraphs.

```
unicode.py l -c emoji -a
```

You may see many squares.  That means your terminal doesn't support the symbols.

Usage.

```
% unicode.py list -h
usage: unicode list [-h] [-c CATEGORY_HINT] [-a] [-r] [-k KEYWORD_HINT]
                    [--columns NB_COLUMNS]

options:
  -h, --help            show this help message and exit
  -c CATEGORY_HINT      specify a unicode category, which is case-insensitive,
                        can be a part of the name, can be a number in the
                        list.
  -a                    show all chars under the category specified.
  -r                    show the range of code point. It is not valid when the
                        hint unique a subategory or the -a option is used.
  -k KEYWORD_HINT       specify a unicode sub category name, which is case-
                        insensitive, can be a part of the name, can be a
                        number in the list.
  --columns NB_COLUMNS  specify the number of the columns to show.
```

repository: tanupoo/unicode

repo_name: tanupoo/unicode


text:
---
title: IEC 61174 / IEC PAS 61174
menus:
  standards:
    weight: 2
---

This standard is only recommended for exchanging route information with shipping vessels.
{:.bsk-alert.bsk-alert-solid.bsk-alert-info}

## IEC (PAS) 61174

Full citation:

> Maritime navigation and radiocommunication equipment and systems – Electronic chart display and information system
> (ECDIS) – Operational and performance requirements, methods of testing and required test results

This standard consists of several parts/revisions (listed here in chronological order):

* *IEC 61174:2015* (RTZ 1.0) - original standard
* *IEC PAS 61174:2021* (RTZ 1.2) - standard revision

Changes between *IEC 61174:2015* and *IEC PAS 61174:2021* are:

> This PAS has been developed to improve interoperability between equipment implementing route plan exchange format by
> addressing issues uncovered in the original RTZ specification (Annex S of IEC 61174:2015), and in recognition of the
> fact that some manufacturers have identified a pressing business need to implement an improved and expanded version
> of the RTZ format.

Though not an international standard, IEC 61174 is an industry standard, defining both an information model and several encodings used by most equipment manufactures. These encodings are:

* *RTZ* - Route Plan Exchange (XML encoding)
* *RTZP* - RTZ Package (Zip archive encoding, containing an RTZ file and optional supporting assets)

BAS has purchased copies of these standards. BAS staff can contact [MAGIC](mailto:magic@bas.ac.uk){:.bsk-alert-link}
for more information.
{:.bsk-alert.bsk-alert-highlight.bsk-alert-info}

## Profiles

Profiles are not used by this standard.
{:.bsk-alert.bsk-alert-solid.bsk-alert-info}

## Vocabularies

Vocabularies are not used by this standard.
{:.bsk-alert.bsk-alert-solid.bsk-alert-info}

## Extensions

Extensions are not currently supported for this standard.
{:.bsk-alert.bsk-alert-solid.bsk-alert-info}

## Validation

The *IEC 61174* standards family uses [XSD schemas](https://www.w3.org/TR/xmlschema11-1/) for checking records comply
with the standard.

In addition, there are [JSON Schemas](https://github.com/antarctica/metadata-library#supported-configuration-versions)
for this standard for use in the [BAS Metadata Library](https://github.com/antarctica/metadata-library).

### XSD schemas

* [*IEC 61174:2015* (RTZ 1.0)](https://www.cirm.org/rtz/RTZ%20Schema%20version%201_0.xsd)
* [*IEC PAS 61174:2021* (RTZ 1.2)](https://www.cirm.org/rtz/RTZ%20Schema%20version%201_2.xsd)

The BAS Metadata Library can be used to
[validate records](https://github.com/antarctica/metadata-library#validating-a-record){:.bsk-alert-link} against these
schemas.
{:.bsk-alert.bsk-alert-highlight.bsk-alert-success}

repository: antarctica/bas-metadata-standards

branch_name: refs/heads/main

repo_name: antarctica/bas-metadata-standards


text:
# Video Doorbell, Lab 7

*A lab report by Fei Gao*

### In This Report

1. Upload a video of your version of the camera lab to your lab Github repository
1. As usual, update your class Hub repository to add your [forked IDD-Fa18-Lab7](/FAR-Lab/IDD-Fa18-Lab7) repository.
1. Answer the questions in-line below on your README.md.

## Part A. HelloYou from the Raspberry Pi

**a. Link to a video of your HelloYou sketch running.**

[HelloYou](https://www.youtube.com/watch?v=GY_Iy3ZSAF4)

## Part B. Web Camera

**a. Compare `helloYou/server.js` and `IDD-Fa18-Lab7/pictureServer.js`. What elements had to be added or changed to enable the web camera? (Hint: It might be good to know that there is a UNIX command called `diff` that compares files.)**

In order to enable the web camera, we need to import the `node-webcam` library into our webapp. Then we need to create a webcam instance with some pre-defined parameters. Then we bind the "Take a picture" key press with the webcam library's `capture()` method.

**b. Include a video of your working video doorbell**

[Doorbell](https://www.youtube.com/watch?v=P-3-B8mdE0U)

## Part C. Make it your own

**a. Find, install, and try out a node-based library and try to incorporate into your lab. Document your successes and failures (totally okay!) for your writeup. This will help others in class figure out cool new tools and capabilities.**

I installed the gm library to resize the image captured. I spent quite some time debugging, but later realized I needed to install the underlying libraries such as `GraphicsMagick` and `ImageMagick`.

**b. Upload a video of your working modified project**

[Zoom Doorbell](https://www.youtube.com/watch?v=jGnmPLySIpM)
[Source Code](newPictureServer.js)

gha_license_id: MIT


text:
# 应用端联接(Application-side Joins)

We can (partly) emulate a relational database by implementing joins in our application. For instance, let’s say we are indexing users and their blog posts. In the relational world, we would do something like this:
我们可以通过在应用中实现联接来(部分)模拟一个关系型数据库。比如，当我们想要索引用户和他们的博客文章时。在关系型的世界中，我们可以这样做：

```json
PUT /my_index/user/1  (1)
{
  "name":     "John Smith",
  "email"<EMAIL_ADDRESS>  "dob":      "1970/10/24"
}

PUT /my_index/blogpost/2   (2)
{
  "title":    "Relationships",
  "body":     "It's complicated...",
  "user":     1   (3)
}
```

(1)(2) The index, type, and id of each document together function as a primary key. 索引，类型以及每份文档的ID一起构成了主键。

(3) The blogpost links to the user by storing the user’s id. The index and type aren’t required as they are hardcoded in our application. 博文通过保存了用户的ID来联接到用户。由于索引和类型是被硬编码到了应用中的，所以这里并不需要。

Finding blog posts by user with ID 1 is easy:
通过用户ID等于1来找到对应的博文很容易：

```json
GET /my_index/blogpost/_search
{
  "query": {
    "filtered": {
      "filter": {
        "term": { "user": 1 }
      }
    }
  }
}
```

To find blogposts by a user called John, we would need to run two queries: the first would look up all users called John in order to find their IDs, and the second would pass those IDs in a query similar to the preceding one:
为了找到用户John的博文，我们可以执行两条查询：第一条查询用来得到所有名为John的用户的IDs，第二条查询通过这些IDs来得到对应文章：

```json
GET /my_index/user/_search
{
  "query": {
    "match": {
      "name": "John"
    }
  }
}

GET /my_index/blogpost/_search
{
  "query": {
    "filtered": {
      "filter": {
        "terms": { "user": [1] }   (1)
      }
    }
  }
}
```

(1) The values in the terms filter would be populated with the results from the first query. 传入到terms过滤器的值是第一条查询的结果。

The main advantage of application-side joins is that the data is normalized. Changing the user’s name has to happen in only one place: the user document. The disadvantage is that you have to run extra queries in order to join documents at search time.
应用端联接最大的优势在于数据是规范化了的。改变用户的名字只需要在一个地方操作：用户对应的文档。劣势在于你需要在搜索期间运行额外的查询来联接文档。

In this example, there was only one user who matched our first query, but in the real world we could easily have millions of users named John. Including all of their IDs in the second query would make for a very large query, and one that has to do millions of term lookups.
在这个例子中，只有一位用户匹配了第一条查询，但是在实际应用中可能轻易就得到了数以百万计的名为John的用户。将所有的IDs传入到第二个查询中会让该查询非常巨大，它需要执行百万计的term查询。

This approach is suitable when the first entity (the user in this example) has a small number of documents and, preferably, they seldom change. This would allow the application to cache the results and avoid running the first query often.
这种方法在第一个实体的文档数量较小并且它们很少改变时合适(这个例子中实体指的是用户)。这就使得通过缓存结果来避免频繁查询成为可能。

url: https://raw.githubusercontent.com/planJava/java-learning-notes-cn/a8acca39fe9946137d16f2c7c36ff356d085360c/Elasticsearch/40 - handling relationships/1 - application-side joins.md

repository: planJava/java-learning-notes-cn

filename: 1 - application-side joins.md

repo_name: planJava/java-learning-notes-cn


text:
lasttalon.dev

This is LastTalon's [website]. Its used to display personal projects and
information. Keep track of what LastTalon is up to.

## Installation

Most people will not need to install, simply view the [website] online.

If you wish to contribute or build the website yourself you can install the
necessary dependencies by running `npm install` in the package directory.

Once all dependencies are installed you can run `npm run develop` or
`gatsby develop` and open http://localhost:8000/ to view the website.

## Contributing

This is a personal website. We don't expect contributions, but contributions are
welcome!

Check our [contribution guide][contributing] and [code of conduct][conduct] when
getting involved.

## License

This website is free software available under the MIT license. See the [license]
for details.

[license]: LICENCE.md
[conduct]: CODE_OF_CONDUCT.md
[contributing]: CONTRIBUTING.md
[website]: https://lasttalon.dev/


text:
# Data Types

## Primitive Data Types

The knowledge statements contains a scalar objects -- literals. Literals are either language-tagged string `rdf:langString` or _type-safe_ values `xsd:string` containing a reference to data-type. This section defines data-types supported by the library, its mapping to Erlang native types and relation to existed schema(s) and ontologies.

### binary

The binary data-type represents character strings in knowledge statements. The language strings are annotated with corresponding tag.

Lang | Data type
---  | ---
Erlang | `-type binary().`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#string"

### integer

The library derives an arbitrary-precision Integers from Erlang (only limited by available memory on the machine).

Lang | Data type
---  | ---
Erlang | `-type integer().`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#integer"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#long"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#int"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#short"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#byte"

### float

The value is the IEEE 754 double-precision 64-bit floating point type.

Lang | Data type
---  | ---
Erlang | `-type float().`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#decimal"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#float"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#double"

### boolean

The value is either true or false, representing a logic values

Lang | Data type
---  | ---
Erlang | `-type true | false.`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#boolean"

### datetime

The date-time value is closely related to calendar dates and times described by ISO 8601, covering AD and BC eras. Erlang native date format is triple of integers giving micro-seconds precision (see tempus interface). The external representation is ISO 8601.

Lang | Data type
---  | ---
Erlang | `-type {integer(), integer(), integer()}.`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#dateTime"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#date"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#time"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#gYearMonth"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#gYear"

Note that library uses same native format to manipulate with:
* _date_ represent the beginning of each date, implicitly set time to '00:00:00'
* _time_ represents an instant of time that recurs every day. It is counted as number of microseconds from beginning of epoch 1970-01-01.
* _gYearMonth_ represents a specific Gregorian month in a specific year, implicitly set time to beginning of month first day at '00:00:00'.
* _gYear_ represents a Gregorian calendar year, implicitly set time to beginning of year first month, first day at '00:00:00'.

### recursive date time

XSD defines set of recursive data-types. They are not yet natively supported by library and translated as strings

Lang | Data type
---  | ---
Erlang | `-type binary().`
RDF | xmlns:xsd="http://www.w3.org/2001/XMLSchema#gMonthDay"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#gMonth"
    | xmlns:xsd="http://www.w3.org/2001/XMLSchema#gDay"

### geo

The geographical coordinates are hashed using GeoHash, ensuring 3.7cm x 1.8cm precision. The hashing is only applied to `georss:point`. Other formats are not supported yet.

Lang | Data type
---  | ---
Erlang | `-type binary().`
RDF | xmlns:xsd="http://www.georss.org/georss/point"
    | xmlns:xsd="http://www.georss.org/georss/hash"

### not supported

* xmlns:xsd="http://www.w3.org/2001/XMLSchema#duration"
* xmlns:xsd="http://www.w3.org/2001/XMLSchema#hexBinary"
* xmlns:xsd="http://www.w3.org/2001/XMLSchema#base64Binary"

## Reference
1. http://www.w3.org/TR/xmlschema-2/
2. https://en.wikipedia.org/wiki/Geohash


text:
General Container Library for C Language
========================================

Introduction
------------

This is a C library to offer a set of easy use general containers.

Features
--------

* This library support the following types of container:

    * Array.
    * Linked list.
    * Queue (first in, first out list).
    * Stack (last in, first out list).
    * Key map.

* Suppot multiple sub types of container:

    * Container templates (implemented by macros) that can be used easily.
    * Pure container without memory management and iterator
        that can be used on embedd environment.

    Please see the following sections for more information in details.

* Optional thread safe behaviour.

    We build a compile-time option to enable or disable the thread safe behaviour,
    so that users can operate container in multiple threads without external locks.
    (This option is enabled by default)

    The following are examples to enable and disable thread safe behaviour:

        cmake -DCCNTR_THREAD_SAFE=ON /path/to/source

        cmake -DCCNTR_THREAD_SAFE=OFF /path/to/source

    (Please notice that the thread safe behaviour is design to
    protect the container it self without iterators!)

Sub Types
---------

For each major type of container,
we implement 3 sub types for different occasion and preference:

1. Pure container.

    The pure container concentrate on container operations,
    and do not involved in memory allocation and user data.
    That means user will be needs to handle menory allocation
    and data convertion by their self,
    but will have a pure and light container,
    or extend to their own container based on it.

    The pure container (class and functions)
    will be named as `ccntr_<type>_*`.

2. Memory managed container.

    The managed container handles and hide things about element nodes and memory,
    so that user can operator with user defined values
    without element management ant convertion.

    The managed container will be named as `ccntr_man_<type>_*`.

3. Container template.

    The container templates are similarly to managed container,
    but handles user data type convertion.
    user can build their container class with specific data type and class name
    by `CCNTR_DECLARE_<type>` macro.

    The container be built by template will be named as `<user_defined_name>_*`.

Documentation
-------------

*Doxygen* can be used to generate the full document,
and please refer that to use library in details:

    doxygen

By the other way, Examples in the next session can be used to quick start.

Examples
--------

The following codes are two examples to show how to use this library.
We only use linked list container as examples,
and the others are similarly.

### List Template

    #include <stdlib.h>  // For memory allocation.
    #include <stdio.h>   // For message print.
    #include <ccntr.h>   // To use our containers.

    // We define our element data type here.
    typedef struct element_t
    {
        int value;
    } element_t;

    element_t* element_create(int value)
    {
        // Create and initialise our element object.
        element_t *ele = malloc(sizeof(element_t));
        ele->value = value;
        return ele;
    }

    void element_release(element_t *ele)
    {
        // Destroy our element object.
        free(ele);
    }

    // Use CCNTR_DECLARE_LIST macro to build our list class with
    // class name "mylist", and element type "element_t*".
    // Note that we assign the function "element_release" to the container,
    // then we will not need to release each element when we erase it
    // from container.
    CCNTR_DECLARE_LIST(mylist, element_t*, (void(*)(void*))element_release)

    int main(int argc, char *argv[])
    {
        // Initialise list container.

        mylist_t list;
        mylist_init(&list);

        // Insert elements.

        element_t *ele = element_create(4);
        mylist_insert_last(&list, ele);

        ele = element_create(6);
        mylist_insert_last(&list, ele);

        ele = element_create(2);
        mylist_insert_first(&list, ele);

        // Get container elements.

        printf("List dump (count=%u):", mylist_get_count(&list));
        for(mylist_citer_t iter = mylist_get_first_c(&list);
            mylist_citer_have_value(&iter);
            mylist_citer_move_next(&iter))
        {
            const element_t *ele = mylist_citer_get_value(&iter);
            printf(" %d", ele->value);
        }
        printf("\n");
        // We will got output for above codes:
        // "List dump (count=3): 2 4 6"

        // Finally, destroy the container when we do not use it any more.
        mylist_destroy(&list);

        return 0;
    }

### Pure List

    #include <stdlib.h>  // For memory allocation.
    #include <stdio.h>   // For message print.
    #include <ccntr.h>   // To use our containers.

    // We define our element data type here.
    typedef struct element_t
    {
        // There must have a container node as a member.
        //
        // And we chose to set the node as the first member of element,
        // so that the address of node and element will be the same.
        // But it is not necessary to set the node as the first member,
        // User can use something like "container_of" macro
        // to get element by node.
        ccntr_list_node_t node;

        // The following variables are user defined member(s).
        int value;

    } element_t;

    element_t* element_create(int value)
    {
        // Create and initialise our element object.
        element_t *ele = malloc(sizeof(element_t));
        ele->value = value;
        return ele;
    }

    void element_release(element_t *ele)
    {
        // Destroy our element object.
        free(ele);
    }

    int main(int argc, char *argv[])
    {
        // Initialise list container.

        ccntr_list_t list;
        ccntr_list_init(&list);

        // Insert elements.

        element_t *ele = element_create(4);
        ccntr_list_link_last(&list, &ele->node);

        ele = element_create(6);
        ccntr_list_link_last(&list, &ele->node);

        ele = element_create(2);
        ccntr_list_link_first(&list, &ele->node);

        // Get container elements.

        printf("List dump (count=%u):", ccntr_list_get_count(&list));
        for(const ccntr_list_node_t *node = ccntr_list_get_first_c(&list);
            node;
            node = node->next)
        {
            const element_t *ele = (const element_t*) node;
            printf(" %d", ele->value);
        }
        printf("\n");
        // We will got output for above codes:
        // "List dump (count=3): 2 4 6"

        // Pop and release all elements.
        //
        // We need to get all nodes and free it by ourself,
        // because the container does not handle memory management.
        for(ccntr_list_node_t *node = ccntr_list_get_first(&list);
            node;
            node = node->next)
        {
            element_t *ele = (element_t*) node;
            ccntr_list_unlink(&list, &ele->node);  // Remark (1).
            element_release(ele);
        }

        ccntr_list_discard_all(&list);  // Remark (2).

        // Remarks:
        //
        // If we are going to erase all elements,
        // then unlink each nodes (1) are not necessary.
        // We can just go through all nodes and free it,
        // then use discard function (2) to discard all nodes in the container.
        //
        // If you are finished using the container,
        // then you can even free all elements and just leave the container there.
        // The key point is that
        // pure containers do nothing about memory management.

        return 0;
    }

license: Zlib

repository: iceignatius/ccntr

repo_name: iceignatius/ccntr


text:
# 1337 enhancer

A zero dependency chrome extension which enhances the over all user experience in 1337x sites.

## Features
1. Allows sorting the table based on Seeds, Leech, Size and uploader.
2. Allows batch copying magnet links.
3. Adds a new column to the table with the magnet link to the torrent.
4. Adds the screenshot from the torrent description to a popup on hovering.
5. Customizable options. For example, disable hover popups or specifying the width of the popup.
6. Many more...

## Building locally
- Clone or download the repo `git clone https://github.com/rishav394/1337-enhancer.git`
- Install all dev-dependencies `npm i`
- `npm run dev`

## Currently supported sites
- [x] 1337.root.yt
- [x] 1337x.to
- [x] 1337x.st
- [x] x1337x.ws
- [x] x1337x.eu
- [x] x1337x.se
- [x] 1337x.is
- [x] 1337x.gd

## Current plans
- [ ] Convert manifest to version 3
- [ ] Make pug file generic that auto makes rows and values according to option types
- [ ] Implement React based popup

## Contribution

I don't spend a lot of time developing this extension and made it specifically for my use case.
Any help, suggestion, contribution, criticism etc are welcome.

## Read before submitting a PR
- Its okay if your PR breaks the *zero dependency theme* as long as its worth it.
- Avoid JQuery, lodash, axios at all costs. Why? Everything they can do, vanilla JS can do with more code.
- Avoid loading scripts from cdns. Use NPM packages instead.

For support feel free to create an [Issue](https://github.com/rishav394/1337-enhancer/issues)


text:
frequency [![ci](https://github.com/smhg/date-frequency-js/actions/workflows/ci.yml/badge.svg)](https://github.com/smhg/date-frequency-js/actions/workflows/ci.yml)
=========
> Temporal frequency library

## Installation
```sh
npm install --save date-frequency
```

## Usage
```javascript
createFrequency()
  .on('hour', 10)
  .on('minute', 30)
  .next(); // next occurence of 10:30

// or, with a ISO-inspired string format
createFrequency('FT10M30')
  .next(); // next occurence of 10:30

createFrequency()
  .on('day', 2, 'week')
  .next(); // next Tuesday

// all occurences of 10:00:00 in the next 5 days
const d = new Date();
createFrequency()
  .on('hour', 10)
  .on('m', 0)
  .on('s', 0)
  .between(d, (new Date(+d)).setDate(d.getDate() + 5));
```

## Methods
### createFrequency()
Constructor takes a string notation or rules object.
```javascript
createFrequency('F3D/WT10H30M0S'); // every Wednesday at 10:30:00

// equals to:
createFrequency({D: {W: 3}, h: {D: 10}, m: {h: 30}, s: {m: 0}});
```

### .on(unit, value[, scope])
Add frequency rules by specifying a unit, a value to fix it to and, optionally, a scope.
```javascript
frequency.on('hour', 10).on('minute', 0).on('second', 0);
// each day at 10:00:00

frequency.on('day', 6).on('m', 30);
// each 30 minutes after the hour of the 6th day of each month

frequency.on('d', 7, 'week');
// Sundays at midnight
```

The value argument can also be a string which matches the name of a predefined function available in the `fn` property of the constructor.
```javascript
createFrequency.fn.even = require('number-kind').even;
createFrequency()
	.on('week', 'even', 'epoch')
	.on('h', 0)
	.on('m', 0)
	.on('s', 0);
// days of even weeks at midnight
```

### .next([date])
Returns the next occurence of the frequency after _or on_ the specified date. Please note that you are responsible for incrementing the date if you want to call `.next()` multiple times to get consecutive occurences.
If no date is specified, `new Date()` is used.

### .between(start, end)
Returns all occurences of the frequency between (and including) the specified start and end date.

### .toString()
Returns a string notation of the frequency.

## Development
* Clone repo & `npm install`.
* Lint: `npm run lint`.
* Test: `npm test`.

repository: smhg/date-frequency-js

repo_name: smhg/date-frequency-js


text:
+++
# Accomplishments widget.
widget = "accomplishments"  # See https://sourcethemes.com/academic/docs/page-builder/
headless = true  # This file represents a page section.
active = true  # Activate this widget? true/false
weight = 50  # Order that this section will appear.

title = "Honors and Awards"
subtitle = ""

# Date format
#   Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "2006"

# Accomplishments.
#   Add/remove as many `[[item]]` blocks below as you like.
#   `title`, `organization` and `date_start` are the required parameters.
#   Leave other parameters empty if not required.
#   Begin/end multi-line descriptions with 3 quotes `"""`.

[[item]]
  organization = "Stanford University"
  #organization_url = "https://www.coursera.org"
  title = "NVIDIA"
  url = ""
  #certificate_url = "https://www.coursera.org"
  date_start = "2012-09-01"
  date_end = "2014-09-01"
  description = "2 year fellowship by NVIDIA, under the CUDA Center of Excellence (CCOE) program."

[[item]]
  organization = "Stanford University"
  #organization_url = "https://www.coursera.org"
  title = "Library of Congress"
  url = ""
  #certificate_url = "https://www.coursera.org"
  date_start = "2011-09-01"
  date_end = "2012-09-01"
  description = "Full research scholarship by the Library of Congress under the Computational Approaches to Digital Stewardship (CADS) program."

[[item]]
  organization = "Fulbright"
  #organization_url = "https://www.coursera.org"
  title = "Fulbright Fellowship"
  url = ""
  #certificate_url = "https://www.coursera.org"
  date_start = "2010-09-01"
  date_end = "2011-09-01"
  description = ""

[[item]]
  organization = "Nuffic"
  organization_url = "https://www.edx.org"
  title = "Huygens Talent Scholarship"
  url = "https://www.edx.org/professional-certificate/uc-berkeleyx-blockchain-fundamentals"
  #certificate_url = "https://www.edx.org"
  date_start = "2010-09-01"
  date_end = "2011-09-01"
  description = "National Award for Best Students in the Netherlands."

[[item]]
  organization = "Delft University of Technology"
  organization_url = "https://www.datacamp.com"
  title = "EEMCS Faculty Scholarship"
  url = ""
  certificate_url = ""
  date_start = "2009-09-01"
  date_end = "2011-06-01"
  description = "Scholarship from Delft University of Technology for research."

+++


text:
---
title: "Pagination"
---

import { ExampleTabs } from "../../../../components/mdx/example-tabs";

Pagination is one of the most common problems that we have to solve when implementing our backend. Often, sets of data are too large to pass them directly to the consumer of our service.

Pagination solves this problem by giving the consumer the ability to fetch a set in chunks.

# Connections

_Connections_ are a standardized way to expose pagination to clients.

Instead of returning a list of entries, we return a _Connection_.

```sdl
type Query {
  users(first: Int after: String last: Int before: String): UserConnection
}

type UserConnection {
  pageInfo: PageInfo!
  edges: [UserEdge!]
  nodes: [User!]
}

type UserEdge {
  cursor: String!
  node: User!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}
```

You can learn more about this in the [GraphQL Cursor Connections Specification](https://relay.dev/graphql/connections.htm).

> Note: _Connections_ are often associated with _cursor-based_ pagination, due to the use of a _cursor_. Nonetheless, since the specification describes the _cursor_ as opaque, it can be used to facilitate an _offset_ as well.

## Usage

Adding pagination capabilties to our fields is a breeze. All we have to do is add the `UsePaging` middleware.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
public class Query
{
    [UsePaging]
    public IEnumerable<User> GetUsers([Service] IUserRespository repository)
        => repository.GetUsers();
}
```

If we need to specify the concrete node type of our pagination, we can do so by passing a Type as the constructor argument `[UsePaging(typeof(User))]`.

The `UsePaging` attribute also allows us to configure some other properties, like `DefaultPageSize`, `MaxPageSize` and `IncludeTotalCount`.

```csharp
[UsePaging(MaxPageSize = 50)]
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor
            .Field("users")
            .UsePaging()
            .Resolve(context =>
            {
                var repository = context.Service<IUserRespository>();

                return repository.GetUsers();
            });
    }
}
```

If we need to specify the concrete node type of our pagination, we can do so via the generic argument: `UsePaging<UserType>()`.

We can also configure the `UsePaging` middleware further, by specifying `PagingOptions`.

```csharp
descriptor.UsePaging(options: new PagingOptions
{
    MaxPageSize = 50
});
```

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

For the `UsePaging` middleware to work, our resolver needs to return an `IEnumerable<T>` or an `IQueryable<T>`. The middleware will then apply the pagination arguments to what we have returned. In the case of an `IQueryable<T>` this means that the pagination operations can be directly translated to native database queries, through database drivers like EntityFramework or the MongoDB client.

## Customization

If we need more control over the pagination process we can do so, by returning a `Connection<T>`.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
public class Query
{
    [UsePaging]
    public Connection<User> GetUsers(string? after, int? first, string sortBy)
    {
        // get users using the above arguments
        IEnumerable<User> users = null;

        var edges = users.Select(user => new Edge<User>(user, user.Id))
                            .ToList();
        var pageInfo = new ConnectionPageInfo(false, false, null, null);

        var connection = new Connection<User>(edges, pageInfo,
                            ct => ValueTask.FromResult(0));

        return connection;
    }
}
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor
            .Field("users")
            .UsePaging()
            .Argument("sortBy", a => a.Type<NonNullType<StringType>>())
            .Resolve(context =>
            {
                var after = context.ArgumentValue<string?>("after");
                var first = context.ArgumentValue<int?>("first");
                var sortBy = context.ArgumentValue<string>("sortBy");

                // get users using the above arguments
                IEnumerable<User> users = null;

                var edges = users.Select(user => new Edge<User>(user, user.Id))
                                    .ToList();
                var pageInfo = new ConnectionPageInfo(false, false, null, null);

                var connection = new Connection<User>(edges, pageInfo,
                                    ct => ValueTask.FromResult(0));

                return connection;
            });
    }
}
```

If we need to work on an even lower level, we could also use `descriptor.AddPagingArguments()` and `descriptor.Type<ConnectionType<UserType>>()` to get rid of the `UsePaging` middleware.

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

## Total count

Sometimes we might want to return the total number of pageable entries.

For this to work we need to enable the `IncludeTotalCount` flag on the `UsePaging` middleware.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
[UsePaging(IncludeTotalCount = true)]
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
descriptor.UsePaging(options: new PagingOptions
{
    IncludeTotalCount = true
});
```

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

This will add a new field called `totalCount` to our _Connection_.

```sdl
type UserConnection {
  pageInfo: PageInfo!
  edges: [UserEdge!]
  nodes: [User!]
  totalCount: Int!
}
```

If our resolver returns an `IEnumerable<T>` or an `IQueryable<T>` the `totalCount` will be automatically computed, if it has been specified as a subfield in the query.

If we have customized our pagination and our resolver now returns a `Connection<T>`, we have to explicitly declare how the `totalCount` value is computed.

```csharp
var connection = new Connection<User>(
    edges,
    pageInfo,
    getTotalCount: cancellationToken => ValueTask.FromResult(0));
```

# Offset Pagination

> Note: While we support _offset-based_ pagination, we highly encourage the use of [_Connections_](#connections) instead. _Connections_ provide an abstraction which makes it easier to switch to another pagination mechanism later on.

Besides _Connections_ we can also expose a more traditional _offset-based_ pagination.

```sdl
type Query {
  users(skip: Int take: Int): UserCollectionSegment
}

type UserCollectionSegment {
  items: [User!]
  pageInfo: CollectionSegmentInfo!
}

type CollectionSegmentInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
}
```

## Usage

To add _offset-based_ pagination capabilties to our fields we have to add the `UseOffsetPaging` middleware.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
public class Query
{
    [UseOffsetPaging]
    public IEnumerable<User> GetUsers([Service] IUserRespository repository)
        => repository.GetUsers();
}
```

If we need to specify the concrete node type of our pagination, we can do so by passing a Type as the constructor argument `[UseOffsetPaging(typeof(User))]`.

The `UseOffsetPaging` attribute also allows us to configure some other properties, like `DefaultPageSize`, `MaxPageSize` and `IncludeTotalCount`.

```csharp
[UseOffsetPaging(MaxPageSize = 50)]
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor
            .Field("users")
            .UseOffsetPaging()
            .Resolve(context =>
            {
                var repository = context.Service<IUserRespository>();

                return repository.GetUsers();
            });
    }
}
```

If we need to specify the concrete node type of our pagination, we can do so via the generic argument: `UseOffsetPaging<UserType>()`.

We can also configure the `UseOffsetPaging` middleware further, by specifying `PagingOptions`.

```csharp
descriptor.UseOffsetPaging(options: new PagingOptions
{
    MaxPageSize = 50
});
```

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

For the `UseOffsetPaging` middleware to work, our resolver needs to return an `IEnumerable<T>` or an `IQueryable<T>`. The middleware will then apply the pagination arguments to what we have returned. In the case of an `IQueryable<T>` this means that the pagination operations can be directly translated to native database queries, through database drivers like EntityFramework or the MongoDB client.

## Customization

If we need more control over the pagination process we can do so, by returning a `CollectionSegment<T>`.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
public class Query
{
    [UseOffsetPaging]
    public CollectionSegment<User> GetUsers(int? skip, int? take, string sortBy)
    {
        /// get users using the above arguments
        IEnumerable<User> users = null;

        var pageInfo = new CollectionSegmentInfo(false, false);

        var collectionSegment = new CollectionSegment<User>(
            users,
            pageInfo,
            ct => ValueTask.FromResult(0));

        return collectionSegment;
    }
}
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor
            .Field("users")
            .UseOffsetPaging()
            .Argument("sortBy", a => a.Type<NonNullType<StringType>>())
            .Resolve(context =>
            {
                var skip = context.ArgumentValue<int?>("skip");
                var take = context.ArgumentValue<int?>("take");
                var sortBy = context.ArgumentValue<string>("sortBy");

                // get users using the above arguments
                IEnumerable<User> users = null;

                var pageInfo = new CollectionSegmentInfo(false, false);

                var collectionSegment = new CollectionSegment<User>(
                    users,
                    pageInfo,
                    ct => ValueTask.FromResult(0));

                return collectionSegment;
            });
    }
}
```

If we need to work on an even lower level, we could also use `descriptor.AddOffsetPagingArguments()` and `descriptor.Type<CollectionSegmentType<UserType>>()` to get rid of the `UseOffsetPaging` middleware.

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

## Total count

Sometimes we might want to return the total number of pageable entries.

For this to work we need to enable the `IncludeTotalCount` flag on the `UseOffsetPaging` middleware.

<ExampleTabs>
<ExampleTabs.Annotation>

```csharp
[UseOffsetPaging(IncludeTotalCount = true)]
```

</ExampleTabs.Annotation>
<ExampleTabs.Code>

```csharp
descriptor.UseOffsetPaging(options: new PagingOptions
{
    IncludeTotalCount = true
});
```

</ExampleTabs.Code>
<ExampleTabs.Schema>

⚠ Schema-first does currently not support pagination!

</ExampleTabs.Schema>
</ExampleTabs>

This will add a new field called `totalCount` to our _CollectionSegment_.

```sdl
type UserCollectionSegment {
  pageInfo: CollectionSegmentInfo!
  items: [User!]
  totalCount: Int!
}
```

If our resolver returns an `IEnumerable<T>` or an `IQueryable<T>` the `totalCount` will be automatically computed, if it has been specified as a subfield in the query.

If we have customized our pagination and our resolver now returns a `CollectionSegment<T>`, we have to explicitly declare how the `totalCount` value is computed.

```csharp
var collectionSegment = new CollectionSegment<User>(
    items,
    pageInfo,
    getTotalCount: cancellationToken => ValueTask.FromResult(0));
```

# Pagination defaults

If we want to enforce consistent pagination defaults throughout our app, we can do so, by setting the global `PagingOptions`.

```csharp
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddGraphQLServer()
            // ...
            .SetPagingOptions(new PagingOptions
            {
                MaxPageSize = 50
            });
    }
}
```

# Types of pagination

In this section we will look at the most common pagination approaches and their downsides. There are mainly two concepts we find today: _offset-based_ and _cursor-based_ pagination.

> Note: This section is intended as a brief overview and should not be treated as a definitive guide or recommendation.

## Offset Pagination

_Offset-based_ pagination is found in many server implementations whether the backend is implemented in SOAP, REST or GraphQL.

It is so common, since it is the simplest form of pagination we can implement. All it requires is an `offset` (start index) and a `limit` (number of entries) argument.

```sql
SELECT * FROM Users
ORDER BY Id
LIMIT %limit OFFSET %offset
```

### Problems

But whilst _offset-based_ pagination is simple to implement and works relatively well, there are also some problems:

- Using `OFFSET` on the database-side does not scale well for large datasets. Most databases work with an index instead of numbered rows. This means the database always has to count _offset + limit_ rows, before discarding the _offset_ and only returning the requested number of rows.

- If new entries are written to or removed from our database at high frequency, the _offset_ becomes unreliable, potentially skipping or returning duplicate entries.

## Cursor Pagination

Contrary to the _offset-based_ pagination, where we identify the position of an entry using an _offset_, _cursor-based_ pagination works by returning the pointer to the next entry in our pagination.

To understand this concept better, let's look at an example: We want to paginate over the users in our application.

First we execute the following to receive our first page:

```sql
SELECT * FROM Users
ORDER BY Id
LIMIT %limit
```

`%limit` is actually `limit + 1`. We are doing this to know wether there are more entries in our dataset and to receive the _cursor_ of the next entry (in this case its `Id`). This additional entry will not be returned to the consumer of our pagination.

To now receive the second page, we execute:

```sql
SELECT * FROM Users
WHERE Id >= %cursor
ORDER BY Id
LIMIT %limit
```

Using `WHERE` instead of `OFFSET` is great, since now we can leverage the index of the `Id` field and the database does not have to compute an _offset_.

For this to work though, our _cursor_ needs to be **unique** and **sequential**. Most of the time the _Id_ field will be the best fit.

But what if we need to sort by a field that does not have the aforementioned properties? We can simply combine the field with another field, which has the needed properties (like `Id`), to form a _cursor_.

Let's look at another example: We want to paginate over the users sorted by their birthday.

After receiving the first page, we create a combined _cursor_, like `"1435+2020-12-31"` (`Id` + `Birthday`), of the next entry. To receive the second page, we convert the _cursor_ to its original values (`Id` + `Birthday`) and use them in our query:

```sql
SELECT * FROM Users
WHERE (Birthday >= %cursorBirthday
OR (Birthday = %cursorBirthday AND Id >= %cursorId))
ORDER BY Birthday, Id
LIMIT %limit
```

### Problems

Even though _cursor-based_ pagination can be more performant than _offset-based_ pagination, it comes with some downsides as well:

- When using `WHERE` and `ORDER BY` on a field without an index, it can be slower than using `ORDER BY` with `OFFSET`.

- Since we now only know of the next entry, there is no more concept of pages. If we have a feed or only _Next_ and _Previous_ buttons, this works great, but if we depend on page numbers, we are in a tight spot.

repository: alkharashiam/hotchocolate

repo_name: alkharashiam/hotchocolate


text:
---
layout: post
title:  "susbstitution for algebra"
date:   2019-07-17 15:00:56 +1000
categories: jekyll update
---
in algebra you can substitute numbers instead of pronumerals. to do this first you would define what number the pronumeral is then you would replace the pronumeral in the equation with what it is defined as.

E.G.

$$3h-2m+7$$

$$h=1$$

$$m=2$$

now we substitute the letters to the numbers

$$3*1-2*2+7=3-4+7=6$$

you can also define a pronumeral to be a equation. these equations can sometimes have more pronumerals in it

E.G.

$$3h-2m+7$$

$$h=2+3$$

$$m=3+z$$

now substitute the equations in. to make it easier you can use brackets for the substitution

$$3(2+3)-2(3+z)+7=15-6+2z+7=16+2z$$

path: /_drafts/2019-07-17-substitution for algebraic equations.markdown

gha_language: HTML


text:
# Meal Tracker, January 20, 2017

## By Erica Nafziger

## Description
This app allows users to track meals based on specified calorie diet. Users can edit, add and delete meals from their meal tracker, with a visual representation of how many calories they have left for the day.

## Prerequisites

You will need the following things properly installed on your computer.

* [Git](http://git-scm.com/)
* [Node.js](http://nodejs.org/) (with NPM)
* [Bower](http://bower.io/)

## Installation

* `git clone Angular-Meal-Tracker`
* `cd Angular-Meal-Tracker`
* `npm install`
* `bower install`

## Running / Development

* `gulp serve`
* Visit the app at [http://localhost:3000](http://localhost:3000/).

### Building

* `gulp build` (development)
* `gulp build --production` (production)

## Technologies Used:
* Angular 2
* Typescript
* Sass
* Node
* Bower

## Supprt and contact details

<EMAIL_ADDRESS>
## Known Bugs

No known bugs at this time.

###License

* This app is licensed under the MIT license.
* Copyright (c) 2016 Erica Nafziger

repository: ericanafziger/Angular-Meal-Tracker

repo_name: ericanafziger/Angular-Meal-Tracker


text:
---
morea_id: reading-text-24-26
morea_type: reading
title: "Text: Ch. 2.4 - 2.6 Names and Things"
published: True
morea_start_date: "2016-09-06T00:00:00"
morea_summary: "Section 2.4 - 2.6"
morea_labels:
  - "Textbook"
---

### Text: Ch. 2.4 - 2.6 Names and Things

Read Chapter 2, sections 4 thru 6 of [Introduction to Programming Using Java, Seventh Edition]({{ site.baseurl }}/javanotes7.0.1-web-site/c2/index.html)

2.1 The Basic Java Application

2.2 Variables and Types

2.3 Objects and Subroutines

**2.4 Text Input and Output**

**2.5 Details of Expressions**

**2.6 Programming Environments**

repository: cammoore/MoreaNextSemester

repo_name: cammoore/MoreaNextSemester


text:
ForegroundViews
=======
Small library that provides Foreground View functionality to most used Android Views with foreground.
If you want support to new View, add an issue :-)

This library is developed based on some other good but not completed approaches of Foreground Views:

### Sources
* [FRelativeLayout][1] made by [Shaka Huang][2]
* [Antonie Merle][3] [post][4] about how custom Foreground Views should work
* [Chris Banes][5] [post][6] that explains which possibilities we have to get the Foreground
 Approach on Android
* [FrameLayout source code][7]

Screenshots
-----------

Usage
-----
You just have to use whatever FView like FrameLayout; just set the android:foreground attribute
as shown below:
```
<com.cesards.android.foregroundviews.ForegroundView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    custom:?="?">

    ... other views ...

</com.cesards.android.foregroundviews.FView>
```
where custom attributes can be:

* __foreground__
Defines the drawable to draw over the content. This can be used as an overlay.

    Just add: ```custom:foreground="@drawable/your_foreground"```

* __foregroundInsidePadding__
Defines whether the foreground drawable should be drawn inside the padding.
This property is false by default except if your background is a NinePatch Drawable.

    Just add: ```custom:foregroundInsidePadding="true"```

* __backgroundAsForeground__
Retrieve the default background and set it as the foreground. Thanks to this, you can get the
default background selector of your theme and set it as your foreground selector if you want.
This property is false  by default.

    Just add: ```custom:foregroundInsidePadding="true"```

Download
--------
Not yet.

Download [the latest JAR][4] or grab via Maven:
```xml
<! -- Coming soon -->
```
or Gradle:
```groovy
# Coming soon
```

Developed By
------------
* César Díez Sánchez -<EMAIL_ADDRESS>

License
-------

    Copyright 2014 DogmaLabs

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

[1]: https://gist.github.com/shakalaca/6199283
[2]: https://github.com/shakalaca
[3]: https://github.com/castorflex
[4]: http://antoine-merle.com/blog/2013/07/17/adding-a-foreground-selector-to-a-view/
[5]: https://github.com/chrisbanes
[6]: https://plus.google.com/+AndroidDevelopers/posts/aHPVDtr6mcp
[7]: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/FrameLayout.java

repository: cesards/ForegroundViews

gha_language: Java

repo_name: cesards/ForegroundViews


text:
---
layout: post
title:  "Basic git command"
date:   2015-11-7 2:44:00
categories: git
subcategory: beginner
comments: true
---

# Display git log
Display git log information nicely
`git log --oneline --decorate --graph`

where `oneline` show commit in one line, `--decorate` give some color and
`--graph` gives graph show.

# Display git branches
* Show all locals and remote branchs
`git branch -a`

* Show all locals branchs only
`git branch`

* Show all remote branchs only
`git branch -r`

# Remove/delete git branch
You can remove either local or remote branch

## Removing local branch
Let you want to delete your locale branch named `foo`
`git branch -d foo`

If branch `foo` have un merged commit then it need to force delete
`git branch -D foo`

## Removing remote branch
You can also use one of the following methods to delete the remote branch.
Let you want to delete remote branch `bar`
`git push --delete origin bar`

Which does the same thing as

`git push origin :serverfix`
but it may be easier to remember.

# Create and checkout to new branch:
`git checkout -b feature/profile-image-crop`

# Show last git commit
* `git show --summray`
this will show commit message
* `git show --stat`
this also show last git commit with change file list

# squashing
`squash` means combine couple of commits. Let you commit 5 commits to implement a feature but some of the commit
was only for `typo`. If you are thinking that all your code should be in one commit. Using  `squash` you can do it.

Let your feature branch name is 'foo-feature' and your base branch name is 'master'

```css
$ git log --oneline origin/master..foo-feature
73bbc09 add migratio
f33b240 do somthimg
f33b301 solve type mistake
```

Above command will show your all commits that you had made for implementing `foo-feature` feature.

`git rebase -i origin/master`

This will open your editor with these contents:

```css
73bbc09 add migratio
f33b240 do somthimg
f33b301 solve type mistake

# Rebase e54a9a9..73bbc09 onto e54a9a9
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# ...
```

Change the pick to squash (or just s) (those commits that you want to squash, at-least leave top commit), save the file and exit. You'll then get another editor with a commit message to edit:

```css
# This is a combination of 3 commits.
# The first commit's message is:
```
Create your commit message and save. That's it.

# branch search
Let you have 40+ branche and most of the time you forget exact branch name. You can search your branc name in different ways

## Using grep
` git branch | grep foo`

above command will return those branches that contain `foo` word

## Using git wildcard search
 You can just use `git branch --list <pattern>` where `<pattern>` can contain wildcards:
`it branch --all --list *Theme*`

The `--all` option will include remote branches in the search.

## set push.default option
- previous `push.default` was `matchin` that means `git push` will push all local branches to matching branches( if does not explicitly set brach)
- new `push.default` is `simple` that means `git push` will push only current local branches to matching branches( if does not explicitly set brach)


text:
# Lykke.Service.Assets

Assets and asset pairs service

Client: [Nuget](https://www.nuget.org/packages/Lykke.Service.Assets.Client/)

# How to use the client

## Initialization

Anyhow, you need to register client types during DI module(s) registration at the program' start up.

Since version 4.1.0 we have two different ways to register the client: the preferred one and the obsolete one.

### Preferred way - using a *container builder*

If you want to use all the advantages of the newest Lykke logging system ([Lykke.Logs](https://github.com/LykkeCity/Lykke.Logs) v5.x and higher), this is the best choice.
Just register the Asset Service client directly in your `ContainerBuilder` instance:

```cs
var builder = new ContainerBuilder();
...
builder.RegisterAssetsClient(
	AssetServiceSettings.Create(
		new Uri(serviceUrl),
		expirationPeriod));
```
where
* `string serviceUrl` - network location of **Lykke.Service.Assets** working instance;
* `TimeSpan expirationPeriod` - local (client) assets cache expiration time period.

:information_source: It's assumed that you have already added Lykke logging to `ContainerBuilder` before. [Here are instructions](https://github.com/LykkeCity/Lykke.Logs/blob/master/README.md) on how you can to.

### Obsolete way - using a *service collection*

In cases when you need to handle some legacy code and\or keep backward compatibility, you still can register Assets Service client using a `ServiceCollection` instance:

```cs
var services = new ServiceCollection();
...
services.RegisterAssetsClient(
	AssetServiceSettings.Create(
		new Uri(serviceUrl),
		expirationPeriod),
	log);
```

where parameters are the same, plus:
* `log` - an instance of any type implementing `ILog`. Is usually passed as an input parameter to the module constructor.

## Usage

Not depending on the way you register Asset Service client, you can use (resolve) the followings:

* `IAssetsservice` - Autorest generated HTTP client for service API;
* `IAssetsServiceWithCache` - cached client for service API, which caches assets and asset pairs with specified expiration period.

gha_language: C#


text:
---
layout: post
title: 191029 TIL React - Redux

permalink: /til/:year/:month/:day/:title/
categories: [1.5막, TIL (Today I Learned)]
comments: true
---

## React ##

### **오늘 공부한 부분**

 - redux

 [설명 출처 - 유튜브](https://www.youtube.com/watch?v=_l8z3TTlQQo)

![image](https://i.redd.it/g25xnwnxgz6x.png)
[사진 출처](https://www.reddit.com/r/reactjs/comments/4r19o8/how_redux_works_for_beginners/)

### **overview with what's happening in Redux**

- store = 모든 state를 모아서 관리, the single source of truth
- provider = store의 state를 컴포넌트가 쓸 수 있게 해줌
- container = connected store cf) presentational component == 덤 컴포넌트, data 모름. prop 받아서 작동
- components = 유저가 보는 화면 (presentational component?), UI rerender
- action = action has specific names of what is about to change in the store && payload (UI에서 fire된 액션 정보)
- reducer = 들어온 모든 action의 타입 봄. 이 action type에 따라 어떻게 state update할 지 결정 / specific reducer chosen ->
 update state -> updated 된 data store에 dispatch
- store = 들어온 최신 data 다시 뿌려줌
-> provider -> container 가 받아서 -> component에서 유저는 최신의 action result를 볼 수 있음.

**=== unidirectional data flow**

### **Redux architecture revolves around a strict unidirectional data flow.**

[redux docs](https://redux.js.org/basics/data-flow)

This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand.
It also encourages data normalization, so that you don't end up with multiple, independent copies of the same data that are unaware of one another.

![68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6d656469612d702e736c69642e65732f75706c6f6164732f3336343831322f696d616765732f323438343535322f415243482d5265647578322d7265616c2e676966](https://user-images.githubusercontent.com/40848630/67752174-dac56d00-fa75-11e9-86fc-c41ea8b7dfc9.gif)
[사진 출처](http://slides.com/jenyaterpil/redux-from-twitter-hype-to-production#/9)

initial state = $0 -> click button (deposit || withdraw) -> fire deposit || withdraw action
-> dispatch -> reducer w/ previous, state -> state에 action 업데이트


text:
# BNetzA EMF Datenbank Scraper

Install requirements:

```
python3 -m venv venv
source venv/bin/activate

pip install -r requirements.txt
```

Test scraper on position:

```
# python emf_scraper.py <lng,lat>
# e.g.
python emf_scraper.py 10.249166,47.350833
```

Run scraper:

```
python emf_scraper.py
```

This creates a `data/` directory and writes results in there.

## Credits

Based on https://github.com/KoelnAPI/data/tree/master/data/communication/bundesnetzagentur-emf

repository: mrlnc/bnetza-emf-scraper

repo_name: mrlnc/bnetza-emf-scraper


text:
Home

Docs

exportfs

exportfs
========

`exportfs` is a helper utility for managing an NFS server.

Used without any parameters, it will just display a list of active
exports, and the hosts that are allowed to access them.

Used with the `r` parameter, it will reread `/etc/exports`.


text:
# wmt-tests
Tests for the CSDMS Web Modeling Tool

## Find Tests

    $ wmt test find .

## Run Tests

    $ wmt test run <path_to_test>

repository: mcflugen/wmt-tests

repo_name: mcflugen/wmt-tests


text:
---
layout: post
title: anaconda-python虚拟环境
tags: python
---

Welcome to Hydrogen!<br>If you saw this post, your blog has been successfully deployed.So enjoy the fun of writing now!

```sh
conda create -n python37 python=3.7
source activate python37
pip install ipykernel
python -m ipykernel install python37
```

### pypi国内源
* 阿里源
```
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host = mirrors.aliyun.com
```


text:
# build-health-endpoint
A proof-of-concept for providing artifact build details in a REST endpoint.  Built with Spring Boot and Maven.
Maven is required to inject compile-time information, Spring Boot is used to make the rest server easier.

This is a proof of concept and will not work as a dependency, instead you should rip the code out and use it yourself

Sample output
----------
```
{
   "artifact":"build-ping",
   "build_date":"2017-11-09 01:49",
   "build_env_spring_profile":"${env.SPRING_PROFILES_ACTIVE}",
   "build_spring_profile":"${spring.profiles.active}",
   "build_os_version":"10.11.6",
   "name":"build-ping",
   "description":"Provides a proof-of-concept controller for showing build details of the current project",
   "build_arch":"x86_64",
   "build_user":"aidan",
   "build_os":"Mac OS X",
   "version":"1.0-SNAPSHOT"
}
```

repository: raidancampbell/build-health-endpoint

repo_name: raidancampbell/build-health-endpoint


text:
# songbird2itunes

[![Build Status](https://travis-ci.org/schnatterer/songbird2itunes.svg?branch=master)](https://travis-ci.org/schnatterer/songbird2itunes)
[![License](https://img.shields.io/github/license/schnatterer/songbird2itunes.svg)](LICENSE)

Migration tool to migrate a songbird database to itunes

## How to use
See the [wiki](https://github.com/schnatterer/songbird2itunes/wiki) for details on how to use.

## History
See [releases](https://github.com/schnatterer/songbird2itunes/releases)


text:
# Gene panels

::: warning NOTE
This documentation is a work in progress and is incomplete.

Please contact developers for more details.
:::

Everything in ELLA revolves around gene panels, and they're an essential part of the configuration. Note that a gene panel doesn't have to be a targeted panel in the traditional sense, but can include all genes in the exome if desired.

A gene panel includes, among other things, the following:

- A list of transcripts, with associated gene name/id and transcript + exon coordinates
- A list of phenotypes, with associated inheritance pattern

To add a new gene panel, run the following command:

``` bash
ella-cli deposit genepanel --folder <path to gene panel directory>
```

Note that `<PanelName>_<version>.transcripts.csv` and `<PanelName>_<version>.phenotypes.csv` files are required.

See `src/vardb/testdata/clinicalGenePanels/` for example gene panels and naming conventions.

repository: dabble-of-devops-consulting/ella

repo_name: dabble-of-devops-consulting/ella


text:
# kolibri-installer-flatpak

## Build and install the flatpak locally

`make build`

## Run Kolibri from within the flatpak

`make start`
(then, Kolibri will be launched in the default web browser at http://<IP_ADDRESS>:8080)

## Stop the flatpak Kolibri service (ungracefully)

`make stop`


text:
# EVM Nonce Manager Github Issue investigation (#1036)
Report stating the work and investigation done in this regard for the [issue](https://github.com/hyperledger/cactus/issues/1036)/

### Issue Description
Architecture, design and development of a higly available setup that does not have nonce related issues with a round robin load balancer fronting a cluster of API servers running EVM connectors so that one could actually be able to run the ledger at peak performance via Cactus.

### Solutions explored/investigated
The various solutions explored/investigated so far are as follows:

##### **nonce-tracker**
**DESCRIPTION**: Maintains global and local nonces and continously polls the global nonces
**ISSUE**: Works with web3 v1.0 references (the provider calls like provider.prototype.sendAsync, getPendingTransactions method etc.)
**CONCLUSION**: nonce-tracker package dropped because of compatibility reasons and workarounds which will make certain calls synchronous (like, to fix the sendAsync call, the following workaround works but makes call synchronous in nature:
`web3.providers.HttpProvider.prototype.sendAsync = web3.providers.HttpProvider.prototype.send`)
**SOLUTION ACCEPTED**: FALSE

##### **mutex/binary-semaphores**
**DESCRIPTION**: Locks the code execution from nonce allocation till sending of signed transaction.
**ISSUE**: The lock information is stored in program heap, which isnt globally available (in case someone tries to run a connector from another machine or another code instance, mutex locks will not work.
**CONCLUSION**: To look for other resources with same functionality and global state storing mechanism.
**SOLUTION ACCEPTED**: FALSE

##### **kafka**
**DESCRIPTION**: Message Queue system which can be used to issue nonces to the tx messages
**ISSUE**:
1. If we pass the transactionRequest to the message queue, then
	   a. We cannot lock the flow from nonce issuance till sending transactions.
	b. As kafka based solution will be a global state store, even if we can set locks from nonce allowance till sending transactions, we cannot guarantee consistency in nonce allowance as these locks cannot control execution of connectors located on other machine.
2. If we pass signedTransactions to the message queue, editing the signed transactions to change nonces isnt a good idea, given this kafka cluster will be globally available.

**CONCLUSION**: Can be explored for local nonce-management, but not for global nonces.
**SOLUTION ACCEPTED**: FALSE

##### red-lock
**DESCRIPTION**: Locks a certain piece of code via global locks which are highly available and fault tolerant
**ISSUE**: The transactions-per-second is very low, because of the presence of a global lock for each account address
**CONCLUSION**: The use of same account on various machines is an example of "wrong use of software" and can be labelled as such.
**SOLUTION ACCEPTED**: FALSE

gha_language: TypeScript


text:
# More Python Completions

A sublime text package that displays total completions of module methods as found on the Python documentation website. Also offers completion for import statements

![preview](preview.gif)

## Usage

* i- --> imports module
* normal typing of method names shows methods for modules
* y-modulename --> shows both module and method e.g. y-method shows modulename.methodname

## Installation
> Important: You need to have `Package Control` installed first on your sublime text which can be found at [The Package Contol Website](http://packagecontrol.io)

### Using Package Control's Repository

Go to `Preferences` --> `Package Control` --> `Add Repository` --> then type into the textbox `https://github.com/tushortz/More-Python-Completions`

After doing this, then go to: `Preferences` --> `Package Control` --> `Install Package` --> then search `More-Python-Completions` and click it.

The package will be installed and ready for use.

### Using Git

Locate your Sublime Text `Packages` directory by using the menu item `Preferences -> Browse Packages...`.

While inside the `Packages` directory, clone the theme repository using the command below:

    git clone https://github.com/tushortz/More-Python-Completions

or just download the zipped folder, extract it and paste the extracted folder into your sublime text packages directory.

## Contributing

All contributions are welcome. fork More Python Completions on [Github](https://github.com/tushortz/More-Python-Completions) and create a pull request. Any suggestions or bugs, please let me know.

## Licence

© 2016 Taiwo Kareem |<EMAIL_ADDRESS>
**Read license.txt**

## Acknowledgements

I'd first like to say a very big thank you to God my creator. Without him, this wouldn't be possible.

repository: tushortz/More-Python-Completions

repo_name: tushortz/More-Python-Completions


text:
# Redshift-Project
Project for ECE-4813

##Task List
- [x] Python Script to merge data to one csv file
- [ ]  Load Data to RedShift
- [ ]  Develop SQL Query
- [ ]  Flask App
- [ ]  PowerPoint Presentation
- [ ]  Project Report

##Assignments
|Task| Team Member|
|:---:|:---:|
|Format Data| Jason|
|Load Data to RedShift|Saketh |
|SQL Analysis|Shivam & Other people|
|Flask| Keary|

gha_language: Python


text:
# Luke's internet connected Christmas Jumper

Because I like building ridiculous things, I decided to make a christmas jumper that can be controlled over the internet.

## Hardware
![Wiring diagram](wiring-diagram.png)

The brains of the whole lot is an ESP8266 running Espruino. This then has a string of battery powered christmas lights attached to it with a MOSFET between the end of the lights and the ground pin. The control pin of the MOSFET is then connected to one of the GPIO pins on the ESP8266 so that the lights can be controlled.

The ESP8266 connects to a Wifi source and then to an MQTT broker to recieve commands.

## Web Client
To send commands to the jumper, there's a web client. This uses MQTT.js to send commands to the MQTT broker. There is no server component, so you can host it on static hosting like Github Pages or Netlify.

## License
MIT

repository: CodeFoodPixels/jumper-lights

repo_name: CodeFoodPixels/jumper-lights


text:
[![Build Status](https://api.travis-ci.org/denisrosset/gluon.png)](https://travis-ci.org/denisrosset/gluon/)

# Gluon - a library for Scala interoperability with dynamic languages

Gluon enables users to write Scala interface code in a robust manner.

The following Matlab code implements the sum of elements of a vector.

```matlab
function res = sumI(vec)
i = com.faacets.gluon.Interface.compile({
    'import com.faacets.gluon._'
    'Interface[Seq[Double], Double]("sumI", "seq") {'
    'seq => seq.sum'
    '}'
                   });
res = i.call(vec);
```

How to compile and pack the deliverables?

- Clone the repo.
- Run `sbt pack` to produce a copy of the Matlab example code and the required jars.
- The libraries and code are copied in `/target/pack`

To run the example code:

- Ensure that the Matlab Java Runtime Environment is at least version 1.8
  by running `version -java`. On Linux, the JRE can be changed by setting
  the MATLAB_JAVA environment variable; on Ubuntu with the Oracle JRE, use
  `export MATLAB_JAVA=/usr/lib/jvm/java-8-oracle/jre`
- Run Matlab, and change to the `/target/pack` directory
- Run `gluon_init` to load the JARs and warm-up the Scala compiler
  It takes generally a few seconds.
- Run `sumI([1 2 3 4])` to try the example code. The first call to
  any interface function requires compilation of Scala code, which
  takes a few hundred milliseconds. The compiled code is cached for
  subsequent calls.

repository: denisrosset/gluon

repo_name: denisrosset/gluon


text:
ScrollableItemList
====================

### Description

An Android RecyclerView List with items that can scroll to reveal more content on the side. This view has been inspired by the one found in the Reddit News App.

### Demo

[![Gif Demo](http://i.imgur.com/9NPgfsN.gif)]

### Notes on using this

The view has been created using standard views now available with Android Lollipop and its compatibility libraries. The list is a `RecyclerView` with a `LinearLayoutManager`. Each item in the list is essentially a ViewPager with two views; a `CardView` and `FrameLayout` with three buttons.

Everything else can be used normally except the ``RecyclerViewAdapter.java`` where most of the work is required.

The challenges were as follows:

**1)** The ViewPager does not inflate properly inside the RecyclerView.

In order to solve this, the width of the ViewPager was manually set to the current width of the screen when it inflates inside the adapter. The height should be specified manaully and `wrap_content` attribute cannot be used.

**2)** The ViewPagers do not retain state as the list items are scrolled away from current view and back.

In order to solve this problem, the `RecyclerViewAdapter` holds a list of states for each of the ViewPager and sets them back when a previously modified item comes back in view.

### License
```
The MIT License (MIT)

Copyright (c) 2016 Rohaan Hamid

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

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

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

repository: AppSecAI-TEST/ScrollableItemList

repo_name: AppSecAI-TEST/ScrollableItemList


text:
## Railscasts 260: Messaging with Faye

Gems: JQuery

We can use other frameworks (Node, Sinatra), but if we want Rails, Faye handles publishing-subscribing asynchronously. There is a Node server and a Ruby server.

We want the benefits of pub-sub only when we need them. We can use this alongside our Rails app

> Installation: Create and make a file.

    $ gem install faye
    $ v faye.ru

> faye.ru

    require  'faye'
    faye_server = Faye::RackAdapter.new(mount: "/faye", timeout: 45)
    run faye_server

> To launch the faye server

    $ rackup faye.ru -s thin -E production
    #=> Starts an open web app at port 9292

> localhost:9292/faye.js

We need to include this in the browser to make sure it update there.

    <%= javascript_include_tag.... %>

[TODO]

license: Unlicense

repository: daryllxd/lifelong-learning

gha_language: Elixir

gha_license_id: Unlicense

repo_name: daryllxd/lifelong-learning


text:
gydict
======

Yahoo Dictionary(<http://tw.dictionary.yahoo.com>) in command line by Groovy.

Usage
-----

You should have Groovy preinstalled in your computer.

1. Download gydict.
2. `chmod +x gydict`.
3. `./gydict test`.

repository: Reder/gydict

repo_name: Reder/gydict