text:
//
// Copyright 2014 Mobile Jazz SL
//
// 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.
//

#import <Foundation/Foundation.h>

#import "HMRequest.h"
#import "HMUploadRequest.h"
#import "HMResponse.h"
#import "HMRequestExecutor.h"
#import "HMConfigurationManager.h"

/**
 * Cache managmenet flags.
 **/
typedef NS_ENUM(NSInteger, HMClientCacheManagement)
{
    /** Default cache management. */
    HMClientCacheManagementDefault,

    /** When offline (no reachability to the internet), cache will be used. */
    HMClientCacheManagementOffline
};

/**
 * Debug logs flags.
 **/
typedef NS_OPTIONS(NSUInteger, HMClientLogLevel)
{
    /** No logs will be done. */
    HMClientLogLevelNone         = 0,

    /** Requests will be logged (including a curl). */
    HMClientLogLevelRequests     = 1 << 0,

    /** Responses will be logged. */
    HMClientLogLevelResponses    = 1 << 1,
};

typedef NS_OPTIONS(NSUInteger, HMClientRequestSerializerType)
{
    /** applicaiton/JSON */
    HMClientRequestSerializerTypeJSON = 0,

    /** applicaiton/x-www-form-urlencoded with utf8 charset */
    HMClientRequestSerializerTypeFormUrlencoded = 1,
};

typedef NS_OPTIONS(NSUInteger, HMClientResponseSerializerType)
{
    /** JSON responses */
    HMClientResponseSerializerTypeJSON = 0,

    /** RAW responses */
    HMClientResponseSerializerTypeRaw = 1,
};

@protocol HMClientDelegate;

/* ************************************************************************************************** */
#pragma mark -

/**
 * The configurator object.
 **/
@interface HMClientConfigurator : NSObject

/**
 * Automatic API Configuration.
 **/
- (void)configureWithConfiguration:(HMConfiguration * _Nonnull)configuration;

/** ************************************************* **
 * @name Configurable properties
 ** ************************************************* **/

/**
 * The host of the API client. Default value is nil.
 **/
@property (nonatomic, strong, readwrite, nonnull) NSString *serverPath;

/**
 * An aditional API route path to be inserted after the host and before the REST arguments. Default value is nil.
 * @discussion Must be prefixed with "/"
 **/
@property (nonatomic, strong, readwrite, nullable) NSString *apiPath;

/**
 * The cache managemenet strategy. Default value is `HMClientCacheManagementDefault`.
 **/
@property (nonatomic, assign, readwrite) HMClientCacheManagement cacheManagement;

/**
 * The request serializer type. Default value is `HMClientRequestSerializerTypeJSON`.
 **/
@property (nonatomic, assign, readwrite) HMClientRequestSerializerType requestSerializerType;

/**
 * The response serializer type. Default value is `HMClientResponseSerializerTypeJSON`.
 **/
@property (nonatomic, assign, readwrite) HMClientResponseSerializerType responseSerializerType;

/**
 * The request timeout interval. Default value is 60 seconds.
 **/
@property (nonatomic, assign) NSTimeInterval timeoutInterval;

/**
 * Requests completion block will be executed on the given queue.
 * @discussion If nil, blocks will be executed on the main queue.
 **/
@property (nonatomic, strong, readwrite, nullable) dispatch_queue_t completionBlockQueue;

/**
 * The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
 */
@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;

@end

/* ************************************************************************************************** */
#pragma mark -

/**
 * An API client.
 * This class build on top of AFNetworking a user-friendly interface to manage API requests and responses.
 * The only constraint is that the backend services must always accept and return application/json HTTP requests and responses.
 **/
@interface HMClient : NSObject <HMRequestExecutor>

/** ************************************************* **
 * @name Main initializers
 ** ************************************************* **/

/**
 * Deprecated initializer.
 * @param serverPath The serverPath. For example: https://www.mydomain.com
 * @param apiPath Additiona API route. For example: /api/v2
 * @return An initialized instance.
 **/
- (instancetype _Nonnull)initWithServerPath:(NSString * _Nonnull)serverPath apiPath:(NSString * _Nullable)apiPath;

/**
 *  Designated initializer.
 *  @param configuratorBlock A HMClientConfigurator block
 *  @return The instance initialized
 */
- (instancetype _Nonnull)initWithConfigurator:(void (^_Nonnull)(HMClientConfigurator * _Nonnull configurator))configuratorBlock;

/** ************************************************* **
 * @name Configuring the client
 ** ************************************************* **/

/**
 * Reconfigure the API client.
 * @param configuratorBlock A HMClientConfigurator block
 **/
- (void)reconfigureWithConfigurator:(void (^_Nonnull)(HMClientConfigurator * _Nonnull configurator))configuratorBlock;

/**
 * The server path of the API client.
 **/
@property (nonatomic, strong, readonly, nonnull) NSString *serverPath;

/**
 * An aditional API route path to be inserted after the host and before the REST arguments.
 * @discussion Must be prefixed with "/"
 **/
@property (nonatomic, strong, readonly, nullable) NSString *apiPath;

/**
 * The cache managemenet strategy.
 **/
@property (nonatomic, assign, readonly) HMClientCacheManagement cacheManagement;

/**
 * Requests completion block will be executed on the given queue.
 * @discussion If nil, blocks will be executed on the main queue.
 **/
@property (nonatomic, strong, readonly, nullable) dispatch_queue_t completionBlockQueue;

/** ************************************************* **
 * @name Authorization Headers
 ** ************************************************* **/

/**
 * Sets a barear token (typically from OAuth access tokens). Replaces the basic authentication header.
 * @param token The authorization token.
 * @discussion If nil, this method will remove the bearer token header.
 **/
- (void)setBearerToken:(NSString * _Nullable)token;

/**
 * Sets a basic authorization setup. Replaces the bearer token header.
 * @param username The username.
 * @param password The password.
 * @discussion If username or password are nil (or both are nil), this method will remove the basic authentication header.
 **/
- (void)setBasicAuthWithUsername:(NSString * _Nonnull)username password:(NSString * _Nonnull)password;

/**
 * Sets a generic "Authorization" value in the Header of the HTTP request.
 * @param value The authorization value.
 * @discussion If nil, this method will remove the authorization header.
 **/
- (void)setAuthorizationHeader:(NSString * _Nullable)value;

/**
 * Clears all authorization headers.
 **/
- (void)removeAuthorizationHeaders;

/** ************************************************* **
 * @name HTTP Headers
 ** ************************************************* **/

/**
 * Dictionary containing additional HTTP header parameters. Default is nil.
 **/
@property (nonatomic, strong, nullable) NSDictionary *headerParameters;

/** ************************************************* **
 * @name Localization
 ** ************************************************* **/

/**
 * If YES, automatically configures the Accept-Language HTTP header to the current device language. Default value is YES.
 **/
@property (nonatomic, assign) BOOL insertAcceptLanguageHeader;

/**
 * If YES, it will insert a language parameter inside all body requests. Default value is NO.
 **/
@property (nonatomic, assign) BOOL insertLanguageAsParameter;

/**
 * The name of the body request language parameter. Default value is "language".
 **/
@property (nonatomic, strong, nonnull) NSString *languageParameterName;

/** ************************************************* **
 * @name Requests
 ** ************************************************* **/

/**
 * A dictionary of parameters that are going to be added to all requests. Default is nil.
 * @discussion Global parameters are added before sending the URL request. If duplicated parameter keys, the values in this dictionary will be the final ones.
 **/
@property (nonatomic, strong, nullable) NSDictionary *requestGlobalParameters;

/** ************************************************* **
 * @name Delegate
 ** ************************************************* **/

/**
 * Delegate object.
 **/
