text:
[![Build Status](https://travis-ci.org/mechanicles/ruby_simple_search.svg?branch=master)](https://travis-ci.org/mechanicles/ruby_simple_search)
[![Maintainability](https://api.codeclimate.com/v1/badges/20e84a4c3be302b07653/maintainability)](https://codeclimate.com/github/mechanicles/ruby_simple_search/maintainability)
[![Test Coverage](https://api.codeclimate.com/v1/badges/20e84a4c3be302b07653/test_coverage)](https://codeclimate.com/github/mechanicles/ruby_simple_search/test_coverage)

The simplest way to search the data in ActiveRecord models.

It offers simple but useful features:

- [Search on the default attributes](#search-on-the-default-attributes)
- [Override default search attributes to specific attributes ](#override-default-search-attributes-to-specific-attributes) (Credit goes to [@abdullahtariq1171](https://github.com/abdullahtariq1171))
- [Search using patterns](#search-using-patterns)
- [Ruby block support to extend the search query](#ruby-block-support-to-extend-the-search-query)
- [Simple search returns an `ActiveRecord::Relation` object](#simple-search-returns-an-activerecordrelation-object)

Mostly on the admin side, we do have a standard text field to search the data on the table.
Sometimes we want to search through the attributes like title, content and ratings on the
post model or email, username and description on the user model. For those searches, we use
MySQL's or PostgreSQL's `LIKE` operator to get the results. While doing the same thing again
and again on the different models, you add lots of duplication in your code.

#### Do not repeat yourself, use RubySimpleSearch.

## Installation

Add this line to your application's Gemfile:

    gem 'ruby_simple_search'

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install ruby_simple_search

## Usage

Define attributes that you want to search on it

```Ruby
class Post < ActiveActiveRecord::Base
  include RubySimpleSearch

  simple_search_attributes :title, :description
end
```

```Ruby
class User < ActiveActiveRecord::Base
  include RubySimpleSearch

  simple_search_attributes :email, :username, :address, :age
end
```

## Features

### Search on the default attributes
If you don't provide any attribute at the time of searching, it will use `simple_search_attributes` from the model.

```ruby
class User < ActiveActiveRecord::Base
  include RubySimpleSearch

  simple_search_attributes :email, :username, :address
end

Post.simple_search('york')
# It will search in :email, :username and :address only
```

### Override default search attributes to specific attributes

If you want to perform a specific search on particular attributes, you can pass specific attributes with `attributes` option.

```ruby
class User < ActiveActiveRecord::Base
  include RubySimpleSearch

  simple_search_attributes :email, :username, :address
end

Post.simple_search('york')
# It will search in :email, :username and :address only

Post.simple_search('york', attributes: :address)
# It will search in :address only

User.simple_search('york', pattern: :ending, attributes: [:email, :address])
# It will search in :email and :address only with 'ending' pattern
```

### Search using patterns
You can pass a `LIKE` pattern to the `simple_search` method.

Patterns:

- beginning
- ending
- containing (Default pattern)
- plain

```ruby
Post.simple_search('york', pattern: :beginning)
# It will search like 'york%' and finds any values that start with "york"

Post.simple_search('york', pattern: :ending)
# It will search like '%york' and finds any values that end with "york"

Post.simple_search('york', pattern: :containing)
# It will search like '%york%' and finds any values that have "york" in any position

Post.simple_search('york', pattern: :plain)
# It will search like 'york' and finds any values that have "york" word
```

### Ruby block support to extend the search query

```Ruby
User.simple_search('35') do |search_term|
  ["AND age = ?", search_term]
end
```
Block should return an array of search condition and values.

### Simple search returns an `ActiveRecord::Relation` object

```Ruby
Model.simple_search('string') # => ActiveRecord::Relation object

Model.simple_search('string').to_sql

# OR

User.simple_search('mechanicles') do |search_term|
  ["AND address != ?", search_term]
end.to_sql

# => It will return an SQL query in string format
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
from py2neo.legacy.batch import *
from py2neo.legacy.core import *
from py2neo.legacy.index import *

__all__ = ["LegacyResource", "LegacyNode", "Index", "LegacyReadBatch", "LegacyWriteBatch"]

redpajama_set_name: RedPajamaGithub


text:
/* global exports, console */
"use strict";

// module Control.Monad.Eff.Console.Unsafe

exports.logAny = function (s) {
  return function () {
    console.log(s);
    return {};
  };
};

exports.errorAny = function (s) {
  return function () {
    console.error(s);
    return {};
  };
};


text:
<?php

use Illuminate\Database\Seeder;
use Point\Framework\Helpers\AllocationHelper;

class FixAllocationReportSeeder extends Seeder
{
    public function run()
    {
        \DB::beginTransaction();

        $reports = \Point\Framework\Models\Master\AllocationReport::join('formulir', 'formulir.id', '=', 'allocation_report.formulir_id')->select('allocation_report.*', 'form_number')->get();

        foreach ($reports as $report) {
            // CASH OR BANK OUT & PURCHASING SHOULD BE IN DEBIT AREA, OTHERWISE SALES AND CASH OR BANK IN SHOULD BE IN CREDIT
            if (str_contains($report->form_number, 'PURCHASING') || str_contains($report->form_number, 'OUT/')) {
                if ($report->amount > 0) {
                    $report->amount *= -1;
                    $report->save();
                }
            } elseif (str_contains($report->form_number, 'SALES') || str_contains($report->form_number, 'IN/')) {
                if ($report->amount < 0) {
                    $report->amount *= -1;
                    $report->save();
                }
            }
        }

        \DB::commit();
    }
}


text:
import useApi from "./useApi";

export { useApi };


text:
layout: page
title: About Me
---

I currently work at [Koko](https://itskoko.com/), a VC backed startup focused on at bringing emotional well being to the world. I currently study Machine Learning and Natural Language Processing at Columbia University. My advisor is [Kathy McKeown](http://www.cs.columbia.edu/~kathy/). I also work with [Sam Bowman](https://www.nyu.edu/projects/bowman/) at NYU.

I am an avid learner and ask a lot of questions. I believe asking questions, thinking hard about a problem, and writing your thoughts is an effective process to learn and share ideas. I'm very interested in Natural Language Processing, Machine Learning, and Psychology. I also write on [Medium](https://medium.com/@rtotheohan).

You can find my resume [here]({{site.baseurl}}public/resume.pdf)


text:
@foreach($atts1 as $attribute)

frontend_size }}">
        code }}">{{ $attribute->frontend_label }}
    <?php
        $type=$attribute->frontend_input;
        $select=explode('2',$type); $htmlClass=['class' => 'form-control'];
        if ($attribute->is_required==1) {
            $htmlClass['required']='required';
        }
        $option=explode('|',$attribute->option);
        if (!isset($eavValue1[$attribute->id])){
            $eavValue1[$attribute->id]=null;
        }
    ?>
    @if($type=='select')
        {!! Form::select('attribute['.$attribute->id.']',array_combine($option,$option), $eavValue1[$attribute->id], $htmlClass) !!}
    @elseif($select[0]=='select')
        <?php
            $htmlClass['class']=$htmlClass['class'].' select2-ajax-'.$select[1];
            $userName=$eavValue1[$attribute->id]&&$eavValue1[$attribute->id]>0?(\App\User::find($eavValue1[$attribute->id],['name'])->name):null; ?>
        {!! Form::select('attribute['.$attribute->id.']', [$eavValue1[$attribute->id]=>$userName], $eavValue1[$attribute->id], $htmlClass) !!}
        @section('scripts')

        @endsection
    @else
        {!! Form::$type('attribute['.$attribute->id.']', $eavValue1[$attribute->id], $htmlClass) !!}
    @endif

@endforeach


text:
package net.cryptonomica.constants;

import com.google.api.server.spi.Constant;
import com.google.appengine.api.utils.SystemProperty;

/**
 * Contains the client IDs and scopes for allowed clients consuming your API.
 */
public class Constants {

    /* Values that have to be changed if switching from sandbox to production and vice-versa. SED_START and SED_END variables
     *  are only to mark start and and point for sed (https://www.gnu.org/software/sed/manual/sed.html)
     * */
    static Boolean SED_START;
    public static final Boolean PRODUCTION = Boolean.FALSE;
    public static final String WEB_CLIENT_ID = "517360814873-7pn1cta2addmcvug6rb1jr2u20vv2qnt.apps.googleusercontent.com";
    public static final Integer priceForOneYerInEuroCents = 1 * 100;
    public static final Integer discountInPercentForTwoYears = 60;
    public static final String host = "sandbox-cryptonomica.appspot.com";
    public static final String supportEmailAddress = "support@cryptonomica.net";
    public static final String adminEmailAddress = "admin@cryptonomica.net";
    public static final String verificationServiceEmailAddress = "verification@cryptonomica.net";
    public static final String emailSubjectPrefix = "[sandbox-cryptonomica] ";
    static Boolean SED_END;

    public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID";
    public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
    public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;

    // public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
    public static final String EMAIL_SCOPE = Constant.API_EMAIL_SCOPE;
    public static final String API_EXPLORER_CLIENT_ID = Constant.API_EXPLORER_CLIENT_ID;

    // -------->>> !!!!
    static final String applicationId = SystemProperty.applicationId.get();
    public static final String GAE_PROJECT_DOMAIN =
            applicationId + ".appspot.com";
    public final static String GAE_PROJECT_URL = "https://" + applicationId + ".appspot.com";
    public final static String CLOUDSTORAGE_DEFAULT_BUCKET = GAE_PROJECT_DOMAIN;

}


text:
class GnomadProfile < ApplicationRecord
  belongs_to :user, optional: true
end


text:
@interface SVViewController ()

//@property (nonatomic, strong) SVOneTableViewController *oneVC;
//@property (nonatomic, strong) SVTowViewController *twoVC;
//@property (nonatomic, strong) SVThreeViewController *threeVC;

@property (nonatomic, strong) NSMutableArray *arrVCs;

@end

@implementation SVViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self oneBtnClick:nil];
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"main%s",__func__);
}

- (IBAction)oneBtnClick:(id)sender {
//    [self.twoVC.view removeFromSuperview];
//    [self.threeVC.view removeFromSuperview];
//    self.oneVC.view.frame = CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
//    [self.view addSubview:self.oneVC.view];

    [self selectViewController:0];

}
- (IBAction)twoBtnClick {
//    [self.oneVC.view removeFromSuperview];
//    [self.threeVC.view removeFromSuperview];
//    self.twoVC.view.frame = CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
//    [self.view addSubview:self.twoVC.view];

        [self selectViewController:1];
}
- (IBAction)threeBtnClick {
//    [self.oneVC.view removeFromSuperview];
//    [self.twoVC.view removeFromSuperview];
//    self.threeVC.view.frame = CGRectMake(0, 44, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 44);
//    [self.view addSubview:self.threeVC.view];

        [self selectViewController:2];
}

- (void)selectViewController:(NSInteger)index {
//    [self.oneVC.view removeFromSuperview];
//    [self.twoVC.view removeFromSuperview];
//    [self.view removeFromSuperview];
    NSArray *arr = self.view.subviews;
    arr = nil;
//    self.view.subviews = arr;

    UIViewController *vc = self.arrVCs[index];
    vc.view.frame = CGRectMake(0, 44, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 44);
    [self.view addSubview:vc.view];
}

-(NSMutableArray *)arrVCs {
    SVOneTableViewController *oneVC = [[SVOneTableViewController alloc] init];
    SVTowViewController *twoVC = [[SVTowViewController alloc] init];
    SVThreeViewController *threeVC = [[SVThreeViewController alloc] init];

    if (!_arrVCs) {
        _arrVCs = @[oneVC, twoVC, threeVC];
    }

//    self addChildViewController:<#(nonnull UIViewController *)#>
    return _arrVCs;
}

@end


text:
module Azure::Logic::Mgmt::V2018_07_01_preview
  module Models
    #
    # The X12 agreement envelope settings.
    #
    class X12EnvelopeSettings

      include MsRestAzure

      # @return [Integer] The controls standards id.
      attr_accessor :control_standards_id

      # @return [Boolean] The value indicating whether to use control standards
      # id as repetition character.
      attr_accessor :use_control_standards_id_as_repetition_character

      # @return [String] The sender application id.
      attr_accessor :sender_application_id

      # @return [String] The receiver application id.
      attr_accessor :receiver_application_id

      # @return [String] The control version number.
      attr_accessor :control_version_number

      # @return [Integer] The interchange  control number lower bound.
      attr_accessor :interchange_control_number_lower_bound

      # @return [Integer] The interchange  control number upper bound.
      attr_accessor :interchange_control_number_upper_bound

      # @return [Boolean] The value indicating whether to rollover interchange
      # control number.
      attr_accessor :rollover_interchange_control_number

      # @return [Boolean] The value indicating whether to enable default group
      # headers.
      attr_accessor :enable_default_group_headers

      # @return [String] The functional group id.
      attr_accessor :functional_group_id

      # @return [Integer] The group control number lower bound.
      attr_accessor :group_control_number_lower_bound

      # @return [Integer] The group control number upper bound.
      attr_accessor :group_control_number_upper_bound

      # @return [Boolean] The value indicating whether to rollover group
      # control number.
      attr_accessor :rollover_group_control_number

      # @return [String] The group header agency code.
      attr_accessor :group_header_agency_code

      # @return [String] The group header version.
      attr_accessor :group_header_version

      # @return [Integer] The transaction set control number lower bound.
      attr_accessor :transaction_set_control_number_lower_bound

      # @return [Integer] The transaction set control number upper bound.
      attr_accessor :transaction_set_control_number_upper_bound

      # @return [Boolean] The value indicating whether to rollover transaction
      # set control number.
      attr_accessor :rollover_transaction_set_control_number

      # @return [String] The transaction set control number prefix.
      attr_accessor :transaction_set_control_number_prefix

      # @return [String] The transaction set control number suffix.
      attr_accessor :transaction_set_control_number_suffix

      # @return [Boolean] The value indicating whether to overwrite existing
      # transaction set control number.
      attr_accessor :overwrite_existing_transaction_set_control_number

      # @return [X12DateFormat] The group header date format. Possible values
      # include: 'NotSpecified', 'CCYYMMDD', 'YYMMDD'
      attr_accessor :group_header_date_format

      # @return [X12TimeFormat] The group header time format. Possible values
      # include: 'NotSpecified', 'HHMM', 'HHMMSS', 'HHMMSSdd', 'HHMMSSd'
      attr_accessor :group_header_time_format

      # @return [UsageIndicator] The usage indicator. Possible values include:
      # 'NotSpecified', 'Test', 'Information', 'Production'
      attr_accessor :usage_indicator

      #
      # Mapper for X12EnvelopeSettings class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'X12EnvelopeSettings',
          type: {
            name: 'Composite',
            class_name: 'X12EnvelopeSettings',
            model_properties: {
              control_standards_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'controlStandardsId',
                type: {
                  name: 'Number'
                }
              },
              use_control_standards_id_as_repetition_character: {
                client_side_validation: true,
                required: true,
                serialized_name: 'useControlStandardsIdAsRepetitionCharacter',
                type: {
                  name: 'Boolean'
                }
              },
              sender_application_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'senderApplicationId',
                type: {
                  name: 'String'
                }
              },
              receiver_application_id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'receiverApplicationId',
                type: {
                  name: 'String'
                }
              },
              control_version_number: {
                client_side_validation: true,
                required: true,
                serialized_name: 'controlVersionNumber',
                type: {
                  name: 'String'
                }
              },
              interchange_control_number_lower_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'interchangeControlNumberLowerBound',
                type: {
                  name: 'Number'
                }
              },
              interchange_control_number_upper_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'interchangeControlNumberUpperBound',
                type: {
                  name: 'Number'
                }
              },
              rollover_interchange_control_number: {
                client_side_validation: true,
                required: true,
                serialized_name: 'rolloverInterchangeControlNumber',
                type: {
                  name: 'Boolean'
                }
              },
              enable_default_group_headers: {
                client_side_validation: true,
                required: true,
                serialized_name: 'enableDefaultGroupHeaders',
                type: {
                  name: 'Boolean'
                }
              },
              functional_group_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'functionalGroupId',
                type: {
                  name: 'String'
                }
              },
              group_control_number_lower_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupControlNumberLowerBound',
                type: {
                  name: 'Number'
                }
              },
              group_control_number_upper_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupControlNumberUpperBound',
                type: {
                  name: 'Number'
                }
              },
              rollover_group_control_number: {
                client_side_validation: true,
                required: true,
                serialized_name: 'rolloverGroupControlNumber',
                type: {
                  name: 'Boolean'
                }
              },
              group_header_agency_code: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupHeaderAgencyCode',
                type: {
                  name: 'String'
                }
              },
              group_header_version: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupHeaderVersion',
                type: {
                  name: 'String'
                }
              },
              transaction_set_control_number_lower_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'transactionSetControlNumberLowerBound',
                type: {
                  name: 'Number'
                }
              },
              transaction_set_control_number_upper_bound: {
                client_side_validation: true,
                required: true,
                serialized_name: 'transactionSetControlNumberUpperBound',
                type: {
                  name: 'Number'
                }
              },
              rollover_transaction_set_control_number: {
                client_side_validation: true,
                required: true,
                serialized_name: 'rolloverTransactionSetControlNumber',
                type: {
                  name: 'Boolean'
                }
              },
              transaction_set_control_number_prefix: {
                client_side_validation: true,
                required: false,
                serialized_name: 'transactionSetControlNumberPrefix',
                type: {
                  name: 'String'
                }
              },
              transaction_set_control_number_suffix: {
                client_side_validation: true,
                required: false,
                serialized_name: 'transactionSetControlNumberSuffix',
                type: {
                  name: 'String'
                }
              },
              overwrite_existing_transaction_set_control_number: {
                client_side_validation: true,
                required: true,
                serialized_name: 'overwriteExistingTransactionSetControlNumber',
                type: {
                  name: 'Boolean'
                }
              },
              group_header_date_format: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupHeaderDateFormat',
                type: {
                  name: 'String'
                }
              },
              group_header_time_format: {
                client_side_validation: true,
                required: true,
                serialized_name: 'groupHeaderTimeFormat',
                type: {
                  name: 'String'
                }
              },
              usage_indicator: {
                client_side_validation: true,
                required: true,
                serialized_name: 'usageIndicator',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package ccv2

import (
	"code.cloudfoundry.org/cli/api/cloudcontroller"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/internal"
)

// FeatureFlag represents a Cloud Controller feature flag.
type FeatureFlag struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`
}

func (client Client) GetConfigFeatureFlags() ([]FeatureFlag, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetConfigFeatureFlagsRequest,
	})
	if err != nil {
		return nil, nil, err
	}

	var featureFlags []FeatureFlag
	response := cloudcontroller.Response{
		Result: &featureFlags,
	}

	err = client.connection.Make(request, &response)
	return featureFlags, response.Warnings, err
}


text:
import expect from 'expect';

describe('Root Test File ', () => {
    it('should get initialized', () => {
        //writing a dummy assertion
        expect(true).toEqual(true);
    });
});


text:
interface FileSystem {
  read: number;
}

function fn(s: WorkerFS): void;
function fn(s: FileSystem): void;
function fn(s: FileSystem|WorkerFS) { }

// This should issue a large error, not a small one
class WorkerFS implements FileSystem {
  read: string;
}

interface Alpha { x: string; }
interface Beta { y: number; }
var x: Alpha;
var y: Beta;

// Only one of these errors should be large
x = y;
x = y;

// Only one of these errors should be large
y = x;
y = x;


text:
			Category for <?php echo ucwords($title);?>

 Home

CMS

Category

			<?php include('message_after_transaction.php');?>

						<form role="form" id="form" method="post" action="<?php echo base_url();?>cms/category_update">
							<input type="hidden" name="type" value="<?php echo $title;?>" />
							<input type="hidden" name="id" id="id-edit" />

								<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit Category

										Category
										<input type="text" class="form-control input-sm" id="name-edit" name="category" placeholder="" required>

										Slug *good keywords
										<input type="text" class="form-control input-sm" id="slug-edit" name="slug" placeholder="" required >

										Parent Category
										<select class="form-control" id="parent-edit" name="parent">
											<option value="">--Please select--</option>
											<?php if($category <> false)
												foreach($category->result() as $row){?>
											<option value="<?php echo $row->id;?>"><?php echo $row->category;?></option>
											<?php } ?>
										</select>

								<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
								<button type="submit" class="btn btn-primary">Save Changes</button>

						</form>

List of Category

							Category
							Parent Category
							Slug
							Action

						<?php if($category<>false)
							foreach($category->result() as $row){?>

							<?php echo $row->category;?>
							<?php echo $parent[$row->id];?>
							<?php echo $row->slug;?>

								<button class="btn btn-primary btn-xs" onclick="modal_set(<?php echo $row->id;?>)">
									 Edit
								</button>
								<?php if($row->parent_id<>"0"){ ?>
								<a href="<?php echo base_url('cms/category_delete?ty='.$title.'&id='.$row->id);?>" onclick="return confirm('Do you want to delete <?php echo $row->category;?>');">
									<button class="btn btn-danger btn-xs">
										 Delete
									</button>

								<?php } ?>

						<?php }	?>

Add new Category

					<form role="form" id="form" method="post" action="<?php echo base_url();?>cms/category_add">
						<input type="hidden" name="type" value="<?php echo $title;?>" />

								Category
								<input type="text" class="form-control input-sm" id="name" name="category" placeholder="" required >

								Slug *good keywords
								<input type="text" class="form-control input-sm" id="slug" name="slug" placeholder="" required >

								Parent Category
								<select class="form-control" id="parent-add" name="parent">
									<option value="">--Please select--</option>
									<?php if($category <> false)
										foreach($category->result() as $row){?>
									<option value="<?php echo $row->id;?>"><?php echo $row->category;?></option>
									<?php } ?>
								</select>

							<button type="submit" class="btn btn-primary">Submit</button>

					</form>

<?php include('footer.php');?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>sample-skeleton-projects</artifactId>
        <groupId>sample-skeleton-projects</groupId>
        <version>0.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Firefly</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.fireflysource</groupId>
            <artifactId>firefly</artifactId>
            <version>4.5.0</version>
        </dependency>

        <dependency>
            <groupId>com.fireflysource</groupId>
            <artifactId>firefly-slf4j</artifactId>
            <version>4.5.0</version>
        </dependency>
    </dependencies>

</project>


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Behat\Service;

use PhpSpec\ObjectBehavior;
use Sylius\Behat\Service\SharedStorage;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class SharedStorageSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(SharedStorage::class);
    }

    function it_implements_shared_storage_interface()
    {
        $this->shouldImplement(SharedStorageInterface::class);
    }

    function it_has_resources_in_clipboard(ChannelInterface $channel, ProductInterface $product)
    {
        $this->set('channel1', $channel);
        $this->get('channel1')->shouldReturn($channel);

        $this->set('product1', $product);
        $this->get('product1')->shouldReturn($product);
    }

    function it_returns_latest_added_resource(ChannelInterface $channel, ProductInterface $product)
    {
        $this->set('channel1', $channel);
        $this->set('product1', $product);

        $this->getLatestResource()->shouldReturn($product);
    }

    function it_overrides_existing_resource_key(ChannelInterface $firstChannel, ChannelInterface $secondChannel)
    {
        $this->set('channel', $firstChannel);
        $this->set('channel', $secondChannel);

        $this->get('channel')->shouldReturn($secondChannel);
    }

    function its_clipboard_can_be_set(ChannelInterface $channel)
    {
        $this->setClipboard(['channel' => $channel]);

        $this->get('channel')->shouldReturn($channel);
    }

    function it_checks_if_resource_under_given_key_exist(ChannelInterface $channel)
    {
        $this->setClipboard(['channel' => $channel]);

        $this->has('channel')->shouldReturn(true);
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 2017-09-27
 * Time: 09:50
 */

namespace sunsun\transfer_station\client;

use GatewayClient\Gateway;
use sunsun\server\consts\SessionKeys;
use sunsun\ServerAddress;
use sunsun\transfer_station\interfaces\DeviceClientInterface;
use sunsun\water_pump\dal\WaterPumpDeviceDal;
use sunsun\water_pump\req\WaterPumpDeviceInfoReq;

class WaterPumpClient extends BaseClient implements DeviceClientInterface
{
    private static $instance = null;

    public function updateAppCnt($did, $cnt = 0)
    {

        $this->setRegisterAddr();
        $clientIds = Gateway::getClientIdByUid($did);
        if (is_array($clientIds) && count($clientIds) > 0 ) {
            $clientId = $clientIds[0];
            Gateway::updateSession($clientId, ['app_cnt' => $cnt]);
            $session = Gateway::getSession($clientId);

            $pwd = '';
            if (array_key_exists(SessionKeys::PWD, $session)) {
                $pwd = $session[SessionKeys::PWD];
            }

            if (!empty($pwd)) {
                //获取一次设备信息
                $this->getInfo($clientId, $did, $pwd);
            }
        }
    }

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new WaterPumpClient();
        }
        return self::$instance;
    }
    public function getInfo($client_id, $did, $pwd = '')
    {
        if (empty($pwd)) {
            $pwd = $this->getDevicePwd($did);
        }
        $req = new WaterPumpDeviceInfoReq();
        $req->setSn($this->getSn());
        $data = $this->getEncryptPacketStr($req, $pwd);
        $this->setRegisterAddr();
        Gateway::sendToClient($client_id, $data);
    }

    // DeviceClientInterface

    public function deviceInfo()
    {

    }

    public function firmwareUpdate()
    {
        // TODO: Implement firmwareUpdate() method.
    }

    // private function
    private function setRegisterAddr(){
        Gateway::$registerAddress = ServerAddress::REGISTER_IP . ":1241";
    }

    protected function getDevicePwd($did){
        $result = (new WaterPumpDeviceDal())->getInfoByDid($did);
        if (empty($result)) {
            return '';
        }
        return $result['pwd'];
    }
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cronjobs extends CI_Controller {

	// Dir of the cronjob-libraries
	private $_cronjobdir = 'application/libraries/cronjobs/';

	/**
	 * Magic Method __construct
	 */
	public function __construct() {
		parent::__construct();
		// Only allow Command-Line-Interface-requests, no external requests
		if(!is_cli())
		{
			show_404();
			die(); // for safety reasons if show_404() won't work as expected or properly.
		}
	}

	/**
	 * Index site
	 * @param string $group dir of a group-files
	 * @param array $methods Array of methods to be executed in group-files (parameters are not possible here)
	 * @return bool returns true if at least one file was loaded
	 */
	public function index($group, $methods)
	{
		if(!is_dir(FCPATH . $this->_cronjobdir . $group . '/')) return false;
		$cronjobs = scandir(FCPATH . $this->_cronjobdir . $group . '/');
		foreach($cronjobs as $cronjob)
		{
			if(substr($cronjob, strlen($cronjob) - 4) == '.php')
			{
				$loadlib = explode('/', $this->_load_if_exists($group . '/' . $cronjob));
				$loadlib = $loadlib[count($loadlib)-1];
				if(is_callable(array($this->$loadlib, 'on_group'))) {
					call_user_func_array(array($this->$loadlib, 'on_group_call'), array());
				}
				foreach($methods as $method) {
					if(is_callable(array($this->$loadlib, $method))) {
						call_user_func_array(array($this->$loadlib, $method), array());
					}
				}
			}
		}
		return true;
	}

	/**
	 * Load file-cronjob to execute multiple methods without parameters inside
	 * @param string $file file-location without .php
	 * @param array $methods array of methods to be executed
	 * @return bool returns true if file exists
	 */
	public function file($file, $methods)
	{
		$loadlib = $this->_load_if_exists($file . '.php');
		if(!$loadlib) return false;

		if(count($methods) == 0) {
			$methods[0] = 'on_function_call';
		}
		foreach($methods as $k => $method) {
			if(is_callable(array($this->$loadlib, $method))) {
				call_user_func_array(array($this->$loadlib, $method), array());
			}
		}
		return true;
	}

	/**
	 * Calls one method in one file with multiple parameters
	 * @param string $file file-location without .php
	 * @param string $method method-name
	 * @param array $params array of arguments; First index = first argument, second index = second argument...
	 * @return mixed returns false if file does not exists; else returns function-call-return
	 */
	public function filemethod($file, $method, $params)
	{

		$loadlib = $this->_load_if_exists($file . '.php');
		if(!$loadlib) return false;

		if(is_callable(array($this->$loadlib, $method))) {
			return call_user_func_array(array($this->$loadlib, $method), $params);
		}
	}

	/**
	 * Remaps the functions so default method for is index and calles by default default_group inside the file-groups
	 * @param string $method name of the method to call
	 * @param array $params parameters to be submitted
	 */
	public function _remap($method, $params = array())
	{
		if($method == 'file')
		{
			$file = $params[0];
			unset($params[0]);
			return call_user_func_array(array($this, 'file'), array($file, $params));
		} elseif($method == 'filemethod') {
			$file = $params[0];
			unset($params[0]);
			$method = $params[1];
			unset($params[1]);
			return call_user_func_array(array($this, 'filemethod'), array($file, $method, $params));
		} else {
			if($method == 'index') $method = 'default_group';
			return call_user_func_array(array($this, 'index'), array($method, $params));
		}
	}

	/**
	 * Loads cronjob-library if exists
	 * @param string $file file-location inside cronjob-dir
	 * @return type
	 */
	private function _load_if_exists($file) {
		if(!file_exists(FCPATH . $this->_cronjobdir . $file)) return false;
		$loadlib = substr($file, 0, strlen($file) - 4);
		$this->load->library('cronjobs/' . $loadlib);
		return $loadlib;
	}
}


text:
layout: post
date: '2016-06-19'
title: "Weddington Way Dessy 2912 Sleeveless Short/Mini Sheath/Column"
category: Weddington Way
tags: [Weddington Way,Sheath/Column,V-neck,Short/Mini,Sleeveless]
---
### Weddington Way Dessy 2912
Just **$159.99**
###   Sleeveless Short/Mini Sheath/Column

BRANDS	Weddington Way

Silhouette	Sheath/Column

Neckline	V-neck

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/weddington-way/15827-weddington-way-dessy-2912.html](https://www.readybrides.com/en/weddington-way/15827-weddington-way-dessy-2912.html)


text:
[![Build Status](https://travis-ci.org/marcos-carceles/swagger-doc.svg?branch=dev)](https://travis-ci.org/marcos-carceles/swagger-doc)

[![Coverage Status](https://coveralls.io/repos/marcos-carceles/swagger-doc/badge.svg?branch=dev)](https://coveralls.io/r/marcos-carceles/swagger-doc?branch=dev)

Swagger 2.0 implementation for Grails.
Based on https://github.com/swagger-api/swagger-core.
This plugin aims to be a non opinionated alternative to existing Swagger plugins for grails, making use of the bare swagger-core annotations without needing to use JAX-RS.


text:
package com.buession.web.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.buession.core.validator.Validate;

/**
 * @author Yong.Teng
 */
public class MobileFilter extends OncePerRequestFilter {

    private boolean isMobile = false;

    private final static Set<String> mobileBrowserKeywords = new HashSet<String>();

    private final static Logger logger = LoggerFactory.getLogger(MobileFilter.class);

    static{
        /* 诺基亚 */
        mobileBrowserKeywords.add("Nokia");
        /* 索尼爱立信 */
        mobileBrowserKeywords.add("SonyEricsson");
        /* 索尼 */
        mobileBrowserKeywords.add("Sony");
        /* 爱立信 */
        mobileBrowserKeywords.add("Ericsson");
        /* 摩托罗拉 */
        mobileBrowserKeywords.add("Mot");
        /* 三星 */
        mobileBrowserKeywords.add("Samsung");
        /* HTC */
        mobileBrowserKeywords.add("HTC");
        /*  */
        mobileBrowserKeywords.add("sgh");
        /* LG */
        mobileBrowserKeywords.add("LG");
        /* 夏普 */
        mobileBrowserKeywords.add("sharp");
        /*  */
        mobileBrowserKeywords.add("sie-");
        /* 飞利浦 */
        mobileBrowserKeywords.add("Philips");
        /* 海尔 */
        mobileBrowserKeywords.add("Haier");
        /* 长虹 */
        mobileBrowserKeywords.add("Changhong");
        /* 松下 */
        mobileBrowserKeywords.add("Panasonic");
        /*  */
        mobileBrowserKeywords.add("alcatel");
        /* 联想 */
        mobileBrowserKeywords.add("Lenovo");
        /* iPhone */
        mobileBrowserKeywords.add("iPhone");
        /* iPod */
        mobileBrowserKeywords.add("iPod");
        /* 黑莓 */
        mobileBrowserKeywords.add("blackberry");
        /* 魅族 */
        mobileBrowserKeywords.add("meizu");
        /*  */
        mobileBrowserKeywords.add("netfront");
        /*  */
        mobileBrowserKeywords.add("palm");
        /*  */
        mobileBrowserKeywords.add("openwave");
        /*  */
        mobileBrowserKeywords.add("nexusone");
        /*  */
        mobileBrowserKeywords.add("cldc");
        /*  */
        mobileBrowserKeywords.add("midp");
        /* 华为 */
        mobileBrowserKeywords.add("Huawei");
        /* TCL */
        mobileBrowserKeywords.add("TCL");
        /* CECT */
        mobileBrowserKeywords.add("CECT");
        /* Compal */
        mobileBrowserKeywords.add("Compal");
        /* NEC */
        mobileBrowserKeywords.add("NEC");
        /* TDG */
        mobileBrowserKeywords.add("TDG");
        /* 阿尔卡特 */
        mobileBrowserKeywords.add("Alcatel");
        /* 波导 */
        mobileBrowserKeywords.add("BIRD");
        /* 大显 */
        mobileBrowserKeywords.add("DAXIAN");
        /* 迪比特 */
        mobileBrowserKeywords.add("DBTEL");
        /* 东信 */
        mobileBrowserKeywords.add("Eastcom");
        /* 多彩 */
        mobileBrowserKeywords.add("PANTECH");
        /* 多普达 */
        mobileBrowserKeywords.add("Dopod");
        /* 康佳 */
        mobileBrowserKeywords.add("KONKA");
        /* 科健 */
        mobileBrowserKeywords.add("Kejian");
        /* 明基 */
        mobileBrowserKeywords.add("BenQ");
        /* 南方高科 */
        mobileBrowserKeywords.add("Soutec");
        /* 萨基姆 */
        mobileBrowserKeywords.add("SAGEM");
        /* 西门子 */
        mobileBrowserKeywords.add("SIE");
        /* 夏新 */
        mobileBrowserKeywords.add("Amoi");
        /* 中兴 */
        mobileBrowserKeywords.add("ZTE");
        /*  */
        mobileBrowserKeywords.add("wap");
        /*  */
        mobileBrowserKeywords.add("mobile");
        /*  */
        mobileBrowserKeywords.add("ucweb");
        /*  */
        mobileBrowserKeywords.add("operamini");
        /*  */
        mobileBrowserKeywords.add("operamobi");
        /* 小米 */
        mobileBrowserKeywords.add("Xiaomi");
        /* 微信 */
        mobileBrowserKeywords.add("MicroMessenger");
        /* QQValidator 浏览器 */
        mobileBrowserKeywords.add("MQQBrowser");
        /*  */
        mobileBrowserKeywords.add("Android");
        /*  */
        mobileBrowserKeywords.add("Symbian");
        /*  */
        mobileBrowserKeywords.add("windowsce");
    }

    public boolean isMobile(){
        return isMobile;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain
            filterChain) throws ServletException, IOException{
        if(request == null){
            filterChain.doFilter(request, response);
            return;
        }

        String userAgent = request.getHeader("User-Agent");

        if(Validate.hasText(userAgent) == true){
            userAgent = userAgent.toLowerCase();
            Iterator<String> iterator = mobileBrowserKeywords.iterator();

            while(iterator.hasNext()){
                final String keywords = iterator.next();

                isMobile = userAgent.contains(keywords.toLowerCase());
                if(isMobile == true){
                    logger.debug("Match keywords {}", keywords);
                    request.setAttribute("isMobile", true);
                    filterChain.doFilter(request, response);
                    return;
                }
            }

            final String accept = request.getHeader("Accept");
            isMobile = accept != null && (accept.contains("vnd.wap.wml") == true && accept.contains("text/html") ==
                    false || accept.indexOf("vnd.wap.wml") > accept.indexOf("text/html"));
        }

        request.setAttribute("isMobile", isMobile);

        filterChain.doFilter(request, response);
    }

}


text:
package example.app;

import io.micronaut.runtime.Micronaut;

public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class);
    }

}


text:
<?php

namespace model;

class Evenement implements \JsonSerializable
{

    private $id;
    private $naam;
    private $beginDatum;
    private $eindDatum;
    private $klantnummer;
    private $bezetting;
    private $kost;
    private $materialen;

    /**
     * Evenement constructor.
     * @param $id
     * @param $naam
     * @param $beginDatum
     * @param $eindDatum
     * @param $klantnummer
     * @param $bezetting
     * @param $kost
     * @param $materialen
     */

    public function __construct($id, $naam, $beginDatum, $eindDatum, $klantnummer, $bezetting, $kost, $materialen)
    {
        $this->setId($id);
        $this->setNaam($naam);
        $this->setBeginDatum($beginDatum);
        $this->setEindDatum($eindDatum);
        $this->setKlantnummer($klantnummer);
        $this->setBezetting($bezetting);
        $this->setKost($kost);
        $this->setMaterialen($materialen);
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getNaam()
    {
        return $this->naam;
    }

    /**
     * @param mixed $naam
     */
    public function setNaam($naam)
    {
        $this->naam = $naam;
    }

    /**
     * @return mixed
     */
    public function getBeginDatum()
    {
        return $this->beginDatum;
    }

    /**
     * @param mixed $beginDatum
     */
    public function setBeginDatum($beginDatum)
    {
        $this->beginDatum = $beginDatum;
    }

    /**
     * @return mixed
     */
    public function getEindDatum()
    {
        return $this->eindDatum;
    }

    /**
     * @param mixed $eindDatum
     */
    public function setEindDatum($eindDatum)
    {
        $this->eindDatum = $eindDatum;
    }

    /**
     * @return mixed
     */
    public function getKlantnummer()
    {
        return $this->klantnummer;
    }

    /**
     * @param mixed $klantnummer
     */
    public function setKlantnummer($klantnummer)
    {
        $this->klantnummer = $klantnummer;
    }

    /**
     * @return mixed
     */
    public function getBezetting()
    {
        return $this->bezetting;
    }

    /**
     * @param mixed $bezetting
     */
    public function setBezetting($bezetting)
    {
        $this->bezetting = $bezetting;
    }

    /**
     * @return mixed
     */
    public function getKost()
    {
        return $this->kost;
    }

    /**
     * @param mixed $kost
     */
    public function setKost($kost)
    {
        $this->kost = $kost;
    }

    /**
     * @return mixed
     */
    public function getMaterialen()
    {
        return $this->materialen;
    }

    /**
     * @param mixed $materialen
     */
    public function setMaterialen($materialen)
    {
        $this->materialen = $materialen;
    }
}


text:
import React, { useEffect } from 'react';
import HardwareConnectionContainer from './hardwareConnection/HardwareConnectionContainer';
import LicenseViewerContainer from './hardwareList/opensourceLicenseViewer/LicenseViewerContainer';
import ErrorAlert from './hardwareList/ErrorAlert';
import SelectPortContainer from './hardwareConnection/SelectPortContainer';
import HardwareListContainer from './hardwareList/HardwareListContainer';
import { connect } from 'react-redux';
import { HardwarePageStateEnum } from '../constants/constants';
import { IMapDispatchToProps, IMapStateToProps } from '../store';
import AlertTab from './common/AlertTab';
import { IAlertMessage } from '../store/modules/common';
import { changeVisiblePortList } from '../store/modules/connection';

const Main: React.FC<IStateProps & IDispatchProps> = (props) => {
    const {
        currentState, isNeedPortSelect, alertMessage, changeVisiblePortList, isPortSelectCanceled,
    } = props;

    useEffect(() => {
        if (currentState === HardwarePageStateEnum.list) {
            changeVisiblePortList(false);
        }
    }, [currentState]);

    return (
        <>
            {currentState === HardwarePageStateEnum.list && (
                <>
                    <HardwareListContainer/>
                    <ErrorAlert/>
                    <LicenseViewerContainer/>
                </>
            )}
            {currentState === HardwarePageStateEnum.connection && (
                <>
                    {alertMessage && <AlertTab {...alertMessage} />}
                    <HardwareConnectionContainer/>
                    {isNeedPortSelect && !isPortSelectCanceled && <SelectPortContainer
                        handleCancelClicked={() => {
                            changeVisiblePortList(true);
                        }}
                    />}
                </>
            )}
        </>
    );
};

interface IStateProps {
    alertMessage?: IAlertMessage;
    currentState: HardwarePageStateEnum;
    isNeedPortSelect: boolean;
    isPortSelectCanceled: boolean;
}

interface IDispatchProps {
    changeVisiblePortList: (isCanceled: boolean) => void;
}

const mapStateToProps: IMapStateToProps<IStateProps> = (state) => ({
    alertMessage: state.common.alertMessage,
    currentState: state.common.currentPageState,
    isNeedPortSelect: state.connection.isNeedPortSelect,
    isPortSelectCanceled: state.connection.isPortSelectCanceled,
});

const mapDispatchToProps: IMapDispatchToProps<IDispatchProps> = (dispatch) => ({
    changeVisiblePortList: changeVisiblePortList(dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(Main);


text:
package org.teavm.ast.optimization;

import java.util.HashSet;
import java.util.Set;
import org.teavm.ast.BlockStatement;
import org.teavm.ast.BreakStatement;
import org.teavm.ast.ContinueStatement;
import org.teavm.ast.IdentifiedStatement;
import org.teavm.ast.RecursiveVisitor;
import org.teavm.ast.SwitchClause;
import org.teavm.ast.SwitchStatement;
import org.teavm.ast.WhileStatement;

class RedundantLabelEliminator extends RecursiveVisitor {
    private IdentifiedStatement currentBlock;
    private Set<IdentifiedStatement> hasRefs = new HashSet<>();

    @Override
    public void visit(SwitchStatement statement) {
        IdentifiedStatement currentBlockBackup = currentBlock;
        currentBlock = statement;
        for (SwitchClause clause : statement.getClauses()) {
            visit(clause.getBody());
        }
        visit(statement.getDefaultClause());
        if (!hasRefs.contains(currentBlock)) {
            currentBlock.setId(null);
        }
        currentBlock = currentBlockBackup;
    }

    @Override
    public void visit(WhileStatement statement) {
        IdentifiedStatement currentBlockBackup = currentBlock;
        currentBlock = statement;
        visit(statement.getBody());
        if (!hasRefs.contains(currentBlock)) {
            currentBlock.setId(null);
        }
        currentBlock = currentBlockBackup;
    }

    @Override
    public void visit(BlockStatement statement) {
        IdentifiedStatement currentBlockBackup = currentBlock;
        currentBlock = null;
        visit(statement.getBody());
        currentBlock = currentBlockBackup;
    }

    @Override
    public void visit(BreakStatement statement) {
        if (statement.getTarget() == currentBlock) {
            statement.setTarget(null);
        } else {
            hasRefs.add(statement.getTarget());
        }
    }

    @Override
    public void visit(ContinueStatement statement) {
        if (statement.getTarget() == currentBlock) {
            statement.setTarget(null);
        } else {
            hasRefs.add(statement.getTarget());
        }
    }
}


text:
<?php

require_once("include/database.inc.php");
require_once("include/auth.class.php");
require_once("include/validation.class.php");

$auth = new Auth(true);
$user = Auth::getUser();
?>
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>QCManager</title>
		<link rel="stylesheet" type="text/css" href="css/main.css">

									<?php
									if(empty($user->user_photo_path))
										echo "
".$user->user_lastname[0]."
".$user->user_firstname[0] . ". " . $user->user_lastname;
									else
										echo '
user_photo_path.');background-size:cover;">
'.$user->user_lastname;
									?>

Tableau de bord

Créer un QCM

Déconnexion

				Éditer le profil


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>dynamic programing on k317h</title>
    <link>https://keithzeng.github.io/series/dynamic-programing/</link>
    <description>Recent content in dynamic programing on k317h</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 18 Feb 2019 19:32:41 -0800</lastBuildDate>

	<atom:link href="https://keithzeng.github.io/series/dynamic-programing/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>CSE202 HW3</title>
      <link>https://keithzeng.github.io/hws/cse202-hw3/</link>
      <pubDate>Mon, 18 Feb 2019 19:32:41 -0800</pubDate>

      <guid>https://keithzeng.github.io/hws/cse202-hw3/</guid>
      <description>Problem 1 Idea We can think every row as a node with influx of row&rsquo;s sum that we want to distribute into every column which is also a node with edge&rsquo;s capacity of M.
Let&rsquo;s define $X_1 &hellip; X_n$ to be the rows and $Y_1 .. Y_n$ to be the columns. The preliminary graph looks like this.
Due to the nature of the network flow problem, we might have edge with 0 flow.</description>
    </item>

    <item>
      <title>Sequence Alignment Revisited</title>
      <link>https://keithzeng.github.io/posts/sequence-alignment-revisited/</link>
      <pubDate>Sat, 09 Feb 2019 18:50:42 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/sequence-alignment-revisited/</guid>
      <description>Problem1 Sequence Alignment
We can reduce the space by using only two column instead.
Space-Efficient-Alignment(X ,Y)
 Array B[0&hellip;m,0&hellip;1] Initialize B[i,0]=iδ for each i (just as in column 0 of A) For j=1,&hellip;,n  B[0,1]=j$\delta$ (since this corresponds to entry A[0,j]) For i=1,&hellip;,m  B[i, 1]= min[$\alpha x_iy_j$ + B[i − 1, 0], $\delta$ + B[i−1,1], $\delta$ + B[i,0]]  Endfor Move column 1 of B to column 0 to make room for next iteration:  Update B[i, 0]= B[i, 1] for each i   Endfor  However, this doesn&rsquo;t left enough information to get back the information about alignment.</description>
    </item>

    <item>
      <title>Sequence Alignment</title>
      <link>https://keithzeng.github.io/posts/sequence-alignment/</link>
      <pubDate>Sat, 09 Feb 2019 17:56:45 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/sequence-alignment/</guid>
      <description>Problem1 When you type &ldquo;ocurrance&rdquo;, the brower will will prompt "Perhaps you mean occurrence?"
How does the search engine knows?
How does it know the most similar word?
How do we determine the similarity between words?
The definition of similarity will be based on the optimal alignment between X and Y where X = $x_1x_2 &hellip; x_m$, Y = $y_1y_2 &hellip; y_n$.
 when there is gap (character not matched), we pay $\delta$ when we match character p and q, we pay $\alpha_{pq}$, where $\alpha_{pq}$ = 0 goal is to minimize the sum of cost.</description>
    </item>

    <item>
      <title>RNA Secondary Structure</title>
      <link>https://keithzeng.github.io/posts/rna-secondary-structure/</link>
      <pubDate>Sat, 09 Feb 2019 17:07:21 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/rna-secondary-structure/</guid>
      <description>Problem1 We have bases of {A,C,G,T} in DNA sequence, where A-T and C-G form a pair. A sinlge strand of RNA will loop back, resulting shape called secondary structure.
Let $B = b_1b_2 &hellip; b_n$, where $b_i$ = {A,C,G,U} also A-U, C-G form pair
Then the Secondary structure, S ={(i, j)}
 no sharp turn, i &lt; j - 4 pair is either {A,U}, {C,G} (either order) no base appear in more than 1 matching no crossing condition, (i,j) and (k, l) $\in$ S, we can&rsquo;t have i &lt; k &lt; j &lt; l  Algorithm Following the same analysis</description>
    </item>

    <item>
      <title>Knapsack</title>
      <link>https://keithzeng.github.io/posts/knapsack/</link>
      <pubDate>Sat, 09 Feb 2019 14:09:38 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/knapsack/</guid>
      <description>Problem1 Each request has value $v_i$ and weight $w_i$, and we have constraint that the total of request weight $\leq$ W.
Greedy doesn&rsquo;t work because sorting the W either in decreasing or increasing manner don&rsquo;t produce the optimal solution.
 {W/2 + 1, W/2, W/2} {1, W/2, W/2}  Using dynamic programing, we can use reduce this problem to whether or not each request belongs to the optimal solution O again.</description>
    </item>

    <item>
      <title>Segmented Least Square</title>
      <link>https://keithzeng.github.io/posts/segmented-least-square/</link>
      <pubDate>Sat, 09 Feb 2019 12:54:29 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/segmented-least-square/</guid>
      <description>Problem1 Data $P = (x_1,y_1), (x_2, y_2)&hellip;(x_n, y_n)$ for $x_1 &lt; x_2 &lt; &hellip; &lt; x_n$.
Given a line y=ax+b, and error
$$Error(L, P) = \sum_{i=1}^n(y_i - ax_i -b)^2$$
And it has closed form solution of
$$a = \frac{n\sum_i x_iy_i - (\sum_i x_i)(\sum_i y_i)}{n\sum_i x_i^2 - (\sum_i x_i)^2}$$
and
$$b = \frac {\sum_i y_i - a \sum_i x_i}{n}$$
However, if the data is show as below (maybe fitted with two lines), we can&rsquo;t just use the above formula.</description>
    </item>

    <item>
      <title>Weighted Interval Scheduling</title>
      <link>https://keithzeng.github.io/posts/weighted-interval-scheduling/</link>
      <pubDate>Fri, 08 Feb 2019 23:22:27 -0800</pubDate>

      <guid>https://keithzeng.github.io/posts/weighted-interval-scheduling/</guid>
      <description>Problem1 Instead of just fitting as many tasks like regular interval scheduling problem, we have weight associates with the interval. Now we want to maximize the value.
So basically, $f_i$ finish time sorted in non-decreasing order, $v_i$ is the value, and $s_i$ is the start time. We want $S \subseteq {1&hellip; n}$.
We also define $p(j)$ which is the largest i &lt; j which is disjoint(compatible) with j.
Algorithm Idea:</description>
    </item>

  </channel>
</rss>


text:
#ifndef vtkOpenGLVertexBufferObject_h
#define vtkOpenGLVertexBufferObject_h

#include "vtkRenderingOpenGL2Module.h" // for export macro
#include "vtkOpenGLBufferObject.h"

/**
 * @brief OpenGL vertex buffer object
 *
 * OpenGL buffer object to store geometry and/or attribute data on the
 * GPU.
 */

// useful union for stuffing colors into a float
union vtkucfloat
{
  unsigned char c[4];
  float f;
};

class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLVertexBufferObject :
  public vtkOpenGLBufferObject
{
public:
  static vtkOpenGLVertexBufferObject *New();
  vtkTypeMacro(vtkOpenGLVertexBufferObject, vtkOpenGLBufferObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Take the points, and pack them into this VBO. This currently
  // takes whatever the input type might be and packs them into a VBO using
  // floats for the vertices and normals, and unsigned char for the colors (if
  // the array is non-null).
  void CreateVBO(vtkPoints *points, unsigned int numPoints,
      vtkDataArray *normals,
      vtkDataArray *tcoords,
      unsigned char *colors, int colorComponents);

  void AppendVBO(vtkPoints *points, unsigned int numPoints,
      vtkDataArray *normals,
      vtkDataArray *tcoords,
      unsigned char *colors, int colorComponents);

  /**\brief Methods for VBO coordinate shift+scale-computation.
    *
    * By default, shift and scale vectors are enabled
    * whenever CreateVBO is called with points whose
    * bounds are many bbox-lengths away from the origin.
    *
    * Shifting and scaling may be completely disabled,
    * or manually specified, or left at the default.
    *
    * Manual specification is for the case when you
    * will be calling AppendVBO instead of just CreateVBO
    * and know better bounds than the what CreateVBO
    * might produce.
    *
    * The automatic method tells CreatVBO to compute shift and
    * scale vectors that remap the points to the unit cube.
    */
  enum ShiftScaleMethod {
    DISABLE_SHIFT_SCALE,  //!< Do not shift/scale point coordinates. Ever!
    AUTO_SHIFT_SCALE,     //!< The default, automatic computation.
    MANUAL_SHIFT_SCALE    //!< Manual shift/scale provided (for use with AppendVBO)
  };

  // Description:
  // Get the shift and scale vectors computed by CreateVBO;
  // or set the values CreateVBO and AppendVBO will use.
  // Note that the "Set" methods **must** be called before the
  // first time that CreateVBO or AppendVBO is invoked and
  // should never be called afterwards.
  //
  // The CoordShiftAndScaleMethod describes how the shift
  // and scale vectors are obtained (or that they should never
  // be used).
  // The GetCoordShiftAndScaleEnabled() method returns true if
  // a shift and scale are currently being applied (or false if not).
  //
  // The "Get" methods are used by the mapper to modify the world
  // and camera transformation matrices to match the scaling applied
  // to coordinates in the VBO.
  // CreateVBO only applies a shift and scale when the midpoint
  // of the point bounding-box is distant from the origin by a
  // factor of 10,000 or more relative to the size of the box
  // along any axis.
  //
  // For example, if the x coordinates of the points range from
  // 200,000 to 200,001 then the factor is
  // 200,000.5 / (200,001 - 200,000) = 2x10^5, which is larger
  // than 10,000 -- so the coordinates will be shifted and scaled.
  //
  // This is important as many OpenGL drivers use reduced precision
  // to hold point coordinates.
  //
  // These methods are used by the mapper to determine the
  // additional transform (if any) to apply to the rendering transform.
  vtkGetMacro(CoordShiftAndScaleEnabled,bool);
  vtkGetMacro(CoordShiftAndScaleMethod,ShiftScaleMethod);
  vtkGetVector3Macro(CoordShift,double);
  vtkGetVector3Macro(CoordScale,double);
  virtual void SetCoordShiftAndScaleMethod(ShiftScaleMethod meth);
  virtual void SetCoordShift(double x, double y, double z);
  virtual void SetCoordShift(const double s[3]);
  virtual void SetCoordScale(double sx, double sy, double sz);
  virtual void SetCoordScale(const double s[3]);

  // Sizes/offsets are all in bytes as OpenGL API expects them.
  size_t VertexCount; // Number of vertices in the VBO
  int Stride;       // The size of a complete vertex + attributes
  int VertexOffset; // Offset of the vertex
  int NormalOffset; // Offset of the normal
  int TCoordOffset; // Offset of the texture coordinates
  int TCoordComponents; // Number of texture dimensions
  int ColorOffset;  // Offset of the color
  int ColorComponents; // Number of color components
  std::vector<float> PackedVBO; // the data

protected:
  vtkOpenGLVertexBufferObject();
  ~vtkOpenGLVertexBufferObject();

  double CoordShift[3];
  double CoordScale[3];
  ShiftScaleMethod CoordShiftAndScaleMethod;
  bool CoordShiftAndScaleEnabled;

private:
  vtkOpenGLVertexBufferObject(const vtkOpenGLVertexBufferObject&) VTK_DELETE_FUNCTION;
  void operator=(const vtkOpenGLVertexBufferObject&) VTK_DELETE_FUNCTION;
};

#endif


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  factory((global.Trois = {}));
}(this, function (exports) { 'use strict';

  var babelHelpers = {};

  babelHelpers.toConsumableArray = function (arr) {
    if (Array.isArray(arr)) {
      for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

      return arr2;
    } else {
      return Array.from(arr);
    }
  };

  babelHelpers;
  var Scene = (function (_ref) {
    var Scene = _ref.Scene;
    var WebGLRenderer = _ref.WebGLRenderer;
    return {
      name: 'Scene',
      template: '<canvas><slot></slot></canvas>',
      data: function data() {
        return {
          realWidth: 0,
          realHeight: 0
        };
      },
      props: {
        width: {
          type: Number,
          default: 640
        },
        height: {
          type: Number,
          default: 480
        }
      },
      beforeCompile: function beforeCompile() {
        this.$trois = new Scene();
        this.$troisRenderer = new WebGLRenderer({
          canvas: this.$el
        });
      },
      attached: function attached() {
        this.setSize();
        this._troisWillRender = false;
        this.render();
      },

      methods: {
        render: function render() {
          var _this = this;

          if (!this._troisWillRender) {
            this._troisWillRender = true;
            this.$nextTick(function () {
              _this.$troisRenderer.render(_this.$trois, _this.$trois.$troisCamera);
              _this._troisWillRender = false;
            });
          }
        },
        setSize: function setSize() {
          this.$troisRenderer.setSize(this.width, this.height);
        }
      },
      watch: {
        width: 'setSize',
        height: 'setSize'
      },
      events: {
        update: 'render'
      }
    };
  })

  var troisMixin = {
    template: '<slot></slot>',
    replace: false
  };

  var constructorMixin = (function (Constructor) {
    var props = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
    var order = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];

    var propNames = Array.isArray(props) ? props : Object.keys(props);

    var construct = function construct(vm) {
      var args = order.map(function (propName) {
        var propValue = vm[propName];
        var transformer = props[propName] && props[propName]._troisTransformer;
        if (transformer) {
          propValue = transformer(propValue);
        }
        return propValue;
      });
      vm.$trois = new (Function.prototype.bind.apply(Constructor, [null].concat(babelHelpers.toConsumableArray(args))))();
    };

    var mixin = {
      props: props,
      watch: {},
      beforeCompile: function beforeCompile() {
        construct(this);
      },
      destroyed: function destroyed() {
        this.$trois = null;
      }
    };

    propNames.forEach(function (propName) {
      mixin.watch[propName] = function () {
        var oldTrois = this.$trois;
        construct(this);
        this.$emit('replace', oldTrois);
        this.$dispatch('update');
      };
    });

    return mixin;
  })

  var childrenMixin = {
    attached: function attached() {
      this.$parent.$trois.add(this.$trois);
      this.$dispatch('update');
    },
    detached: function detached() {
      this.$parent.$trois.remove(this.$trois);
      this.$dispatch('update');
    },

    events: {
      replace: function replace(oldTrois) {
        this.$parent.$trois.remove(oldTrois);
        this.$parent.$troid.add(this.$trois);
      }
    }
  };

  var Mesh = (function (_ref) {
    var Mesh = _ref.Mesh;
    return {
      name: 'Mesh',
      mixins: [troisMixin, constructorMixin(Mesh), childrenMixin]
    };
  })

  var memberMixin = (function (propName) {
    return {
      attached: function attached() {
        this.$parent.$trois[propName] = this.$trois;
      },
      detached: function detached() {
        this.$parent.$trois[propName] = null;
      },

      events: {
        replace: function replace() {
          this.$parent.$trois[propName] = this.$trois;
        }
      }
    };
  })

  var propsMixin = (function (props) {
    var transformers = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

    var propNames = Array.isArray(props) ? props : Object.keys(props);

    var mixin = {
      props: props,
      watch: {},
      compiled: function compiled() {
        var _this = this;

        propNames.forEach(function (propName) {
          var propValue = _this[propName];
          if (propValue != null) {
            var transformer = transformers[propName];
            _this.$trois[propName] = transformer ? transformer(propValue) : propValue;
          }
        });
      }
    };

    propNames.forEach(function (propName) {
      var transformer = transformers[propName];
      mixin.watch[propName] = transformer ? function (propValue) {
        this.$trois[propName] = transformer(propValue);
        this.$dispatch('update');
      } : function (propValue) {
        this.$trois[propName] = propValue;
        this.$dispatch('update');
      };
    });

    return mixin;
  })

  var PerspectiveCamera = (function (_ref) {
    var PerspectiveCamera = _ref.PerspectiveCamera;
    return {
      name: 'PerspectiveCamera',
      mixins: [troisMixin, constructorMixin(PerspectiveCamera), memberMixin('$troisCamera'), propsMixin({
        fov: Number,
        near: Number,
        far: Number
      })],
      compiled: function compiled() {
        this.setAspect(this.aspect);
      },

      computed: {
        aspect: function aspect() {
          return this.$parent.width / this.$parent.height;
        }
      },
      methods: {
        setAspect: function setAspect(aspect) {
          this.$trois.aspect = aspect;
          this.updateProjectionMatrix();
        },
        updateProjectionMatrix: function updateProjectionMatrix() {
          this.$trois.updateProjectionMatrix();
          this.$dispatch('update');
        }
      },
      watch: {
        fov: 'updateProjectionMatrix',
        near: 'updateProjectionMatrix',
        far: 'updateProjectionMatrix',
        aspect: 'setAspect'
      }
    };
  })

  var lightMixin = {
    ready: function ready() {
      this._troisMaterialCacheUpdate();
    },
    beforeDestroy: function beforeDestroy() {
      this._troisMaterialCacheUpdate();
    }
  };

  var AmbientLight = (function (_ref) {
    var AmbientLight = _ref.AmbientLight;
    var Color = _ref.Color;
    return {
      name: 'AmbientLight',
      mixins: [troisMixin, constructorMixin(AmbientLight), childrenMixin, propsMixin(['color'], {
        color: function color(value) {
          return new Color(value);
        }
      }), lightMixin]
    };
  })

  var DirectionalLight = (function (_ref) {
    var DirectionalLight = _ref.DirectionalLight;
    var Color = _ref.Color;
    return {
      name: 'DirectionalLight',
      mixins: [troisMixin, constructorMixin(DirectionalLight), childrenMixin, propsMixin({
        color: {},
        intensity: Number
      }, {
        color: function color(value) {
          return new Color(value);
        }
      }), lightMixin]
    };
  })

  var PointLight = (function (_ref) {
    var PointLight = _ref.PointLight;
    var Color = _ref.Color;
    return {
      name: 'PointLight',
      mixins: [troisMixin, constructorMixin(PointLight), childrenMixin, propsMixin({
        color: {},
        intensity: Number,
        distance: Number,
        decay: Number
      }, {
        color: function color(value) {
          return new Color(value);
        }
      }), lightMixin]
    };
  })

  var disposeMixin = {
    beforeDestroy: function beforeDestroy() {
      this.$trois.dispose();
    },

    events: {
      replace: function replace(oldTrois) {
        oldTrois.dispose();
      }
    }
  };

  var BoxGeometry = (function (_ref) {
    var BoxGeometry = _ref.BoxGeometry;
    return {
      name: 'BoxGeometry',
      mixins: [troisMixin, constructorMixin(BoxGeometry, {
        width: { type: Number, default: 1 },
        height: { type: Number, default: 1 },
        depth: { type: Number, default: 1 }
      }, ['width', 'height', 'depth']), memberMixin('geometry'), disposeMixin]
    };
  })

  var materialMixin = {
    compiled: function compiled() {
      this._troisMaterialCacheAdd();
    },
    beforeDestroy: function beforeDestroy() {
      this._troisMaterialCacheRemove();
    }
  };

  var MeshBasicMaterial = (function (_ref) {
    var MeshBasicMaterial = _ref.MeshBasicMaterial;
    var Color = _ref.Color;
    return {
      name: 'MeshBasicMaterial',
      mixins: [troisMixin, constructorMixin(MeshBasicMaterial), memberMixin('material'), propsMixin(['color'], {
        color: function color(value) {
          return new Color(value);
        }
      }), disposeMixin, materialMixin]
    };
  })

  var MeshLambertMaterial = (function (_ref) {
    var MeshLambertMaterial = _ref.MeshLambertMaterial;
    var Color = _ref.Color;
    return {
      name: 'MeshLambertMaterial',
      mixins: [troisMixin, constructorMixin(MeshLambertMaterial), memberMixin('material'), propsMixin(['color'], {
        color: function color(value) {
          return new Color(value);
        }
      }), disposeMixin, materialMixin]
    };
  })

  var MeshPhongMaterial = (function (_ref) {
    var MeshPhongMaterial = _ref.MeshPhongMaterial;
    var Color = _ref.Color;
    return {
      name: 'MeshPhongMaterial',
      mixins: [troisMixin, constructorMixin(MeshPhongMaterial), memberMixin('material'), propsMixin(['color'], {
        color: function color(value) {
          return new Color(value);
        }
      }), disposeMixin, materialMixin]
    };
  })

  var valuesMixin = (function (name, props) {
    var transformers = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

    var propNames = Array.isArray(props) ? props : Object.keys(props);

    var mixin = {
      props: props,
      watch: {},
      attached: function attached() {
        var _this = this;

        propNames.forEach(function (propName) {
          var propValue = _this[propName];
          if (propValue != null) {
            var transformer = transformers[propName];
            _this.$parent.$trois[name][propName] = transformer ? transformer(propValue) : propValue;
            _this.$dispatch('update');
          }
        });
      }
    };

    propNames.forEach(function (propName) {
      var transformer = transformers[propName];
      mixin.watch[propName] = transformer ? function (propValue) {
        this.$parent.$trois[name][propName] = transformer(propValue);
        this.$dispatch('update');
      } : function (propValue) {
        this.$parent.$trois[name][propName] = propValue;
        this.$dispatch('update');
      };
    });

    return mixin;
  })

  var position = {
    name: 'position',
    mixins: [troisMixin, valuesMixin('position', {
      x: Number,
      y: Number,
      z: Number
    })]
  };

  var deg2rad = function deg2rad(rad) {
    return rad * Math.PI / 180;
  };

  var rotation = {
    name: 'rotation',
    mixins: [troisMixin, valuesMixin('rotation', {
      x: Number,
      y: Number,
      z: Number,
      order: String
    }, {
      x: deg2rad,
      y: deg2rad,
      z: deg2rad
    })]
  };

  var scale = {
    name: 'scale',
    mixins: [troisMixin, valuesMixin('scale', {
      x: Number,
      y: Number,
      z: Number
    })]
  };

  var materialCache = {
    install: function install(Vue) {
      Vue._troisMaterialCache = {};
      Object.assign(Vue.prototype, {
        _troisMaterialCacheAdd: function _troisMaterialCacheAdd() {
          Vue._troisMaterialCache[this._uid] = this;
        },
        _troisMaterialCacheRemove: function _troisMaterialCacheRemove() {
          delete Vue._troisMaterialCache[this._uid];
        },
        _troisMaterialCacheUpdate: function _troisMaterialCacheUpdate() {
          for (var uid in Vue._troisMaterialCache) {
            Vue._troisMaterialCache[uid].$trois.needsUpdate = true;
          }
        }
      });
    }
  };

  var version = '0.0.0';

  function install(Vue, _ref) {
    var THREE = _ref.THREE;
    var _ref$prefix = _ref.prefix;
    var prefix = _ref$prefix === undefined ? false : _ref$prefix;

    Vue.use(materialCache);

    switch (prefix) {

      case true:
        prefix = 'trois-';
        break;

      case false:
        prefix = '';
        break;

      default:
        if (prefix[prefix.length - 1] !== '-') {
          prefix += '-';
        }
    }

    Vue.component(prefix + 'scene', Scene(THREE));
    Vue.component(prefix + 'mesh', Mesh(THREE));

    Vue.component(prefix + 'perspective-camera', PerspectiveCamera(THREE));

    Vue.component(prefix + 'ambient-light', AmbientLight(THREE));
    Vue.component(prefix + 'directional-light', DirectionalLight(THREE));
    Vue.component(prefix + 'point-light', PointLight(THREE));

    Vue.component(prefix + 'box-geometry', BoxGeometry(THREE));

    Vue.component(prefix + 'mesh-basic-material', MeshBasicMaterial(THREE));
    Vue.component(prefix + 'mesh-lambert-material', MeshLambertMaterial(THREE));
    Vue.component(prefix + 'mesh-phong-material', MeshPhongMaterial(THREE));

    Vue.component(prefix + 'position', position);
    Vue.component(prefix + 'rotation', rotation);
    Vue.component(prefix + 'scale', scale);
  }

  exports.version = version;
  exports.install = install;

}));


text:
#include "tensorflow/c/c_api_experimental.h"

#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/compiler/jit/legacy_flags/mark_for_compilation_pass_flags.h"
#include "tensorflow/core/protobuf/config.pb.h"

void TF_EnableXLACompilation(TF_SessionOptions* options, unsigned char enable) {
  tensorflow::ConfigProto& config = options->options.config;
  auto* optimizer_options =
      config.mutable_graph_options()->mutable_optimizer_options();
  if (enable) {
    optimizer_options->set_global_jit_level(tensorflow::OptimizerOptions::ON_1);

    // These XLA flags are needed to trigger XLA properly from C (more generally
    // non-Python) clients. If this API is called again with `enable` set to
    // false, it is safe to keep these flag values as is.
    tensorflow::legacy_flags::MarkForCompilationPassFlags* flags =
        tensorflow::legacy_flags::GetMarkForCompilationPassFlags();
    flags->tf_xla_cpu_global_jit = true;
    flags->tf_xla_min_cluster_size = 1;
  } else {
    optimizer_options->set_global_jit_level(tensorflow::OptimizerOptions::OFF);
  }
}


text:
package com.persist.dst

import com.persist.dst.DstColumns.{AggIntColumn, DstTransform}
import org.apache.spark.sql.DataFrame

import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
//import scala.reflect.runtime.universe._
//import com.persist.dst.DstColumns._

object DstTransforms {
  // TODO fix problem with select has only a single value

  private def getColumnInfo(c: Context)(t: c.universe.Type): Seq[(String, c.universe.Type)] = {
    val names = t.decls
      .filter { case d => d.isMethod && d.toString.startsWith("value ") }
      .map { case decl =>
        val ty = decl.asMethod.returnType
        val name = decl.name.toString()
        (name, ty)
      }
      .toSeq
    names
  }

  def FuncMap[TOLD, TNEW](f: (TOLD) => TNEW): Any = macro funcMapImpl[TOLD, TNEW]

  def funcMapImpl[Told: c.WeakTypeTag, Tnew: c.WeakTypeTag]
  (c: Context)(f: c.Expr[Any]): c.Expr[Any] = {
    import c.universe._
    val told = c.weakTypeTag[Told].tpe
    val tnew = c.weakTypeTag[Tnew].tpe
    val q =
      q"""
      (ds:Dataset[$told]) => {
        ds.rdd.map($f).toDF().as[$tnew]
      }
      """
    c.Expr(q)
  }

  def SqlJoin[TA, TB, TNEW]: Any = macro SqlJoinImpl[TA, TB, TNEW]

  def SqlJoinImpl[Ta: c.WeakTypeTag, Tb: c.WeakTypeTag, Tnew: c.WeakTypeTag](c: Context): c.Expr[Any] = {
    import c.universe._
    val ta = c.weakTypeTag[Ta].tpe
    val aNames = getColumnInfo(c)(ta)
    val tb = c.weakTypeTag[Tb].tpe
    val bNames = getColumnInfo(c)(ta)
    val tnew = c.weakTypeTag[Tnew].tpe
    val newNames = getColumnInfo(c)(tnew)
    val acolsExp = getColumns(c)(ta, "_1")
    val bcolsExp = getColumns(c)(tb, "_2")
    val fields = newNames map { case (name, ty) =>
      tq"DstTypedColumn[ThisTransform,$ty]"
    }
    val qargs1 = for (((n, ty), i) <- newNames.zipWithIndex) yield {
      val pos = TermName(s"_${i + 1}")
      q"""(f.$pos.col).as($n)"""
    }
    // TODO use ThisTransformA in getColumns
    // TODO Distinguish A and B
    val q =
      q"""
         new {
             class ThisTransform extends DstTransform
             class ThisTransformA extends ThisTransform
             class ThisTransformB extends ThisTransform

             val acols = $acolsExp
             val bcols = $bcolsExp

             def act[T](akey: (acols.type) => DstTypedColumn[ThisTransform,T],
             bkey: (bcols.type)=> DstTypedColumn[ThisTransform,T],
             fields: (acols.type,bcols.type) => (..$fields)) = {
                val f = fields(acols,bcols)
                (dsa:Dataset[$ta],dsb:Dataset[$tb]) => {
                  dsa.as("_1").joinWith(dsb.as("_2"), akey(acols).col === bkey(bcols).col )
                  .toDF().select(..$qargs1).as[$tnew]
                 }
             }
             override def toString() = "SqlJoin[" + ${ta.toString} +
             "," + ${tb.toString} + "," + ${tnew.toString} + "]"
          }
      """
    c.Expr(q)
  }

  def SqlSort[T]: Any = macro SqlSortImpl[T]

  def SqlSortImpl[T: c.WeakTypeTag]
  (c: Context): c.Expr[Any] = {
    import c.universe._
    val t = c.weakTypeTag[T].tpe
    val names = getColumnInfo(c)(t)
    val colsExp = getColumns(c)(t, "")
    val q =
      q"""
         new {
             class ThisTransform extends DstTransform

             val cols = $colsExp

             def act(fields: (cols.type) => Seq[DstColumn[ThisTransform]]) = {
                val f = fields(cols).map(_.col)
                (ds:Dataset[$t]) => {
                  ds.toDF().sort(f:_*).as[$t]
                 }
             }
             override def toString() = "SqlSort[" + ${t.toString} + "]"
          }
      """
    c.Expr(q)
  }

  def SqlMap[TOLD, TNEW]: Any = macro sqlMapImpl[TOLD, TNEW]

  def sqlMapImpl[Told: c.WeakTypeTag, Tnew: c.WeakTypeTag]
  (c: Context): c.Expr[Any] = {
    import c.universe._
    val told = c.weakTypeTag[Told].tpe
    val oldNames = getColumnInfo(c)(told)
    val tnew = c.weakTypeTag[Tnew].tpe
    val newNames = getColumnInfo(c)(tnew)
    val colsExp = getColumns(c)(told, "")
    val fields = newNames map { case (name, ty) =>
      tq"DstTypedColumn[ThisTransform,$ty]"
    }

    val qargs1 = for (((n, ty), i) <- newNames.zipWithIndex) yield {
      val pos = TermName(s"_${i + 1}")
      q"""(f.$pos.col).as($n)"""
    }
    val q =
      q"""
         new {
             class ThisTransform extends DstTransform

             val cols = $colsExp

             def act(fields: (cols.type) => (..$fields)) = {
                val f = fields(cols)
                (ds:Dataset[$told]) => {
                  ds.toDF().select(..$qargs1).as[$tnew]
                 }
             }
             override def toString() = "SqlMap[" + ${told.toString} + "," + ${tnew.toString} + "]"
          }
      """
    c.Expr(q)
  }

  def SqlAgg[TOLD, TNEW]: Any = macro sqlAggImpl[TOLD, TNEW]

  def sqlAggImpl[Told: c.WeakTypeTag, Tnew: c.WeakTypeTag]
  (c: Context): c.Expr[Any] = {
    import c.universe._
    val told = c.weakTypeTag[Told].tpe
    val oldNames = getColumnInfo(c)(told)
    val tnew = c.weakTypeTag[Tnew].tpe
    val newNames = getColumnInfo(c)(tnew)
    val colsExp = getColumns(c)(told, "")
    val fields = newNames map { case (name, ty) =>
      if (ty.toString() == "Int") {
        tq"AggTypedColumn[ThisTransform,$ty]"
      } else {
        tq"DstTypedColumn[ThisTransform,$ty]"
      }
    }

    val qargs1 = for (((n, ty), i) <- newNames.zipWithIndex) yield {
      val pos = TermName(s"_${i + 1}")
      q"""(f.$pos.col).as($n)"""
    }

    val q =
      q"""
         new {
             class ThisTransform extends DstTransform

             def fix1(df:DataFrame, a:AggIntColumn[ThisTransform]):DataFrame = {
               df.withColumnRenamed(a.kind ++ "(" ++  a.col.name ++ ")", a.col.name)
               .withColumn(a.col.name, a.col.col.cast(IntegerType))
             }

             def fixAll(df:DataFrame, as:Seq[AggIntColumn[ThisTransform]]) = as.foldLeft(df)(fix1)

             val cols = $colsExp

             def act(fields: (cols.type) => (..$fields)) = {
                val s = fields(cols).productIterator.toList
                val f = s.collect{case x:DstColumn[ThisTransform] @unchecked => x}.map(_.col)
                val a = s.collect{case x:AggIntColumn[ThisTransform] @unchecked => x}
                val m:Map[String,String] = a.map{case aic => aic.col.name -> aic.kind}.toMap
                (ds:Dataset[$told]) => {
                  val df1 = ds.toDF().groupBy(f:_*).agg(m)
                  fixAll(df1,a).as[$tnew]
                 }
             }
             override def toString() = "SqlAgg[" + ${told.toString} + "," + ${tnew.toString} + "]"
          }
      """
    c.Expr(q)
  }

  def FuncFilter[TOLD](f: (TOLD) => Boolean): Any = macro funcFilterImpl[TOLD]

  def funcFilterImpl[Told: c.WeakTypeTag]
  (c: Context)(f: c.Expr[Any]): c.Expr[Any] = {
    import c.universe._
    val told = c.weakTypeTag[Told].tpe
    val q =
      q"""
      (ds:Dataset[$told]) => {
        ds.filter($f)
      }
      """
    c.Expr(q)
  }

  def SqlFilter[TOLD]: Any = macro sqlFilterImpl[TOLD]

  def sqlFilterImpl[Told: c.WeakTypeTag]
  (c: Context): c.Expr[Any] = {
    import c.universe._
    val told = c.weakTypeTag[Told].tpe
    val oldNames = getColumnInfo(c)(told)
    val colsExp = getColumns(c)(told, "")
    val q =
      q"""
         new {
             class ThisTransform extends DstTransform

             val cols = $colsExp

             def act(fields: (cols.type) => DstBooleanColumn[ThisTransform]) = {
                val f = fields(cols)
                (ds:Dataset[$told]) => {
                  ds.toDF().filter(f.col).as[$told]
                 }
             }
             override def toString() = "SqlFilter[" + ${told.toString} + "]"
          }
      """
    c.Expr(q)
  }

  private def getColumns(c: Context)(ty: c.universe.Type, ext: String): c.Expr[Any] = {
    import c.universe._
    val transform = "ThisTransform" //+ ext
    val prefix = if (ext.isEmpty) "" else ext + "."
    val className = ty.toString
    val ci = getColumnInfo(c)(ty)
    val tytransform = TypeName(transform)
    val names = ci.flatMap { case (name, tyc) =>
      val colName = s"COLUMN_$name"
      val colNameN = TypeName(colName)
      val nameT = TermName(name)
      val ct = if (tyc == c.weakTypeOf[Int]) {
        tq"DstIntColumn[$tytransform]"
      } else if (tyc == c.weakTypeOf[Boolean]) {
        tq"DstBooleanColumn[$tytransform]"
      } else {
        tq"DstTypedColumn[$tytransform,$tyc]"
      }
      val q1 =
        q"""
           class $colNameN extends $ct {
             val name = ${prefix + name}
             val col = new ColumnName(${prefix + name})
          }
        """
      val q2 =
        q"""
          val $nameT = new $colNameN
        """
      Seq(q1, q2)
    }
    val q1 = q"""new { ..$names }"""
    c.Expr(q1)
  }

}


text:
<?xml version="1.0"?>
<layers>
  <layer
    name="mitr.sitetheme"
    interface="mitr.sitetheme.interfaces.IMitrSiteThemeLayer"
  />
</layers>


text:
package gov.samhsa.consent2share.domain.provider;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

/**
 * The Interface OrganizationalProviderRepository.
 */
@Repository
public interface OrganizationalProviderRepository extends JpaRepository<OrganizationalProvider, Long>, JpaSpecificationExecutor<OrganizationalProvider> {

	/**
	 * Find by npi.
	 *
	 * @param npi the npi
	 * @return the organizational provider
	 */
	public abstract OrganizationalProvider findByNpi(String npi);
}


text:
<?php

/* FOSUserBundle:Profile:show.html.twig */
class __TwigTemplate_fe29ca401609ccd825a26553263cdf267a21aacad46522a07345dd677de8aa16 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("FOSUserBundle::layout.html.twig", "FOSUserBundle:Profile:show.html.twig", 1);
        $this->blocks = array(
            'fos_user_content' => array($this, 'block_fos_user_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "FOSUserBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_b89a6da49163168b5b0e1e650f6d5c013aba143f24c4e91092b95c34312ea598 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_b89a6da49163168b5b0e1e650f6d5c013aba143f24c4e91092b95c34312ea598->enter($__internal_b89a6da49163168b5b0e1e650f6d5c013aba143f24c4e91092b95c34312ea598_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "FOSUserBundle:Profile:show.html.twig"));

        $this->parent->display($context, array_merge($this->blocks, $blocks));

        $__internal_b89a6da49163168b5b0e1e650f6d5c013aba143f24c4e91092b95c34312ea598->leave($__internal_b89a6da49163168b5b0e1e650f6d5c013aba143f24c4e91092b95c34312ea598_prof);

    }

    // line 3
    public function block_fos_user_content($context, array $blocks = array())
    {
        $__internal_b873afeeff22f66e091e57c90988b4597f1d0bed74972987d505d431b7e444af = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_b873afeeff22f66e091e57c90988b4597f1d0bed74972987d505d431b7e444af->enter($__internal_b873afeeff22f66e091e57c90988b4597f1d0bed74972987d505d431b7e444af_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "fos_user_content"));

        // line 4
        $this->loadTemplate("FOSUserBundle:Profile:show_content.html.twig", "FOSUserBundle:Profile:show.html.twig", 4)->display($context);

        $__internal_b873afeeff22f66e091e57c90988b4597f1d0bed74972987d505d431b7e444af->leave($__internal_b873afeeff22f66e091e57c90988b4597f1d0bed74972987d505d431b7e444af_prof);

    }

    public function getTemplateName()
    {
        return "FOSUserBundle:Profile:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  40 => 4,  34 => 3,  11 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{% extends \"FOSUserBundle::layout.html.twig\" %}

{% block fos_user_content %}
{% include \"FOSUserBundle:Profile:show_content.html.twig\" %}
{% endblock fos_user_content %}
", "FOSUserBundle:Profile:show.html.twig", "C:\\wamp\\www\\ecommerce\\app\\Resources\\FOSUserBundle\\views\\Profile\\show.html.twig");
    }
}