@property (nonatomic, weak, nullable) id <HMClientDelegate> delegate;

/** ************************************************* **
 * @name Logging
 ** ************************************************* **/

/**
 * The log level of the api client. Default value is `HMClientLogLevelNone`.
 **/
@property (nonatomic, assign) HMClientLogLevel logLevel;

@end

/* ************************************************************************************************** */
#pragma mark -

/**
 * Delegate of an API client.
 **/
@protocol HMClientDelegate <NSObject>

/** ************************************************* **
 * @name Managing errors
 ** ************************************************* **/

@optional
/**
 * By implementing this method, the delegate thas the oportunity to create custom errors depending on the incoming response body or the incoming error.
 * @param apiClient The API client.
 * @param responseBody The response body (can be nil).
 * @param httpResponse The HTTP URL Response.
 * @param error The incoming error (can be nil).
 * @discussion This method is called for every succeed and failed API response. Either the response body is not nil, the error is not nil or both are not nil.
 **/
- (NSError * _Nullable)apiClient:(HMClient * _Nonnull)apiClient errorForResponseBody:(id _Nullable)responseBody httpResponse:(NSHTTPURLResponse * _Nonnull)httpResponse incomingError:(NSError * _Nullable)error;

/**
 * Notifies the delegate that an api response has got an error.
 * @param apiClient The API client.
 * @param response The API response with an error.
 **/
- (void)apiClient:(HMClient * _Nonnull)apiClient didReceiveErrorInResponse:(HMResponse * _Nonnull)response;

@end

redpajama_set_name: RedPajamaGithub


text:
Type "erm.Entity"
{
	entity = "erm.IEntity"
}

Type "erm.Model"
{
	model = "erm.IModel"
}

Type "erm.Relationship"
{
	relationship = "erm.IRelationship",
	entityA = "erm.IEntity",
}

Type "erm.Multiplicity"
{
	min = "int32",
	max = "int32",
}

Type "erm.IEntity"
{
	name = "string",
	parent = "erm.IEntity",
}

Type "erm.IModel"
{
	entities = "erm.IEntity[]",
	throwsOnGet = "bool" ,
	relationships = "erm.IRelationship[]",
}

Type "erm.IRelationship"
{
	entityA = "erm.IEntity",
	entityB = "erm.IEntity",
	multiplicityA = "erm.Multiplicity",
	multiplicityB = "erm.Multiplicity",
}


text:
var Marionette = require('backbone.marionette');

var tpl = require('./header.hbs');

module.exports = Marionette.ItemView.extend({

    template: tpl,

    ui: {
        input: '#new-todo'
    },

    events: {
        'submit form': 'onSubmit'
    },

    onSubmit: function (e) {
        // prevent form orignal submit
        e.preventDefault();

        var todoText = this.ui.input.val().trim();
        if (todoText) {
            this.collection.create({
                title: todoText
            });
            this.ui.input.val('');
        }
    }

});


text:
    var fs = require('fs-extra');
    var url = require('url');
    var request = require('request');
    var querystring = require('querystring');
    var electron = require('electron').remote;
    var BrowserWindow = electron.BrowserWindow;
    var ipcRenderer = require('electron').ipcRenderer;
    var shell = require('electron').shell;
    var remote = require('electron').remote;
    var dialog = require('electron').remote.dialog;
    var path = require('path');

    var ptcJar = request.jar();
    var ptcReq = request.defaults({
        headers: {'User-Agent': 'niantic'},
        jar: ptcJar
    });

    var geoLocation = "34.0432108, -118.2675059";

    $( document ).ready(function(){
        // Show version
        $('#version').html('Version ' + electron.app.getVersion());
        // Get checkbox state
        [
            'remember'
        ].forEach(function(elem){
            if (localStorage.getItem(elem)) {
                document.getElementById(elem).checked = (
                    localStorage.getItem(elem) == "true");
            }
            $('#' + elem).change(function() {
                localStorage.setItem(elem, !!this.checked);
            });
        });

        if (checked('remember')) {
            setupValue('ptc_username', $('#ptc_username'));
            setupValue('ptc_password', $('#ptc_password'));
            setupValue('google_username', $('#google_username'));
            setupValue('google_password', $('#google_password'));
            //Open login section if we have saved username
            if (localStorage.getItem('ptc_username')) {
                $('.collapsible li:eq(1) .collapsible-header').click();
            }else if(localStorage.getItem('google_username')) {
                $('.collapsible li:eq(0) .collapsible-header').click();
            }
        }
        setupValue('google_maps_api', $('#google_maps_api'));
        setupValue('walk_speed', $('#walk_speed'));
        setupValue('last_location', $('#location'));
    });

    function openFile () {
      dialog.showOpenDialog(function (fileNames) {
        fs.copySync((fileNames[0]), path.join(__dirname, '../gofbot/encrypt'+fileNames[0].match(/\.\w+/)[0]));
        var file_end = fileNames[0]
        document.getElementById('file_path').innerHTML = fileNames[0]
      });
    }

    function setupValue(key, elem) {
        if (localStorage.getItem(key)) {
            elem.val(localStorage.getItem(key));
        }
    }

    function setupValueAndSetter(key, elem) {
        setupValue(key, elem);
        elem.change(function() {
            localStorage.setItem(key, elem.val());
        });
    }

    function checked(elemId) {
        return document.getElementById(elemId).checked;
    }

    function saveState() {
        if (checked('remember')) {
            localStorage.setItem("ptc_username", $('#ptc_username').val());
            localStorage.setItem("ptc_password", $('#ptc_password').val());
            localStorage.setItem("google_username", $('#google_username').val());
            localStorage.setItem("google_password", $('#google_password').val());
        }
        localStorage.setItem("last_location", $('#location').val());
        localStorage.setItem("google_maps_api", $('#google_maps_api').val());
        localStorage.setItem("walk_speed", $('#walk_speed').val());

    }

    navigator.geolocation.getCurrentPosition(function success(position) {
        geoLat = position.coords.latitude;
        geoLon = position.coords.longitude;
        $('#location').prop('placeholder', ''+geoLat+', '+geoLon);
        console.log("Got location: " + geoLat + ", " + geoLon);
    }, function error(err) {
        console.log("Error getting location, trying second provider", err);
        $.getJSON("http://ipinfo.io", function(ipinfo){
            console.log("Found location ["+ipinfo.loc+"] by ipinfo.io");
            var latLong = ipinfo.loc.split(",");
            geoLat = latLong[0];
            geoLon = latLong[1];
            $('#location').prop('placeholder', ''+geoLat+', '+geoLon);
        });
    });

    ipcRenderer.on('pythonLog', function(evt, data) {
        console.log(data.msg);
    });

    ipcRenderer.on('appLog', function(evt, data) {
        console.log(data.msg);
    });

    function toggleLogin(disabled) {
        saveState();
        jQuery('.login').prop("disabled", disabled);
    }

    function doGoogleLogin() {
        toggleLogin(true);
        var username = jQuery('#google_username').val(),
            password = jQuery('#google_password').val();

        // Reset cookie jar
        ptcJar = request.jar();

        completeLogin('google', '');

        return false;
    }

    function doPTCLogin() {
        toggleLogin(true);
        jQuery('#ptc_errors').html('');
        var username = jQuery('#ptc_username').val(),
            password = jQuery('#ptc_password').val();

        // Reset cookie jar
        ptcJar = request.jar();

        // Get Login session from SSO servers
        ptcReq.get('https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize',
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                doPTCLoginStep2(username, password, JSON.parse(body));
            } else {
                console.log(error);
                toggleLogin(false);
                alert('Oops! Something went wrong and we couldn\'t ' +
                    'log you in. Please try again. Code 6.');
            }
        });

        return false;
    }

    function doPTCLoginStep2(user, pass, session) {
        var loginData = {
            'lt': session.lt,
            'execution': session.execution,
            '_eventId': 'submit',
            'username': user,
            'password': pass
        };

        ptcReq.post(
                'https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize',
                {form: loginData},
                function (error, response, body) {
                    if (!error && response.statusCode == 302) {
                        var rawRedirect = response.headers.location;
                        handlePokemonCallback(rawRedirect);
                    } else {
                        toggleLogin(false);
                        var errors = null;
                        try {
                            errors = JSON.parse(body).errors;
                            errors = errors.join(' ');
                        } catch(e) {}
                        if (errors) {
                            jQuery('#ptc_errors').html(errors);
                        } else {
                            alert('Oops! Something went wrong and we couldn\'t ' +
                                'log you in. Please try again. Code 7.');
                        }
                    }
                }
            );
    }

    function handlePokemonCallback(newUrl) {

      // Login by passing in password to prevent timeouts
      completeLogin('ptc', '');

    }

    function completeLogin(auth, code) {
        var userLocation = $('#location').val();
        if (userLocation != '') {
            geoLocation = userLocation;
        };

        ipcRenderer.send('startPython', auth, code, geoLocation, {
            google_maps_api: $('#google_maps_api').val(),
            walk_speed: $('#walk_speed').val(),
            ptc_username: $('#ptc_username').val(),
            ptc_password: $('#ptc_password').val(),
            mode: $("input[name='mode']:checked").val(),
            google_username: $('#google_username').val(),
            google_password: $('#google_password').val()
        });
    }

    function openURL(url) {
        shell.openExternal(url);
    }


text:
package universe.constellation.orion.viewer;

/**
 * User: mike
 * Date: 29.08.12
 * Time: 12:58
 */
public class PageWalker {

    public static enum DIR {
        //X, Y, -X, -Y
        X (1), Y(1), X_M(-1), Y_M(-1);

        private final int delta;

        DIR(int delta) {
            this.delta = delta;
        }

        public DIR inverse() {
            switch (this) {
                case X : return X_M;
                case X_M: return X;
                case Y: return Y_M;
                case Y_M: return Y;
            }
            return X;
        }

        public boolean isX() {
            return this == X_M || this == X;
        }

        public boolean toLeftOrUp() {
            return this == X_M || this == Y_M;
        }

        public boolean toRightOrDown() {
            return this == X || this == Y;
        }
    }

    public static enum WALK_ORDER {

        ABCD (0, DIR.X, DIR.Y), ACBD (1, DIR.Y, DIR.X), BADC(2, DIR.X_M, DIR.Y), BDAC (3, DIR.Y, DIR.X_M);

        private final DIR first;

        private final DIR second;

        WALK_ORDER(int code, DIR first, DIR second) {
            this.first = first;
            this.second = second;
        }

        public String code() {
            return this.name();
        }

        public boolean isLeftToRight() {
            return this == ABCD || this == ACBD;
        }
    };

    private boolean doCentering = true;

    private WALK_ORDER direction;

    private SimpleLayoutStrategy layout;

    public PageWalker(String direction, SimpleLayoutStrategy layout) {
        WALK_ORDER [] values = WALK_ORDER.values();
        this.direction = WALK_ORDER.ABCD;
        for (int i = 0; i < values.length; i++) {
            WALK_ORDER value = values[i];
            if (value.code().equals(direction)) {
                this.direction = value;
                break;
            }
        }
        this.layout = layout;
    }

    public boolean next(LayoutPosition info) {
        return next(info, direction.first, direction.second);
    }

    public boolean prev(LayoutPosition info) {
        return next(info, direction.first.inverse(), direction.second.inverse());
    }

    //true if should show prev/next page
    private boolean next(LayoutPosition info, DIR firstDir, DIR secondDir) {
        boolean isX = firstDir.isX();
        OneDimension first = isX ? info.x : info.y;
        OneDimension second = isX ? info.y : info.x;

        boolean changeSecond = true;
        int newFirstOffset = -1;
        int newSecondOffset = -1;

        for (int i = 1; i <= 2; i ++) {
            OneDimension dimension = i == 1 ? first : second;
            DIR dir = i == 1 ? firstDir : secondDir;

            boolean inverseX = dir.isX() && !direction.isLeftToRight();
            int offset = inverseX ? dimension.pageDimension - dimension.offset - dimension.screenDimension: dimension.offset;
            dir = inverseX ? dir.inverse() : dir;

            if (changeSecond) {
                changeSecond = false;

                int newOffsetStart = offset + dimension.screenDimension * dir.delta;
                int newOffsetEnd = newOffsetStart + dimension.screenDimension - 1;

                if (!inInterval(newOffsetStart, dimension) && !inInterval(newOffsetEnd, dimension)) {
                    changeSecond = true;
                    offset = reset(dir, dimension, 0);
                } else {
                    if (needAlign(dir) && (!inInterval(newOffsetStart, dimension) || !inInterval(newOffsetEnd, dimension))) {
                        offset = align(dir, dimension);
                    } else {
                        offset = newOffsetStart - dimension.overlap * dir.delta;
                    }
                }
            }

            offset = inverseX ? dimension.pageDimension - offset - dimension.screenDimension: offset;

            if (i == 1) {
                newFirstOffset = offset;
            } else {
                newSecondOffset = offset;
            }
        }

        if (!changeSecond) {
            (isX ? info.x : info.y).offset = newFirstOffset;
            second.offset = newSecondOffset;
        }

        return changeSecond;
    }

    private int reset(DIR dir, OneDimension dim, int possibleOffset) {
        if (doCentering) {
            if (dim.pageDimension < dim.screenDimension) {
                return (dim.pageDimension - dim.screenDimension) / 2;
            }
        }

        if (dir.toRightOrDown() || dim.pageDimension <= dim.screenDimension || dim.screenDimension == 0) {
            return 0;
        } else {
            if (!needAlign(dir)) {
                return  ((dim.pageDimension - dim.overlap) / (dim.screenDimension - dim.overlap)) * (dim.screenDimension - dim.overlap);
            } else {
                return dim.pageDimension - dim.screenDimension;
            }
        }
    }

    private int align(DIR dir, OneDimension dim) {
        if (dir.toRightOrDown()) {
            return dim.pageDimension - dim.screenDimension;
        } else {
            return 0;
        }
    }

    private boolean needAlign(DIR dir) {
        return dir.isX() && layout.getLayout() != 0 || (!dir.isX() && layout.getLayout() == 1);
    }

    private boolean inInterval(int value, OneDimension dim) {
        return value >= 0 && value < dim.pageDimension;
    }

    public void reset(LayoutPosition info, boolean isNext) {
        DIR first = isNext ? direction.first : direction.first.inverse();
        DIR second = isNext ? direction.second : direction.second.inverse();

        DIR horDir = first.isX() ? first : second;
        DIR vertDir = first.isX() ? second : first;

        boolean inverse = !direction.isLeftToRight();
        horDir = inverse ? horDir.inverse() : horDir;
        info.x.offset = reset(horDir, info.x, 0);
        info.x.offset = inverse ? info.x.pageDimension - info.x.screenDimension - info.x.offset : info.x.offset;

        info.y.offset = reset(vertDir, info.y, 0);
    }

    public String getDirection() {
        return direction.name();
    }

}


text:
struct NVGcontext;
struct GLFWwindow;

class Window
{
public:
  Window(std::pair<int, int> const& windowsize = std::make_pair(640, 480));
  ~Window();

  // Draw a line starting at (startX,startY) to (endX, endY) with color (r,g,b)
  // where (startX,startY), (endX, endY) \in [0,1)^2 and (r,g,b) \in [0,1)^3
  void draw_line(float startX, float startY,
                float endX, float endY,
                float r, float g, float b,
                float thickness = 1.0
                ) const;

  // Draw a point at (x,y) with color (r,g,b)
  // where (x,y)\in [0,1)^2 and (r,g,b) \in [0,1)^3
  void draw_point(float x, float y, float r, float g, float b) const;

  void draw_text(float x, float y, float font_size, std::string const& text) const;

  // Return the mouse position in screen coordinates
  std::pair<double, double> mouse_position() const;

  // is closed flag set
  bool should_close() const;

  // close window
  void close();

  // update window
  void update();

  // test if given key is pressed
  // See here for key codes:
  // http://www.glfw.org/docs/latest/group__keys.html
  int get_key(int key) const;
  int get_mouse_button(int button) const;

  // current window size
  std::pair<int, int> window_size() const;

  // time elapsed since GLFW was initialized
  float get_time() const;

private:
  GLFWwindow* m_window;
  NVGcontext* m_nvgContext;
  std::pair<int, int> m_windowSize;
  std::pair<int, int> m_framebufferSize;
  std::string const m_title;

  int m_font_normal;
  int m_font_bold;
  int m_font_icons;
  int m_font_emoji;
};

#endif // define BUW_WINDOW_HPP


text:
A [Zhihu](http://www.zhihu.com/) crawler based on Python2.7

**More APIs being updated.**

## API reference

### Session
* login()
* logout()

### Question
* get_title()
* get_description()
* get_num_answers()
* get_num_followers()
* get_topics()
* get_related_questions()
* get_answers()
* get_followers()
* get_all_answers(limit = sys.maxsize)
* get_all_followers(limit = sys.maxsize)

### User
* get_name()
* get_biography()
* get_about()
* get_num_followees()
* get_num_followers()
* get_num_agrees()
* get_num_thanks()
* get_num_asks()
* get_num_answers()
* get_num_column_papers()
* get_answers()
* get_asks()
* get_followees()
* get_followers()
* get_all_answers(limit = sys.maxsize)
* get_all_asks(limit = sys.maxsize)
* get_all_followees(limit = sys.maxsize)
* get_all_followers(limit = sys.maxsize)

### Collection
* get_title()
* get_creator()

### Answer
* get_author()
* get_num_upvotes()
* get_num_comments()
* get_num_collects()
* get_content_text()

### Topic
* get_num_followers()
* get_description()


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="agile_nimble_board.utils.controller_utils.class">Agile\NimbleBoardBundle\Utils\ControllerUtils</parameter>
        <parameter key="agile_nimble_board.controller.project.class">Agile\NimbleBoardBundle\Controller\ProjectController</parameter>
    </parameters>

    <services>
        <service id="agile_nimble_board.utils.controller_utils" class="%agile_nimble_board.utils.controller_utils.class%">
            <argument type="service" id="service_container" />
        </service>
        <service id="agile_nimble_board.controller.project" class="%agile_nimble_board.controller.project.class%">
            <argument type="service" id="agile_nimble_board.utils.controller_utils" />
        </service>
    </services>
</container>


text:
```csharp
public class Artigo
{
    public string Autor { get; set; }
    public string Canal { get; set; }
    public DateTime Data { get; set; }

    public static void Main()
    {
        new Artigo()
        {
            Autor = "Erlimar Silva Campos",
            Canal = "http://erlimar.wordpress.com",
            Data = new DateTime(2015, 2, 13)
        };
    }
}
```

Este repositório contém o código fonte construído na série de artigos sobre ASP.NET/5 (acesse a série [clicando aqui](http://goo.gl/ocH82S)), além de materiais e outras informações complementares.

## Tópicos

1. Introdução
2. Preparando o ambiente
3. Peças fundamentais de um projeto
4. Um projeto web, OWIN e o Startup
5. MVC, Controllers
6. MVC, Views
7. MVC, Models
8. Injeção de dependências
9. Organização do código fonte, Básico
10. Organização do código fonte, Componentes
11. Organização do código fonte, Produtos
12. Runtime, CLR e CoreCLR
13. Project.JSON, Dependências
14. Project.JSON, Diretivas
15. Project.JSON, Comandos
16. Empacotando componentes e publicando no NuGet.org
17. Boas práticas, Code Standards e Extensão de métodos
18. No Visual Studio
19. Middleware
20. Recursos
21. Deploy

## Encontrando o material correto

A série de artigos pretende construir um conteúdo, que vai evoluindo de acordo com que os tópicos são apresentados, de forma que este repositório conterá o conteúdo final.

Mas você poderá encontrar uma [TAG](https://github.com/e5r-learning/serie-helloaspnet5/tags) correspondente a cada tópico relevante nos artigos, assim você poderá obter o material exatamente como estava na época que foi apresentado.

## [Licença](LICENSE)

```
The MIT License (MIT)

Copyright (c) 2015 E5R Learning and Training

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.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 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.
```


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    /// <summary> Defines a managed rule set. </summary>
    public partial class ManagedRuleSet
    {
        /// <summary> Initializes a new instance of ManagedRuleSet. </summary>
        /// <param name="ruleSetType"> Defines the rule set type to use. </param>
        /// <param name="ruleSetVersion"> Defines the version of the rule set to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="ruleSetType"/> or <paramref name="ruleSetVersion"/> is null. </exception>
        public ManagedRuleSet(string ruleSetType, string ruleSetVersion)
        {
            Argument.AssertNotNull(ruleSetType, nameof(ruleSetType));
            Argument.AssertNotNull(ruleSetVersion, nameof(ruleSetVersion));

            RuleSetType = ruleSetType;
            RuleSetVersion = ruleSetVersion;
            RuleGroupOverrides = new ChangeTrackingList<ManagedRuleGroupOverride>();
        }

        /// <summary> Initializes a new instance of ManagedRuleSet. </summary>
        /// <param name="ruleSetType"> Defines the rule set type to use. </param>
        /// <param name="ruleSetVersion"> Defines the version of the rule set to use. </param>
        /// <param name="ruleGroupOverrides"> Defines the rule group overrides to apply to the rule set. </param>
        internal ManagedRuleSet(string ruleSetType, string ruleSetVersion, IList<ManagedRuleGroupOverride> ruleGroupOverrides)
        {
            RuleSetType = ruleSetType;
            RuleSetVersion = ruleSetVersion;
            RuleGroupOverrides = ruleGroupOverrides;
        }

        /// <summary> Defines the rule set type to use. </summary>
        public string RuleSetType { get; set; }
        /// <summary> Defines the version of the rule set to use. </summary>
        public string RuleSetVersion { get; set; }
        /// <summary> Defines the rule group overrides to apply to the rule set. </summary>
        public IList<ManagedRuleGroupOverride> RuleGroupOverrides { get; }
    }
}


text:
A very simple example ruby router you should never actually use. Just for learning purposes. Built for the book [BuildYourOwnSinatra](https://buildYourOwnSinatra.com)

## Installation

Add to your Gemfile:

```ruby
gem 'a-simple-route', github: 'BuildYourOwnSinatra/a-simple-router'
```

## Usage

Place the following in a rackup file

```ruby
require 'a-simple-router'
run ASimpleRouter.new do
  get '/cats', {200, {}, ["Cats!"]}
end
```


text:
[![Identifier](https://img.shields.io/badge/doi-10.5438%2Fcxe5--rg55-fca709.svg)](https://doi.org/10.5438/cxe5-rg55)
![Release](https://github.com/datacite/bracco/workflows/Release/badge.svg)
[![bracco](https://img.shields.io/endpoint?url=https://dashboard.cypress.io/badge/detailed/8j7yje&style=flat&logo=cypress)](https://dashboard.cypress.io/projects/8j7yje/runs)
[![Code Climate](https://codeclimate.com/github/datacite/bracco/badges/gpa.svg)](https://codeclimate.com/github/datacite/bracco)
[![Test Coverage](https://codeclimate.com/github/datacite/bracco/badges/coverage.svg)](https://codeclimate.com/github/datacite/bracco/coverage)

# Bracco

The web frontend for the DataCite Fabrica service.

## Prerequisites

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

- [Git](https://git-scm.com/)
- [Node.js](https://nodejs.org/) (with NPM) - 14.x
- [Ember CLI](https://ember-cli.com/)

## Installation

- `git clone <repository-url>` this repository
- `cd bracco`
- `cp .env.example .env`
- `yarn`

## Running / Development

- `yarn ember serve`
- Visit your app at [http://localhost:4200](http://localhost:4200).

### Code Generators

Make use of the many generators for code, try `ember help generate` for more details

### Running Tests

- `ember test`
- `ember test --server`

### Linting

- `npm run lint:hbs`
- `npm run lint:js`
- `npm run lint:js -- --fix`

### Building

- `ember build` (development)
- `ember build --environment production` (production)

### Deploying

The application as Docker containers via GitHub Actions and AWS Fargate.

#### Nginx

```
server {
    server_name example.org;
    listen 8080;
    set $frontend http://example.org.s3.amazonaws.com;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;

        proxy_pass $frontend;
    }

    location /assets {
        proxy_pass $frontend;
    }
```

#### Cloudfront (using [terraform](https://www.terraform.io/))

```
custom_error_response {
  error_code            = "404"
  error_caching_min_ttl = "5"
  response_code         = "200"
  response_page_path    = "/index.html"
}
```

### Note on Patches/Pull Requests

- Fork the project
- Write tests for your new feature or a test that reproduces a bug
- Implement your feature or make a bug fix
- Do not mess with Rakefile, version or history
- Commit, push and make a pull request. Bonus points for topical branches.

## License

**bracco** is released under the [MIT License](https://github.com/datacite/bracco/blob/master/LICENSE).


text:
Timer
=====

This module will not load unless ProtocolLib is installed and is not disableable.

The icon for this module is clock.

For documentation on the timer command visit the [/timer documentation](../commands/timer.md)

At least 1 of 'boss bar' or 'action bar' must be used for this module to load.
If neither are enabled this module will fail to load, if both are loaded then
the boss bar takes precendence.

This module requires either 1.9+ (boss bar) or ProtocolLib (action bar) to run

### Configuration

```yaml
use boss bar: true
boss bar colour: BLUE
boss bar style: SOLID
use action bar: true
```

`use boss bar` Whether to use the boss bar for the timer, requires 1.9+

`boss bar colour` The colour for the boss bar, values can be found [here](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/boss/BarColor.html)

`boss bar style` The style of the boss bar, values can be found [here](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/boss/BarStyle.html)

`use action bar` Whether to use the action bar for the timer, requires ProtocolLib


text:
using Microsoft.Extensions.CommandLineUtils;
using System;

namespace StegoPrint {
    public class ExtractFingerprintCommand : CommandLineApplication {
        CommandOption _keyfile;
        CommandOption _input;
        public ExtractFingerprintCommand() {
            Name = "extract";
            Description = "Extracts a fingerprint from a file";

            _keyfile = Option("-$|-k |--keyfile <keyfile>", "The keyfile for the fingerprint", CommandOptionType.SingleValue);
            _input = Option("-$|-i |--input <input>", "The input audio file to process", CommandOptionType.SingleValue);

            HelpOption("-h | -? | --help");
            OnExecute((Func<int>)RunCommand);
        }

        private int RunCommand() {
            new Fingerprinter().ExtractMessage(_keyfile.Value(), _input.Value());
            return -1;
        }
    }
}


text:
    <hero></hero>
    <navbar></navbar>

    <jumbotron id="slub" name="slub" icon="fa fa-heart" jumbo-title="Ślub">

                Wirginia i Piotr mają wielką radość i ogromny zaszczyt zaprosić szanownych gości, a więc Was nasi
                najbliźsi na ślub, który odbędzie się 5.08.2017r. w Kościele św. Apostołów Piotra i Pawła przy ul. Szkolnej 2 w
                Kraszewicach o godz. 16:00. Ponieważ zdajemy sobie sprawę z tego, że dojazd do
                mniejszej miejscowości może być kłopotliwy poniżej zamieszczamy mapkę z oznaczonym miejscem ślubu i
                przyjęcia weselnego.

                    Aby dojechać do kościoła należy kierować się:

                    1. jadąc od strony Wrocławia przy wjeździe do miejscowości Kraszewice - cały czas prosto ulicą
                    początkowo grabowską, nastąnie wieluńską, a po minięciu przystanku autobusowego po prawej stronie
                    należy skręcić w prawo. Kościół powinien być widoczny już na wysokości przystanku autobusowego,

                    2. nadjeżdżając do miejscowości Kraszewice od strony przeciwnej, a więc od Wielunia należy, podobnie
                    jak w przypadku opisywanym powyżej jechać prosto ulicą wieluńską oraz po minięciu sklepu Polo Market
                    po lewej stronie przejechać jedno skrzyżowanie prosto, a na kolejnym skręcić w lewo w
                    ul. Szkolną.

        <wedding-date></wedding-date>
    </jumbotron>

    <jumbotron id="wesele" name="wesele" icon="fa fa-glass" jumbo-title="Wesele">

                Po uroczystości ślubnej wszystkich gości serdecznie zapraszamy na przyjęcie weselne do Restauracji Łużyczanka przy ul.
                Wieluńskiej 41 w Kraszewicach. W miejscu tym czeka na Was wyśmienita zabawa, dlatego polecamy zabrać ze
                sobą dobry nastrój, wygodne buty i odpowiednie imprezowe nastawienie:)

                Dnia następnego tj. 6.08.2017 r. wszystkich gości zapraszamy na poprawiny.

    </jumbotron>

    <jumbotron id="dojazd" name="dojazd" icon="fa fa-car" jumbo-title="Dojazd">

                Kierując się z Wrocławia lub ze Świdnicy do miejscowości Kraszewice dojedziecie drogą
                krajową S8 w kierunku Sycowa, z której należy zjechać przy zjeździe "Syców Zachód". Z miejscowości Syców
                następnie należy kierować się drogą nr 449 w kierunku Kobylej Góry, Ostrzeszowa,
                Grabowa nad Prosną i ostatecznie do Kraszewic.

Kierując się z Warszawy do miejsca uroczystości dojedziecie jadąc w kierunku Łodzi
                autostradą A2 (drogą nr E30), kolejno na wysokości miejscowości Stryków wjeżdżając na autostradę A1
                (droga nr E75), a następnie zjeżdżając na drogę ekspresową S8. Z drogi tej należy zjechać na wysokości
                miejscowości Jeziory oraz kierować się początkowo na Tumidaj, Bronisławów, Wiry, Ciołki, Brąszewice,
                Czajków oraz docelowo do Kraszewic.

Dojeżdżając z Zamościa należy kierować się początkowo na miejscowość Krasnystaw,
                kolejno na Świdnik, Lublin, Puławy, Radom, Tomaszów Mazowiecki, Piotrków Trybunalski. Następnie należy
                wjechać na autostradę A1 oraz zjechać na drogę ekspresową S8. Z drogi tej należy zjechać na wysokości
                miejscowości Jeziory oraz kierować się kolejno na miejscowości Tumidaj, Bronisławów, Wiry, Ciołki,
                Brąszewice, Czajków oraz docelowo do Kraszewice.

            Przewidywany czas przejazdu to:

z Wrocławia: 1 godz. 37 minut

ze Świdnicy: 2 godz. 9 minut

        <ui-gmap-google-map
                center='$ctrl.map.center'
                zoom='$ctrl.map.zoom'
                draggable="true">

            <ui-gmap-marker
                    coords="$ctrl.marker.coords"
                    options="$ctrl.marker.options"
                    events="$ctrl.marker.events"
                    idkey="$ctrl.marker.id">
            </ui-gmap-marker>
        </ui-gmap-google-map>
    </jumbotron>

    <jumbotron id="nocleg" name="nocleg" icon="fa fa-hotel"
               jumbo-title="Nocleg">

                Każdy uczestnik zabawy spoza województwa wielkopolskiego może liczyć na nocleg oferowany przez Nas.
                Dlatego też osoby przyjezdne prosimy o indywidualny kontakt z nami pod numerami telefonów podanymi w
                zaproszeniach. Każdemu udzielimy dokładnych informacji dotyczących dojazdu do miejsca noclegu. Miejsca
                zakwaterowania będą dostępne w dniu 5.08.2017 r. co najmniej od godziny 14:00.

    </jumbotron>

Mamy nadzieję, że zaszczycicie nas swoją obecnością i będziecie chcieli razem z nami dzielić
        ważne dla nas w życiu chwile.


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
using Microsoft.SSHDebugPS;
using Microsoft.SSHDebugPS.Utilities;
using Xunit;

namespace SSHDebugTests
{
    public class SSHConnectionStringTests
    {
        internal struct ConnectionStringTestItem
        {
            internal string rawConnectionString;
            internal string expectedUsername;
            internal string expectedPassword;
            internal string expectedHostname;
            internal int expectedPort;
        }

        [Fact]
        public void IPv6ConnectionStrings()
        {
            List<ConnectionStringTestItem> ipv6TestStrings = new List<ConnectionStringTestItem>();
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid
                    rawConnectionString = "testuser@[1:2:3:4:5:6:7:8]:24",
                    expectedUsername = "testuser",
                    expectedPassword = null,
                    expectedHostname = "[1:2:3:4:5:6:7:8]",
                    expectedPort = 24
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid with no port
                    rawConnectionString = "testuser@[1:2:3:4:5:6:7:8]",
                    expectedUsername = "testuser",
                    expectedPassword = null,
                    expectedHostname = "[1:2:3:4:5:6:7:8]",
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid with username:password
                    rawConnectionString = "test:user@[1234::6:7:8]",
                    expectedUsername = "test",
                    expectedPassword = "user",
                    expectedHostname = "[1234::6:7:8]",
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Valid with large port
                    rawConnectionString = "[1:2:3:4:5:6:7:8]:12345",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = "[1:2:3:4:5:6:7:8]",
                    expectedPort = 12345
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Invalid format
                    rawConnectionString = "testuser@:8",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Invalid string (just port)
                    rawConnectionString = ":8",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Empty String
                    rawConnectionString = string.Empty,
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv6TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Invalid port
                    rawConnectionString = "[1:2:3:4:5:6:7:8]:123456",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });

            foreach (var connection in ipv6TestStrings)
            {
                ParseConnectionAndValidate(connection);
            }
        }

        [Fact]
        public void Ipv4ConnectionStrings()
        {
            List<ConnectionStringTestItem> ipv4TestStrings = new List<ConnectionStringTestItem>();
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid no username
                    rawConnectionString = "192.168.1.1:156",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = "192.168.1.1",
                    expectedPort = 156
                });
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid username with port
                    rawConnectionString = "customUser@192.168.1.1:65354",
                    expectedUsername = "customUser",
                    expectedPassword = null,
                    expectedHostname = "192.168.1.1",
                    expectedPort = 65354
                });
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid no username, Large port
                    rawConnectionString = "192.168.1.1:" + (ushort.MaxValue).ToString("d", CultureInfo.InvariantCulture),
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = "192.168.1.1",
                    expectedPort = ushort.MaxValue
                });
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // valid username no port
                    rawConnectionString = "user@10.10.10.10",
                    expectedUsername = "user",
                    expectedPassword = null,
                    expectedHostname = "10.10.10.10",
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv4TestStrings.Add(
                 new ConnectionStringTestItem()
                 {
                     // valid username no port with password
                     rawConnectionString = "user:pass@10.10.10.10",
                     expectedUsername = "user",
                     expectedPassword = "pass",
                     expectedHostname = "10.10.10.10",
                     expectedPort = ConnectionManager.DefaultSSHPort
                 });
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Invalid port
                    rawConnectionString = "192.168.1.1:123456",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });
            ipv4TestStrings.Add(
                new ConnectionStringTestItem()
                {
                    // Invalid address
                    rawConnectionString = "1%92.168.1.1:23",
                    expectedUsername = StringResources.UserName_PlaceHolder,
                    expectedPassword = null,
                    expectedHostname = StringResources.HostName_PlaceHolder,
                    expectedPort = ConnectionManager.DefaultSSHPort
                });

            foreach (var connection in ipv4TestStrings)
            {
                ParseConnectionAndValidate(connection);
            }
        }

        private const string _comparisonErrorStringFormat = "{0} - Expected:'{1}' Actual:'{2}'";
        private void ParseConnectionAndValidate(ConnectionStringTestItem item)
        {
            string username;
            string hostname;
            int port;
            ConnectionManager.ParseSSHConnectionString(item.rawConnectionString, out username, out SecureString password, out hostname, out port);

            Assert.True(item.expectedUsername.Equals(username, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("UserName", item.expectedUsername, username));
            Assert.True(item.expectedHostname.Equals(hostname, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("Hostname", item.expectedHostname, hostname));
            Assert.True(item.expectedPort == port, _comparisonErrorStringFormat.FormatInvariantWithArgs("Port", item.expectedPort, port));
            if (item.expectedPassword == null)
            {
                Assert.True(password == null);
            }
            else
            {
                string passwordString = StringFromSecureString(password);
                Assert.True(item.expectedPassword.Equals(passwordString, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("Password", item.expectedPassword, passwordString));
            }
        }

        private static string StringFromSecureString(SecureString secString)
        {
            if (secString == null)
            {
                return null;
            }

            IntPtr bstr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secString);
            string value = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(bstr);
            System.Runtime.InteropServices.Marshal.FreeBSTR(bstr);
            return value;
        }
    }
}


text:
package com.hotbitmapgg.leisureread.mvp.scope;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import javax.inject.Scope;

/**
 * A scoping annotation to permit objects whose lifetime should
 * conform to the life of the activity to be memorized in the
 * correct component.
 */
@Scope
@Retention(RUNTIME)
public @interface FragmentScope {

}


text:
package enums

import enumeratum.values.{IntEnum, IntEnumEntry}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import slick.lifted.Isomorphism

class ValueEnumIsomorphismTests extends AnyFunSuite with Matchers {

  sealed abstract class IntGreeting(val value: Int) extends IntEnumEntry

  object IntGreeting extends IntEnum[IntGreeting] {
    case object Hello   extends IntGreeting(0)
    case object GoodBye extends IntGreeting(1)
    case object Hi      extends IntGreeting(2)
    case object Bye     extends IntGreeting(3)

    val values = findValues
  }

  import IntGreeting._

  test("Implicit isomorphism from ValueEnumEntry") {
    import pl.iterators.kebs.enums._

    val iso = implicitly[Isomorphism[IntGreeting, Int]]
    iso.map(Bye) shouldBe 3
    iso.comap(3) shouldBe Bye
  }

}


text:
"""Diagnostics support for ReCollect Waste."""
from __future__ import annotations

import dataclasses
from typing import Any

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

async def async_get_config_entry_diagnostics(
    hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
    """Return diagnostics for a config entry."""
    coordinator: DataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

    return {
        "entry": entry.as_dict(),
        "data": [dataclasses.asdict(event) for event in coordinator.data],
    }


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "musical_instrument".
 *
 * @property integer $id
 * @property string $title
 * @property integer $approved
 *
 * @property MusicalInstrumentBrand[] $musicalInstrumentBrands
 */
class MusicalInstrument extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'musical_instrument';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            [['approved'], 'integer'],
            [['title'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'approved' => 'Approved',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMusicalInstrumentBrands()
    {
        return $this->hasMany(MusicalInstrumentBrand::className(), ['instrument_id' => 'id']);
    }

    /**
     * Returns array of musical instruments for autocomlete
     * @return array
     */
    public static function getInstrumentsArray() {
        $result = [];
        $instruments = self::find()
            ->select(['title'])
            ->where(['approved' => 1])
            ->orderBy('title')
            ->column();
        if (!empty($instruments)) {
            $result = $instruments;
        }
        return $result;
    }

    /**
     * Register instrument
     * @param string $instrumentStr
     * @return int
     */
    public static function register($instrumentStr) {
        $instrument = self::find()->where('lower(title) = :title', [':title' => mb_strtolower($instrumentStr)])->one();
        if ($instrument) {
            return $instrument;
        }

        $instrument = new self();
        $instrument->title = $instrumentStr;
        $instrument->approved = 0;
        $instrument->save();
        return $instrument;
    }
}


text:
set -e
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
key_file="$DIR/.wmata_key"
[ -e "$key_file" ] || exit

wmata_key=$(cat $DIR/.wmata_key)
url="https://api.wmata.com/Bus.svc/json/jRouteDetails?RouteID=$1&IncludingVariations=false"
header="api_key:$wmata_key"
if [ -z "$2" ]; then
    curl $url -s -H "$header" | python -m json.tool | grep -e Name -e DirectionText
else
    curl $url -s -H "$header" | python -m json.tool | grep -e StopID -e Name -e DirectionText | sed -n "/$2/{N;p;};/DirectionText/p"
fi


text:
"""
Proxy Minion interface module for managing Palo Alto firewall devices
=====================================================================

.. versionadded:: 2018.3.0

:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity:   new
:depends:    none
:platform:   unix

This proxy minion enables Palo Alto firewalls (hereafter referred to
as simply 'panos') to be treated individually like a Salt Minion.

The panos proxy leverages the XML API functionality on the Palo Alto
firewall. The Salt proxy must have access to the Palo Alto firewall on
HTTPS (tcp/443).

More in-depth conceptual reading on Proxy Minions can be found in the
:ref:`Proxy Minion <proxy-minion>` section of Salt's
documentation.

Configuration
=============

To use this integration proxy module, please configure the following:

Pillar
------

Proxy minions get their configuration from Salt's Pillar. Every proxy must
have a stanza in Pillar and a reference in the Pillar top-file that matches
the ID. There are four connection options available for the panos proxy module.

- Direct Device (Password)
- Direct Device (API Key)
- Panorama Pass-Through (Password)
- Panorama Pass-Through (API Key)

Direct Device (Password)
------------------------

The direct device configuration configures the proxy to connect directly to
the device with username and password.

.. code-block:: yaml

    proxy:
      proxytype: panos
      host: <ip or dns name of panos host>
      username: <panos username>
      password: <panos password>
      verify_ssl: True

proxytype
^^^^^^^^^

The ``proxytype`` key and value pair is critical, as it tells Salt which
interface to load from the ``proxy`` directory in Salt's install hierarchy,
or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your
own proxy module, for example). To use this panos Proxy Module, set this to
``panos``.

host
^^^^

The location, or ip/dns, of the panos host. Required.

username
^^^^^^^^

The username used to login to the panos host. Required.

password
^^^^^^^^

The password used to login to the panos host. Required.

Direct Device (API Key)
------------------------

Palo Alto devices allow for access to the XML API with a generated 'API key'_
instead of username and password.

.. _API key: https://www.paloaltonetworks.com/documentation/71/pan-os/xml-api/get-started-with-the-pan-os-xml-api/get-your-api-key

.. code-block:: yaml

    proxy:
      proxytype: panos
      host: <ip or dns name of panos host>
      apikey: <panos generated api key>

proxytype
^^^^^^^^^

The ``proxytype`` key and value pair is critical, as it tells Salt which
interface to load from the ``proxy`` directory in Salt's install hierarchy,
or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your
own proxy module, for example). To use this panos Proxy Module, set this to
``panos``.

host
^^^^

The location, or ip/dns, of the panos host. Required.

apikey
^^^^^^

The generated XML API key for the panos host. Required.

Panorama Pass-Through (Password)
--------------------------------

The Panorama pass-through method sends all connections through the Panorama
management system. It passes the connections to the appropriate device using
the serial number of the Palo Alto firewall.

This option will reduce the number of connections that must be present for the
proxy server. It will only require a connection to the Panorama server.

The username and password will be for authentication to the Panorama server,
not the panos device.

.. code-block:: yaml

    proxy:
      proxytype: panos
      serial: <serial number of panos host>
      host: <ip or dns name of the panorama server>
      username: <panorama server username>
      password: <panorama server password>

proxytype
^^^^^^^^^

The ``proxytype`` key and value pair is critical, as it tells Salt which
interface to load from the ``proxy`` directory in Salt's install hierarchy,
or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your
own proxy module, for example). To use this panos Proxy Module, set this to
``panos``.

serial
^^^^^^

The serial number of the panos host. Required.

host
^^^^

The location, or ip/dns, of the Panorama server. Required.

username
^^^^^^^^

The username used to login to the Panorama server. Required.

password
^^^^^^^^

The password used to login to the Panorama server. Required.

Panorama Pass-Through (API Key)
-------------------------------

The Panorama server can also utilize a generated 'API key'_ for authentication.

.. _API key: https://www.paloaltonetworks.com/documentation/71/pan-os/xml-api/get-started-with-the-pan-os-xml-api/get-your-api-key

.. code-block:: yaml

    proxy:
      proxytype: panos
      serial: <serial number of panos host>
      host: <ip or dns name of the panorama server>
      apikey: <panos generated api key>

proxytype
^^^^^^^^^

The ``proxytype`` key and value pair is critical, as it tells Salt which
interface to load from the ``proxy`` directory in Salt's install hierarchy,
or from ``/srv/salt/_proxy`` on the Salt Master (if you have created your
own proxy module, for example). To use this panos Proxy Module, set this to
``panos``.

serial
^^^^^^

The serial number of the panos host. Required.

host
^^^^

The location, or ip/dns, of the Panorama server. Required.

apikey
^^^^^^^^

The generated XML API key for the Panorama server. Required.
"""

import logging
import xml.etree.ElementTree as ET

import salt.exceptions
import salt.utils.xmlutil as xml

# This must be present or the Salt loader won't load this module.
__proxyenabled__ = ["panos"]

# Variables are scoped to this module so we can have persistent data.
GRAINS_CACHE = {"vendor": "Palo Alto"}
DETAILS = {}

# Set up logging
log = logging.getLogger(__file__)

# Define the module's virtual name
__virtualname__ = "panos"

def __virtual__():
    """
    Only return if all the modules are available.
    """
    return __virtualname__

def _strip_dirty(xmltree):
    """
    Removes dirtyID tags from the candidate config result. Palo Alto devices will make the candidate configuration with
    a dirty ID after a change. This can cause unexpected results when parsing.
    """
    dirty = xmltree.attrib.pop("dirtyId", None)
    if dirty:
        xmltree.attrib.pop("admin", None)
        xmltree.attrib.pop("time", None)

    for child in xmltree:
        child = _strip_dirty(child)

    return xmltree

def init(opts):
    """
    This function gets called when the proxy starts up. For
    panos devices, a determination is made on the connection type
    and the appropriate connection details that must be cached.
    """
    if "host" not in opts["proxy"]:
        log.critical("No 'host' key found in pillar for this proxy.")
        return False
    if "apikey" not in opts["proxy"]:
        # If we do not have an apikey, we must have both a username and password
        if "username" not in opts["proxy"]:
            log.critical("No 'username' key found in pillar for this proxy.")
            return False
        if "password" not in opts["proxy"]:
            log.critical("No 'passwords' key found in pillar for this proxy.")
            return False

    DETAILS["url"] = "https://{}/api/".format(opts["proxy"]["host"])

    # Set configuration details
    DETAILS["host"] = opts["proxy"]["host"]
    DETAILS["verify_ssl"] = opts["proxy"].get("verify_ssl", True)
    if "serial" in opts["proxy"]:
        DETAILS["serial"] = opts["proxy"].get("serial")
        if "apikey" in opts["proxy"]:
            log.debug("Selected pan_key method for panos proxy module.")
            DETAILS["method"] = "pan_key"
            DETAILS["apikey"] = opts["proxy"].get("apikey")
        else:
            log.debug("Selected pan_pass method for panos proxy module.")
            DETAILS["method"] = "pan_pass"
            DETAILS["username"] = opts["proxy"].get("username")
            DETAILS["password"] = opts["proxy"].get("password")
    else:
        if "apikey" in opts["proxy"]:
            log.debug("Selected dev_key method for panos proxy module.")
            DETAILS["method"] = "dev_key"
            DETAILS["apikey"] = opts["proxy"].get("apikey")
        else:
            log.debug("Selected dev_pass method for panos proxy module.")
            DETAILS["method"] = "dev_pass"
            DETAILS["username"] = opts["proxy"].get("username")
            DETAILS["password"] = opts["proxy"].get("password")

    # Ensure connectivity to the device
    log.debug("Attempting to connect to panos proxy host.")
    query = {"type": "op", "cmd": "<show><system><info></info></system></show>"}
    call(query)
    log.debug("Successfully connected to panos proxy host.")

    DETAILS["initialized"] = True

def call(payload=None):
    """
    This function captures the query string and sends it to the Palo Alto device.
    """
    r = None
    try:
        if DETAILS["method"] == "dev_key":
            # Pass the api key without the target declaration
            conditional_payload = {"key": DETAILS["apikey"]}
            payload.update(conditional_payload)
            r = __utils__["http.query"](
                DETAILS["url"],
                data=payload,
                method="POST",
                decode_type="plain",
                decode=True,
                verify_ssl=DETAILS["verify_ssl"],
                status=True,
                raise_error=True,
            )
        elif DETAILS["method"] == "dev_pass":
            # Pass credentials without the target declaration
            r = __utils__["http.query"](
                DETAILS["url"],
                username=DETAILS["username"],
                password=DETAILS["password"],
                data=payload,
                method="POST",
                decode_type="plain",
                decode=True,
                verify_ssl=DETAILS["verify_ssl"],
                status=True,
                raise_error=True,
            )
        elif DETAILS["method"] == "pan_key":
            # Pass the api key with the target declaration
            conditional_payload = {
                "key": DETAILS["apikey"],
                "target": DETAILS["serial"],
            }
            payload.update(conditional_payload)
            r = __utils__["http.query"](
                DETAILS["url"],
                data=payload,
                method="POST",
                decode_type="plain",
                decode=True,
                verify_ssl=DETAILS["verify_ssl"],
                status=True,
                raise_error=True,
            )
        elif DETAILS["method"] == "pan_pass":
            # Pass credentials with the target declaration
            conditional_payload = {"target": DETAILS["serial"]}
            payload.update(conditional_payload)
            r = __utils__["http.query"](
                DETAILS["url"],
                username=DETAILS["username"],
                password=DETAILS["password"],
                data=payload,
                method="POST",
                decode_type="plain",
                decode=True,
                verify_ssl=DETAILS["verify_ssl"],
                status=True,
                raise_error=True,
            )
    except KeyError as err:
        raise salt.exceptions.CommandExecutionError(
            "Did not receive a valid response from host."
        )

    if not r:
        raise salt.exceptions.CommandExecutionError(
            "Did not receive a valid response from host."
        )

    if str(r["status"]) not in ["200", "201", "204"]:
        if str(r["status"]) == "400":
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request due to a client error."
            )
        elif str(r["status"]) == "401":
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request because it lacks valid"
                " authentication credentials for the target resource."
            )
        elif str(r["status"]) == "403":
            raise salt.exceptions.CommandExecutionError(
                "The server refused to authorize the request."
            )
        elif str(r["status"]) == "404":
            raise salt.exceptions.CommandExecutionError(
                "The requested resource could not be found."
            )
        else:
            raise salt.exceptions.CommandExecutionError(
                "Did not receive a valid response from host."
            )

    xmldata = ET.fromstring(r["text"])

    # If we are pulling the candidate configuration, we need to strip the dirtyId
    if payload["type"] == "config" and payload["action"] == "get":
        xmldata = _strip_dirty(xmldata)

    return xml.to_dict(xmldata, True)

def is_required_version(required_version="0.0.0"):
    """
    Because different versions of Palo Alto support different command sets, this function
    will return true if the current version of Palo Alto supports the required command.
    """
    if "sw-version" in DETAILS["grains_cache"]:
        current_version = DETAILS["grains_cache"]["sw-version"]
    else:
        # If we do not have the current sw-version cached, we cannot check version requirements.
        return False

    required_version_split = required_version.split(".")
    current_version_split = current_version.split(".")

    try:
        if int(current_version_split[0]) > int(required_version_split[0]):
            return True
        elif int(current_version_split[0]) < int(required_version_split[0]):
            return False

        if int(current_version_split[1]) > int(required_version_split[1]):
            return True
        elif int(current_version_split[1]) < int(required_version_split[1]):
            return False

        if int(current_version_split[2]) > int(required_version_split[2]):
            return True
        elif int(current_version_split[2]) < int(required_version_split[2]):
            return False

        # We have an exact match
        return True
    except Exception as err:  # pylint: disable=broad-except
        return False

def initialized():
    """
    Since grains are loaded in many different places and some of those
    places occur before the proxy can be initialized, return whether
    our init() function has been called
    """
    return DETAILS.get("initialized", False)

def grains():
    """
    Get the grains from the proxied device
    """
    if not DETAILS.get("grains_cache", {}):
        DETAILS["grains_cache"] = GRAINS_CACHE
        try:
            query = {"type": "op", "cmd": "<show><system><info></info></system></show>"}
            DETAILS["grains_cache"] = call(query)["result"]["system"]
        except Exception as err:  # pylint: disable=broad-except
            pass
    return DETAILS["grains_cache"]

def grains_refresh():
    """
    Refresh the grains from the proxied device
    """
    DETAILS["grains_cache"] = None
    return grains()

def ping():
    """
    Returns true if the device is reachable, else false.
    """
    try:
        query = {"type": "op", "cmd": "<show><system><info></info></system></show>"}
        if "result" in call(query):
            return True
        else:
            return False
    except Exception as err:  # pylint: disable=broad-except
        return False

def shutdown():
    """
    Shutdown the connection to the proxy device. For this proxy,
    shutdown is a no-op.
    """
    log.debug("Panos proxy shutdown() called.")