text:
module("Post Tests");
asyncTest("getPosts", 2,
	function()
	{
		var num = 1;
		var user = "sam";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0].owner,user,"Post owner matches");
						start();
				});
	}
);
asyncTest("getPostsEmpty", 2,
	function()
	{
		var num = 0;
		var user = "samNotExists";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0],null,"Result matches");
						start();
				});
	}
);

asyncTest("getFollowersPosts", 2,
	function()
	{
		var num = 1;
		var user = "sam";
		var owner = "chris";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user_followers",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0].owner,owner,"Post owner matches");
						start();
				});
	}
);
asyncTest("getFollowersPostsEmpty", 2,
	function()
	{
		var num = 0;
		var user = "chris";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user_followers",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0],null,"Result matches");
						start();
				});
	}
);

asyncTest("getFollowingPosts", 2,
	function()
	{
		var num = 1;
		var user = "sam";
		var owner = "james";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user_following",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0].owner,owner,"Post owner matches");
						start();
				});
	}
);
asyncTest("getFollowingPostsEmpty", 2,
	function()
	{
		var num = 0;
		var user = "james";
		getObjects(	$SCRIPT_ROOT + "posts/_query_user_following",
					user,
					function(data)
					{
						equal(data.posts.length,num,"Correct number of matches");
						equal(data.posts[0],null,"Result matches");
						start();
				});
	}
);


text:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Junshoong의 기술블로그</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
        <link rel="stylesheet" href="../../theme/css/pygment.css" />
        <link rel="stylesheet" href="../../theme/css/style.css" />
        <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

 Junshoong의 기술블로그

[Python] selenium 3 + FireFox50 사용시 발생하는 geckodriver관련 에러 해결

    2017-01-09, Mon

문제

selenium과 firefox를 사용해서 테스트를 진행하는 도중 아래와 같은 에러가 발생했다.

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://www.python.org")

assert 'Python' in browser.title

browser.quit()

$ python functional_test.py

Traceback (most recent call last):
  File "/home/harvey/venvs/dbproject/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "/usr/lib64/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib64/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "functional_test.py", line 3, in <module>
    browser = webdriver.Firefox()
  File "/home/harvey/venvs/dbproject/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 140, in __init__
    self.service.start()
  File "/home/harvey/venvs/dbproject/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 81, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x7f117dff9668>>
Traceback (most recent call last):
  File "/home/harvey/venvs/dbproject/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 173, in __del__
    self.stop()
  File "/home/harvey/venvs/dbproject/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 145, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'

로그를 살펴보면 geckodriver가 없고, 이것을 PATH에 등록해주어야 하는걸로 보인다.

geckodriver는 selenium에서 사용하는 webdriver와 firefox에서 최근에 사용하기 시작한 marionette 라는 자동화 드라이버를 연결해준다.

이를 위해 처음 설정 부분부터 정리해보자.

selenium 설치

$ virtualenv venv
$ source venv/bin/activate
$ pip install selenium

geckodriver 설치

github의 geckodriver저장소에서 파일을 받을 수 있다. #github mozilla/geckodriver

적당한 경로에 압축을 풀어주고 환경변수에 등록해준다. 내 경우에는 홈디렉터리에 builds 디렉터리를 만들고 그 안에 파일을 뒀다. 환경변수는 zsh을 사용하고 있기 때문에 /home/harvey/.zshrc파일에 경로를 추가해줬다. 참고로 파일의 경로를 직접 지정하는게 아니라 __파일이 들어있는 디렉터리의 경로__를 지정해주어야 한다.

...
export PATH=$PATH:/home/harvey/builds
...

$ source .zshrc

바로 적용하기 위해서 파일을 실행해준다. 이후에는 shell을 키면 바로 적용된다.

코드 실행

selenium_test.py

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://www.python.org")

assert 'Python' in browser.title

browser.quit()

코드는 맨위와 같다.

이제 다시 실행하면 문제없이 실행된다. 혹은 시스템 환경변수를 추가하지 않고 코드내에서 명시적으로 경로를 지정할 수도 있다.

from selenium import webdriver

# browser = webdriver.Firefox()
browser = webdriver.Firefox(excutable_path='/home/harvey/builds/geckodriver')
browser.get("http://www.python.org")

assert 'Python' in browser.title

browser.quit()

참고자료

Python - Selenium in Ubuntu OSError: (Errno 20) Not a directory - Stack Overflow

WebDriver - Mozilla

 Category

            Agile
            (2)

            Angular
            (1)

            Blog
            (3)

            Book
            (3)

            CSS
            (1)

            CTF
            (4)

            DevOps
            (2)

            Django
            (6)

            Docker
            (2)

            Editor
            (3)

            English
            (2)

            ETC
            (11)

            Game
            (2)

            Git
            (2)

            Life
            (22)

            Linux
            (19)

            Mac
            (1)

            Movie
            (1)

            Nginx
            (2)

            Pelican
            (1)

            Python
            (8)

            Regex
            (1)

            Shell
            (2)

 Social

         email
         facebook
         linkedin
         slideshare
         github
         stack-overflow
         FEED

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Phebalium hexapetalum A.Juss.

### Remarks
null


text:
package eu.mosaic_cloud.platform.v2.connectors.core;

/**
 * Interface for custom connector factory. For each connector type an implementation of this interface should be implemented.
 *
 * @author Ciprian Craciun
 * @param <TConnector>
 *            the type of the connector created by this factory
 */
public interface ConnectorFactory<TConnector extends Connector>
{}


text:
#ifndef __ASM_SH_CACHEFLUSH_H
#define __ASM_SH_CACHEFLUSH_H
#ifdef __KERNEL__

#include <asm/cpu/cacheflush.h>

/* Flush (write-back only) a region (smaller than a page) */
extern void __flush_wback_region(void *start, int size);
/* Flush (write-back & invalidate) a region (smaller than a page) */
extern void __flush_purge_region(void *start, int size);
/* Flush (invalidate only) a region (smaller than a page) */
extern void __flush_invalidate_region(void *start, int size);

#define flush_cache_vmap(start, end)		flush_cache_all()
#define flush_cache_vunmap(start, end)		flush_cache_all()

#define copy_to_user_page(vma, page, vaddr, dst, src, len) \
	do {							\
		flush_cache_page(vma, vaddr, page_to_pfn(page));\
		memcpy(dst, src, len);				\
		flush_icache_user_range(vma, page, vaddr, len);	\
	} while (0)

#define copy_from_user_page(vma, page, vaddr, dst, src, len) \
	do {							\
		flush_cache_page(vma, vaddr, page_to_pfn(page));\
		memcpy(dst, src, len);				\
	} while (0)

#endif /* __KERNEL__ */
#endif /* __ASM_SH_CACHEFLUSH_H */


text:
package file

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/caixw/lib.go/assert"
	sess "github.com/caixw/lib.go/session"
)

func hello(a *assert.Assertion, w http.ResponseWriter) {
	n, err := w.Write([]byte("hello world"))
	a.NotError(err)
	a.NotEmpty(n)
}

func freeSession(a *assert.Assertion, inst *sess.Instance, w http.ResponseWriter, r *http.Request) {
	err := inst.EndSession(w, r)
	a.NotError(err)
}

// 测试freeSession之后,值是否被清空
func freeSession2(a *assert.Assertion, inst *sess.Instance, w http.ResponseWriter, r *http.Request) {
	sess, err := inst.StartSession(w, r)
	a.NotError(err)
	a.NotNil(sess)
	defer func() {
		a.NotError(sess.Release())
	}()

	uid, found := sess.Get("uid")
	a.False(found)
	a.Equal(uid, nil)
}

func testSession(a *assert.Assertion, inst *sess.Instance, w http.ResponseWriter, r *http.Request) {
	// 获取session接口实例
	sess, err := inst.StartSession(w, r)
	a.NotError(err)
	a.NotNil(sess)
	defer func() {
		a.NotError(sess.Release())
	}()

	// 设置值
	sess.Set("uid", 1)
	uid, found := sess.Get("uid")
	a.True(found)
	a.Equal(uid, 1)

	// 不存在的值
	username := sess.MustGet("username", "abc")
	a.Equal(username, "abc")

	// 添加值
	sess.Set("username", "caixw")
	username = sess.MustGet("username", "abc")
	a.Equal(username, "caixw")

	// 修改值
	sess.Set("uid", "2")
	uid, found = sess.Get("uid")
	a.True(found)
	a.Equal(uid, "2")
}

// 测试cookie能否正常使用
func testSession2(a *assert.Assertion, inst *sess.Instance, w http.ResponseWriter, r *http.Request) {
	sess, err := inst.StartSession(w, r)
	a.NotError(err)
	a.NotNil(sess)
	defer func() {
		a.NotError(sess.Release())
	}()

	uid, found := sess.Get("uid")
	a.True(found)
	a.Equal(uid, "2")
}

func TestFile(t *testing.T) {
	a := assert.New(t)
	inst := sess.New(New("./testdata"), "gosid", 3600, false)
	a.NotNil(inst)

	// 构建服务端
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm()
		a.NotError(err)
		if action, found := r.Form["action"]; found {
			switch action[0] {
			case "testSession":
				testSession(a, inst, w, r)
			case "freeSession2":
				freeSession2(a, inst, w, r)
			case "freeSession":
				freeSession(a, inst, w, r)
			case "testSession2":
				testSession2(a, inst, w, r)
			}
			return
		}

		// 没有action参数的情况下,输出普通内容。
		hello(a, w)
	}))
	defer ts.Close()

	// 普通客户端请求
	response, err := http.Get(ts.URL)
	a.NotError(err)
	a.NotNil(response)
	txt, err := ioutil.ReadAll(response.Body)
	a.NotError(err)
	a.NotEmpty(txt)
	a.T().Log(string(txt))

	// testSession
	response, err = http.Get(ts.URL + "?action=testSession")
	a.NotError(err)
	a.NotNil(response)

	// 提交cookie,测试是否可以还原数据
	req, err := http.NewRequest("GET", ts.URL+"?action=testSession2", nil)
	a.NotError(err)
	a.NotNil(req)
	req.Header.Add("Cookie", response.Header.Get("Set-Cookie")) // 模拟浏览器提交cookie
	client := &http.Client{}
	response, err = client.Do(req)
	a.NotError(err)
	a.NotNil(response)

	// freeSession
	req, err = http.NewRequest("GET", ts.URL+"?action=freeSession", nil)
	a.NotError(err)
	a.NotNil(req)
	req.Header.Add("Cookie", response.Header.Get("Set-Cookie")) // 模拟浏览器提交cookie
	client = &http.Client{}
	response, err = client.Do(req)
	a.NotError(err)
	a.NotNil(response)

	// freeSession2 测试FreeSession之后,是否正常
	response, err = http.Get(ts.URL + "?action=freeSession2")
	a.NotError(err)
	a.NotNil(response)
}


text:
Connector::Connector() {}

Connector::Connector(Component* left, Component* right)
{
    this->leftChild = left;
    this->rightChild = right;
}


text:
<include file="Public/header" />

                      登陆旅之沙
                      注册账号

                      注册旅之沙
                      登陆

                  <form class="form-horizontal login-form hidden" method="post" action="{:U('Web/Login/login')}">

                      email

                        <input type="text" class="form-control" id="email" name="email" placeholder="email">

                      密码

                        <input type="password" class="form-control" name="password" id="iPassword" placeholder="密码">

                                    <input type="checkbox"> 记住密码

                                    找回密码

							<button type="submit" class="btn btn-danger" style="width: 50%">登陆</button>

                  </form>

                    <form class="form-horizontal register-form " method="post" action="{:U('Web/Login/register')}">

                            用户名

                                <input type="text" class="form-control" id="username" name="username" placeholder="用户名不能少于5位">

                            邮箱

                                <input type="text" class="form-control" id="inputEmail" name="email" placeholder="邮箱">

                            密码

                                <input type="password" class="form-control"  name="password" id="inputPassword" placeholder="密码至少为5位数字加字母或者下划线">

                            <button type="submit" class="btn btn-danger" style="width:80%">注册</button>

                    </form>

<include file="Public/foot-bottom" />


text:
from setuptools import setup, find_packages
import flameprof

setup(
    name='flameprof',
    version=flameprof.version,
    url='https://github.com/baverman/flameprof/',
    license='MIT',
    author='Anton Bobrov',
    author_email='baverman@gmail.com',
    description='cProfile flamegraph generator',
    long_description=open('README.rst').read(),
    py_modules=['flameprof'],
    scripts=['bin/flameprof'],
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    classifiers=[
        'Development Status :: 4 - Beta',
        # 'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Operating System :: MacOS',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Internet',
        'Topic :: Scientific/Engineering',
        'Topic :: System :: Distributed Computing',
        'Topic :: System :: Systems Administration',
        'Topic :: System :: Monitoring',
    ]
)


text:
if (!Control) var Control = { };

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider = Class.create({
  initialize: function(handle, track, options) {
    var slider = this;

    if (Object.isArray(handle)) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }

    this.track   = $(track);
    this.options = options || { };

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);

    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');

    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ?
      (this.handles[0].offsetHeight != 0 ?
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if (this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if (this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (Object.isArray(slider.options.sliderValue) ?
          slider.options.sliderValue[i] : slider.options.sliderValue) ||
         slider.range.start), i);
      h.makePositioned().observe("mousedown", slider.eventMouseDown);
    });

    this.track.observe("mousedown", this.eventMouseDown);
    document.observe("mouseup", this.eventMouseUp);
    document.observe("mousemove", this.eventMouseMove);

    this.initialized = true;
  },
  dispose: function() {
    var slider = this;
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },
  getNearestValue: function(value){
    if (this.allowedValues){
      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
      if (value <= this.allowedValues.min()) return(this.allowedValues.min());

      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if (currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        }
      });
      return newValue;
    }
    if (value > this.range.end) return this.range.end;
    if (value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if (!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if (this.initialized && this.restricted) {
      if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat

    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
      this.translateToPx(sliderValue);

    this.drawSpans();
    if (!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) *
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K);
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ?
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY :
      (this.track.offsetWidth != 0 ? this.track.offsetWidth :
        this.track.style.width.replace(/px$/,"")) - this.alignX);
  },
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if (this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if (this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if (this.options.endSpan)
      this.setSpan(this.options.endSpan,
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if (this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if (Event.isLeftClick(event)) {
      if (!this.disabled){
        this.active = true;

        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if (track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track);
          this.event = event;
          this.setValue(this.translateToValue(
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode)
            handle = handle.parentNode;

          if (this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();

            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if (this.active) {
      if (!this.dragging) this.dragging = true;
      this.draw(event);
      if (Prototype.Browser.WebKit) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if (this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if (this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if (this.initialized && this.options.onChange)
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
});


text:
#ifndef GROUP_H
#define GROUP_H

#include "IXMLFlattenable.h"

#include <be/support/String.h>

class Group : public IXMLFlattenable
{
	public:
		Group();
		Group(BString name, BString groupID);
		virtual				~Group();

		//inherited from IXMLFlattenable
		BString				XMLFlatten();
		void				XMLUnflatten(xmlDocPtr xmlDocument);

		void				SetGroupName(BString name);
		BString				GroupName();

		void				SetGroupID(BString id);
		BString				GroupID();

	private:
		BString				m_groupName,
							m_groupID;
};

#endif


text:
Cephei is a framework for jailbroken iOS devices that includes various convenience features for developers. Primarily, it focuses on settings-related features, but it also contains other utilties. I hope you'll appreciate what it has to offer.

All iOS versions since 5.0 are supported, on all devices.

Documentation is available at **[hbang.github.io/libcephei](https://hbang.github.io/libcephei/)**.

## Integrating Cephei into a Theos project
If you need to install Cephei, visit [chariz.com/get/cephei](https://chariz.com/get/cephei) on your device and tap the Install button.

Theos includes headers and linkable frameworks for Cephei, so you don't need to worry about copying files over from your device. You can also find these as zipped-up SDKs on the [GitHub releases](https://github.com/hbang/libcephei/releases) page.

For all projects that will be using Cephei, add it to the instance's frameworks list:

```makefile
MyAwesomeTweak_EXTRA_FRAMEWORKS += Cephei
```

If you are using CepheiUI or CepheiPrefs components (refer to the sidebar of the [documentation](https://hbang.github.io/libcephei/)), make sure to also add those names to the frameworks list.

You can now use Cephei components in your project.

You must also add `ws.hbang.common` to the `Depends:` list in your control file. If Cephei isn't present on the device, your binaries will fail to load. For example:

```yaml
Depends: mobilesubstrate, something-else, some-other-package, ws.hbang.common (>= 1.17)
```

You should specify the current version of Cephei as the minimum requirement, so you can guarantee all features you use are available.

## Trying it out
You can take a look at a demo of CepheiPrefs by copying `/Library/PreferenceBundles/Cephei.bundle/entry.plist` to `/Library/PreferenceLoader/Preferences/Cephei.plist` – quit and relaunch Settings if it's open. Alternatively, you can compile Cephei yourself – when compiling a debug build, the Cephei Demo preference bundle will be visible by default.

## License
Licensed under the Apache License, version 2.0. Refer to [LICENSE.md](https://github.com/hbang/libcephei/blob/main/LICENSE.md).

Header backdrop photo credit: [Kristopher Roller](https://unsplash.com/@krisroller) on Unsplash


text:
name: Bug report
about: Report a bug in OSMnx's code
title: ''
labels: bug
assignees: ''

---

**Read these instructions carefully. Use the template below and fill out every section. Your issue will be automatically closed if you don't provide all of the information requested in the template, because we need this information to assist you. Before you proceed, review the contributing guidelines in the CONTRIBUTING.md file.**

Please don't use the issue tracker to ask "how-to" or usage questions. If asked here, they will be closed automatically. Instead, ask "how-to" and usage questions on [StackOverflow](https://stackoverflow.com/search?q=osmnx). If you installed OSMnx via conda and are experiencing installation problems, please open an issue at its [feedstock](https://github.com/conda-forge/osmnx-feedstock/issues) instead.

Bug reports are for reporting a bug you have found in OSMnx's codebase. First search the open/closed issues and StackOverflow to see if the problem has already been noted. If it hasn't, fill in the bug reporting template below.

**Do not delete the following template. Fill it out completely.**

  - [ ] I have read the OSMnx [contributing guidelines](../blob/main/CONTRIBUTING.md)
  - [ ] I have read the OSMnx [documentation](https://osmnx.readthedocs.io/) and [usage examples](https://github.com/gboeing/osmnx-examples)
  - [ ] I have searched the open/closed issues and [StackOverflow](https://stackoverflow.com/search?q=osmnx) for problems similar to mine

**Problem description**
  - What did you do?
  - What did you expect to happen?
  - And what actually happened instead?

**Environment information**
  - What operating system are you using?
  - What Python version are you using?
  - What OSMnx version are you using?
  - Provide a complete list of your environment's packages and their versions (for example, run `conda list` or `pip list` then paste the output between the two "details" tags below)

<details>
# paste the output of your Python packages/versions here between these two "details" tags

</details>

**Provide a complete minimal reproducible example**

Your example code snippet here must be *minimal* so it doesn't contain extraneous code or data unrelated to your specific problem and it must be *complete* so we can independently run it from top to bottom by copying/pasting it into a Python interpreter. That means all imports and all variables must be defined. If you're unsure how to create a good reproducible example, read [this guide](https://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports). Do not post a screenshot of your code or error message: provide it as text.

```python
# your code goes here

```


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="cn.addapp.androidpicker">

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:name="cn.addapp.androidpickers.PickerApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning,NewApi">
        <activity android:name="cn.addapp.androidpickers.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="cn.addapp.androidpickers.NextActivity"/>
    </application>

</manifest>


text:
#ifndef PHYSXSHAPE_H
#define PHYSXSHAPE_H

#include "pandabase.h"
#include "pointerTo.h"
#include "luse.h"

#include "physxObject.h"
#include "physxEnums.h"
#include "physx_includes.h"

class PhysxActor;
class PhysxMaterial;
class PhysxGroupsMask;
class PhysxBounds3;
class PhysxSphere;
class PhysxBox;
class PhysxCapsule;
class PhysxRay;
class PhysxRaycastHit;
class PhysxCcdSkeleton;

/**
 * Abstract base class for shapes.
 */
class EXPCL_PANDAPHYSX PhysxShape : public PhysxObject, public PhysxEnums {

PUBLISHED:
  void release();

  PhysxActor *get_actor() const;

  void set_name(const char *name);
  void set_flag(const PhysxShapeFlag flag, bool value);
  void set_skin_width(float skinWidth);
  void set_group(unsigned short group);
  void set_local_pos(const LPoint3f &pos);
  void set_local_mat(const LMatrix4f &mat);
  void set_material(const PhysxMaterial &material);
  void set_material_index(unsigned short idx);
  void set_groups_mask(const PhysxGroupsMask &mask);
  void set_ccd_skeleton(PhysxCcdSkeleton *skel);

  const char *get_name() const;
  bool get_flag(const PhysxShapeFlag flag) const;
  float get_skin_width() const;
  unsigned short get_group() const;
  LPoint3f get_local_pos() const;
  LMatrix4f get_local_mat() const;
  unsigned short get_material_index() const;
  PhysxGroupsMask get_groups_mask() const;
  PhysxBounds3 get_world_bounds() const;
  PhysxCcdSkeleton *get_ccd_skeleton() const;

  bool check_overlap_aabb(const PhysxBounds3 &world_bounds) const;
  bool check_overlap_capsule(const PhysxCapsule &world_capsule) const;
  bool check_overlap_obb(const PhysxBox &world_box) const;
  bool check_overlap_sphere(const PhysxSphere &world_sphere) const;
  PhysxRaycastHit raycast(const PhysxRay &worldRay, bool firstHit, bool smoothNormal) const;

  INLINE void ls() const;
  INLINE void ls(std::ostream &out, int indent_level=0) const;

public:
  static PhysxShape *factory(NxShapeType shapeType);

  virtual NxShape *ptr() const = 0;

  virtual void link(NxShape *shapePtr) = 0;
  virtual void unlink() = 0;

protected:
  INLINE PhysxShape();

private:
  std::string _name;
  PT(PhysxCcdSkeleton) _skel;

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    PhysxObject::init_type();
    register_type(_type_handle, "PhysxShape",
                  PhysxObject::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {
    init_type();
    return get_class_type();
  }

private:
  static TypeHandle _type_handle;
};

#include "physxShape.I"

#endif // PHYSXSHAPE_H


text:
import { logger } from '../lib/logger';
import { getFederatedRoomData, hasExternalDomain, isLocalUser, checkRoomType, checkRoomDomainsLength } from '../functions/helpers';
import { FederationRoomEvents, Subscriptions } from '../../../models/server';
import { normalizers } from '../normalizers';
import { doAfterCreateRoom } from './afterCreateRoom';
import { getFederationDomain } from '../lib/getFederationDomain';
import { dispatchEvent } from '../handler';

async function afterAddedToRoom(involvedUsers, room) {
	const { user: addedUser } = involvedUsers;

	const localDomain = getFederationDomain();

	if (!hasExternalDomain(room) && isLocalUser(addedUser, localDomain)) {
		return involvedUsers;
	}

	logger.client.debug(() => `afterAddedToRoom => involvedUsers=${ JSON.stringify(involvedUsers, null, 2) } room=${ JSON.stringify(room, null, 2) }`);

	// If there are not federated users on this room, ignore it
	const { users, subscriptions } = getFederatedRoomData(room);

	// Load the subscription
	const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, addedUser._id);

	try {
		// If the room is not on the allowed types, ignore
		if (!checkRoomType(room)) {
			throw new Error('Channels cannot be federated');
		}

		//
		// Check if the room is already federated, if it is not, create the genesis event
		//
		if (!room.federation) {
			//
			// Create the room with everything
			//

			await doAfterCreateRoom(room, users, subscriptions);
		} else {
			//
			// Normalize the room's federation status
			//

			// Get the users domains
			const domainsAfterAdd = users.map((u) => u.federation.origin);

			// Check if the number of domains is allowed
			if (!checkRoomDomainsLength(room.federation.domains)) {
				throw new Error('Cannot federate rooms with more than 10 domains');
			}

			//
			// Create the user add event
			//

			const normalizedSourceUser = normalizers.normalizeUser(addedUser);
			const normalizedSourceSubscription = normalizers.normalizeSubscription(subscription);

			const addUserEvent = await FederationRoomEvents.createAddUserEvent(localDomain, room._id, normalizedSourceUser, normalizedSourceSubscription, domainsAfterAdd);

			// Dispatch the events
			dispatchEvent(domainsAfterAdd, addUserEvent);
		}
	} catch (err) {
		// Remove the user subscription from the room
		Subscriptions.remove({ _id: subscription._id });

		logger.client.error('afterAddedToRoom => Could not add user:', err);
	}

	return involvedUsers;
}

export const definition = {
	hook: 'afterAddedToRoom',
	callback: (roomOwner, room) => Promise.await(afterAddedToRoom(roomOwner, room)),
	id: 'federation-after-added-to-room',
};


text:
<?php

namespace Cache\Driver;

use Cache\Driver;

class Memcached extends Driver {

  // store for the memache connection
  protected $connection = null;

  /**
   * Set all parameters which are needed for the memcache client
   * see defaults for available parameters
   *
   * @param array $params
   */
  public function __construct($params = array()) {

    $defaults = array(
      'host'    => 'localhost',
      'port'    => 11211,
      'prefix'  => null,
    );

    $this->options    = array_merge($defaults, (array)$params);
    $this->connection = new \Memcached();
    $this->connection->addServer($this->options['host'], $this->options['port']);

  }

  /**
   * Write an item to the cache for a given number of minutes.
   *
   * <code>
   *    // Put an item in the cache for 15 minutes
   *    Cache::set('value', 'my value', 15);
   * </code>
   *
   * @param  string  $key
   * @param  mixed   $value
   * @param  int     $minutes
   * @return void
   */
  public function set($key, $value, $minutes = null) {
    return $this->connection->set($this->key($key), $this->value($value, $minutes), $this->expiration($minutes));
  }

  /**
   * Returns the full keyname
   * including the prefix (if set)
   *
   * @param string $key
   * @return string
   */
  public function key($key) {
    return $this->options['prefix'] . $key;
  }

  /**
   * Retrieve the CacheValue object from the cache.
   *
   * @param  string  $key
   * @return object CacheValue
   */
  public function retrieve($key) {
    return $this->connection->get($this->key($key));
  }

  /**
   * Remove an item from the cache
   *
   * @param string $key
   * @return boolean
   */
  public function remove($key) {
    return $this->connection->delete($this->key($key));
  }

  /**
   * Checks when an item in the cache expires
   *
   * @param string $key
   * @return int
   */
  public function expires($key) {
    return parent::expires($this->key($key));
  }

  /**
   * Checks if an item in the cache is expired
   *
   * @param string $key
   * @return int
   */
  public function expired($key) {
    return parent::expired($this->key($key));
  }

  /**
   * Checks when the cache has been created
   *
   * @param string $key
   * @return int
   */
  public function created($key) {
    return parent::created($this->key($key));
  }

  /**
   * Flush the entire cache directory
   *
   * @return boolean
   */
  public function flush() {
    return $this->connection->flush();
  }

}


text:
A sample of build nginx and php(with phalcon extension) containers with Dockerfile

### usage
- clone the repo

```bash
git clone git://github.com/voids/docker-sample
cd docker-sample
```
- clone phalcon source code

```bash
git clone git://github.com/phalcon/cphalcon.git
```

- build image and copy configs

```bash
./build.sh
```

- generate containers

```bash
./init.sh
```


text:
import os
import sys
import arcpy

import Base

class UserCode:
    def sample00(self, data):

        base = Base.Base()          # using Base class for its XML specific common functions. (getXMLXPathValue, getXMLNodeValue, getXMLNode)
        xmlDOM = data['mdcs']       # access to MDCS config file
        command_used = base.getXMLNodeValue(xmlDOM, 'Command')

        workspace = data['workspace']
        md = data['mosaicdataset']

        log = data['log']
        log.Message('%s\\%s' % (workspace, md), 0)

        return True

    def sample01(self, data):

        log = data['log']
        log.Message('hello world', 0)

        return True

    def customCV(self, data):

        workspace = data['workspace']
        md = data['mosaicdataset']

        ds = os.path.join(workspace, md)
        ds_cursor = arcpy.UpdateCursor(ds)
        if (ds_cursor != None):
            print ('Calculating values..')
            row = ds_cursor.next()
            while(row != None):
                row.setValue('MinPS', 0)
                row.setValue('MaxPS', 300)

                WRS_Path = row.getValue('WRS_Path')
                WRS_Row = row.getValue('WRS_Row')

                if (WRS_Path != None and
                    WRS_Row != None):
                    PR = (WRS_Path*1000)+WRS_Row
                    row.setValue('PR', PR)

                AcquisitionData = row.getValue('AcquisitionDate')
                if (AcquisitionData != None):
                    AcquisitionData = str(AcquisitionData).replace('-', '/')
                    day = int(AcquisitionData.split()[0].split('/')[1])
                    row.setValue('Month', day)

                grp_name = row.getValue('GroupName')
                if (grp_name != None):
                    CMAX_INDEX = 16
                    if (len(grp_name) >= CMAX_INDEX):
                        row.setValue('DayOfYear', int(grp_name[13:CMAX_INDEX]))
                        row.setValue('Name', grp_name.split('_')[0] + '_' + row.getValue('Tag'))

                ds_cursor.updateRow(row)
                row = ds_cursor.next()

            del ds_cursor

        return True


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>OpenNI 1.5.7: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

OpenNI 1.5.7

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

XnCallback Member List

This is the complete list of members for XnCallback, including all inherited members.

pCookie	XnCallback

pFuncPtr	XnCallback

Set(XnFuncPtr pFuncPtr, void *pCookie)	XnCallback	inline

XnCallback()	XnCallback	inline

XnCallback(XnFuncPtr pFuncPtr, void *pCookie)	XnCallback	inline

<address class="footer">
Generated on Tue Nov 12 2013 13:40:21 for OpenNI 1.5.7 by

 1.8.3.1
</address>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N688.html">

Redirecting to type.N688.html...


text:
package ru.albatros.metropolis;

public class Station
{
	private int x, y, anchorX, anchorY;

	public Station(int x, int y, int anchorX, int anchorY)
	{
		this.x = x;
		this.y = y;
		this.anchorX = anchorX;
		this.anchorY = anchorY;
	}

	public int getX()
	{
		return x;
	}

	public int getY()
	{
		return y;
	}

	public int getAnchorX(){
		return anchorX;
	}

	public int getAnchorY(){
		return anchorY;
	}
	}


text:
require 'spec_helper'
require 'puppet/pops'

describe Puppet::Pops::Parser::Parser do
  it "should instantiate a parser" do
    parser = Puppet::Pops::Parser::Parser.new()
    parser.class.should == Puppet::Pops::Parser::Parser
  end

  it "should parse a code string and return a model" do
    parser = Puppet::Pops::Parser::Parser.new()
    model = parser.parse_string("$a = 10").current
    model.class.should == Puppet::Pops::Model::Program
    model.body.class.should == Puppet::Pops::Model::AssignmentExpression
  end

  it "should accept empty input and return a model" do
    parser = Puppet::Pops::Parser::Parser.new()
    model = parser.parse_string("").current
    model.class.should == Puppet::Pops::Model::Program
    model.body.class.should == Puppet::Pops::Model::Nop
  end

  it "should accept empty input containing only comments and report location at end of input" do
    parser = Puppet::Pops::Parser::Parser.new()
    model = parser.parse_string("# comment\n").current
    model.class.should == Puppet::Pops::Model::Program
    model.body.class.should == Puppet::Pops::Model::Nop
    adapter = Puppet::Pops::Adapters::SourcePosAdapter.adapt(model.body)
    expect(adapter.offset).to eq(10)
    expect(adapter.length).to eq(0)
  end

  it "should raise an error with position information when error is raised from within parser" do
    parser = Puppet::Pops::Parser::Parser.new()
    the_error = nil
    begin
      parser.parse_string("File [1] { }", 'fakefile.pp')
    rescue Puppet::ParseError => e
      the_error = e
    end
    expect(the_error).to be_a(Puppet::ParseError)
    expect(the_error.file).to eq('fakefile.pp')
    expect(the_error.line).to eq(1)
    expect(the_error.pos).to eq(6)
  end
end


text:
package com.oyster.DBandContentProviderEx.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.parse.ParseUser;

/**
 * @author bamboo
 * @since 3/30/14 12:57 PM
 */
public class DispatchActivity extends Activity {

    public DispatchActivity() {
    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (ParseUser.getCurrentUser() != null) {
            Intent i = new Intent(DispatchActivity.this, TodoMainActivity.class);
            startActivity(i);
        } else {
            Intent i = new Intent(DispatchActivity.this, LogInOrSignUpActivity.class);
            startActivity(i);
        }

    }
}


text:
'use strict';

// MODULES //

var constantFunction = require( '@stdlib/utils/constant-function' );
var degenerate = require( '@stdlib/stats/base/dists/degenerate/logpdf' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var cospi = require( '@stdlib/math/base/special/cospi' );
var ln = require( '@stdlib/math/base/special/ln' );
var NINF = require( '@stdlib/constants/float64/ninf' );

// MAIN //

/**
* Returns a function for evaluating the logarithm of the probability density function (PDF) for a raised cosine distribution.
*
* @param {number} mu - location parameter
* @param {NonNegativeNumber} s - scale parameter
* @returns {Function} logPDF
*
* @example
* var logpdf = factory( 10.0, 2.0 );
* var y = logpdf( 10.0 );
* // returns ~-0.693
*
* y = logpdf( 9.0 );
* // returns ~-1.386
*/
function factory( mu, s ) {
	if ( isnan( mu ) || isnan( s ) || s < 0.0 ) {
		return constantFunction( NaN );
	}
	if ( s === 0.0 ) {
		return degenerate( mu );
	}
	return logpdf;

	/**
	* Evaluates the logarithm of the probability density function (PDF) for a raised cosine distribution.
	*
	* @private
	* @param {number} x - input value
	* @returns {number} evaluated logPDF
	*
	* @example
	* var y = logpdf( -1.2 );
	* // returns <number>
	*/
	function logpdf( x ) {
		var z;
		if ( isnan( x ) ) {
			return NaN;
		}
		if (
			x < mu - s ||
			x > mu + s
		) {
			return NINF;
		}
		z = ( x - mu ) / s;
		return ln( 1.0 + cospi( z ) ) - ln( 2.0 * s );
	}
}

// EXPORTS //

module.exports = factory;


text:
package com.example.android.qcircleview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.IOException;

public class DialerAppActivity extends Activity implements View.OnClickListener {
    /**
     * Called when the activity is first created.
     */
    ImageButton dialBtn;
    EditText numTxt;
    Button one, two, three, four, five, six, seven, eight, nine, zero, dieze, mul;
    public static boolean dial, dialstate = false;
    public static Activity dial1;

    @Override
    protected void onDestroy() {
        dial = false;
        super.onDestroy();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        dial = true;
        dial1 = this;
        SlidingTabsBasicFragment.state3=false;
        Menu.menu1.finish();
        setContentView(R.layout.dialer);
        ImageButton retour8 = (ImageButton) findViewById(R.id.retour8);
        retour8.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        dialBtn = (ImageButton) findViewById(R.id.call);
        numTxt = (EditText) findViewById(R.id.editText1);
        ImageButton supp1 = (ImageButton) findViewById(R.id.supp);
        supp1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                numTxt.setText("");
            }
        });
        one = (Button) findViewById(R.id.one1);
        two = (Button) findViewById(R.id.two1);
        three = (Button) findViewById(R.id.three1);
        four = (Button) findViewById(R.id.four1);
        five = (Button) findViewById(R.id.five1);
        six = (Button) findViewById(R.id.six1);
        seven = (Button) findViewById(R.id.seven1);
        eight = (Button) findViewById(R.id.eight1);
        nine = (Button) findViewById(R.id.nine1);
        zero = (Button) findViewById(R.id.zero1);
        dieze = (Button) findViewById(R.id.dieze1);
        mul = (Button) findViewById(R.id.mul1);

        try {
            one.setOnClickListener(this);

            two.setOnClickListener(this);

            three.setOnClickListener(this);

            four.setOnClickListener(this);

            five.setOnClickListener(this);

            six.setOnClickListener(this);

            seven.setOnClickListener(this);

            eight.setOnClickListener(this);

            nine.setOnClickListener(this);

            zero.setOnClickListener(this);

            dieze.setOnClickListener(this);

            mul.setOnClickListener(this);

        } catch (Exception e) {

        }
        zero.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Editable str = numTxt.getText();
                str = str.append("+");
                numTxt.setText(str);
                return true;
            }
        });
        dialBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    if (numTxt != null && numTxt.getText().length() == 0) {
                        Toast.makeText(getApplicationContext(), "You missed to type the number!", Toast.LENGTH_SHORT).show();
                        numTxt.setText("");
                    }/*else if (numTxt != null && numTxt.getText().length() < 10) {
                        Toast.makeText(getApplicationContext(), "Check whether you entered correct number!", Toast.LENGTH_SHORT).show();
                    }*/ else {
                        if (numTxt != null) {
                            dial = false;
                            //MainActivity.mainactivity1.finish();
                            startActivity(new Intent(Intent.ACTION_CALL, Uri
                                    .parse("tel:" + numTxt.getText())));

                            CallHelper.phone_state = true;
                            /*try {
                                Process su = Runtime.getRuntime().exec("su");
                                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

                                outputStream.writeBytes("input keyevent 26\n");
                                outputStream.flush();

                                outputStream.writeBytes("exit\n");
                                outputStream.flush();
                                su.waitFor();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }*/
                            finish();
                            Contact.contact1.finish();
                            try {
                                Thread.sleep(2500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Intent startIntent = new Intent(DialerAppActivity.this, MainActivity.class);
                            startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(startIntent);
                            if (SlidingTabsBasicFragment.myThread == null) {
                                SlidingTabsBasicFragment.myThread = new Thread(SlidingTabsBasicFragment.runnable);
                                SlidingTabsBasicFragment.myThread.start();
                            }
                            SlidingTabsBasicFragment.mViewPager.setCurrentItem(NotificationListener.call_pos);
                            CallHelper.phone_state=false;
                            try {
                                Process su = Runtime.getRuntime().exec("su");
                                DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

                                outputStream.writeBytes("input keyevent 26\n");
                                outputStream.flush();

                                outputStream.writeBytes("exit\n");
                                outputStream.flush();
                                su.waitFor();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("DialerAppActivity", "error: " + e.getMessage(),
                            e);
                }
            }
        });
    }

    @Override
    public void onClick(View arg0) {
        Editable str = numTxt.getText();
        switch (arg0.getId()) {
            case R.id.one1:
                str = str.append("1");
                numTxt.setText(str);
                break;
            case R.id.two1:
                str = str.append("2");
                numTxt.setText(str);
                break;
            case R.id.three1:
                str = str.append("3");
                numTxt.setText(str);
                break;
            case R.id.four1:
                str = str.append("4");
                numTxt.setText(str);
                break;
            case R.id.five1:
                str = str.append("5");
                numTxt.setText(str);
                break;
            case R.id.six1:
                str = str.append("6");
                numTxt.setText(str);
                break;
            case R.id.seven1:
                str = str.append("7");
                numTxt.setText(str);
                break;
            case R.id.eight1:
                str = str.append("8");
                numTxt.setText(str);
                break;
            case R.id.nine1:
                str = str.append("9");
                numTxt.setText(str);
                break;
            case R.id.zero1:
                str = str.append("0");
                numTxt.setText(str);
                break;
            case R.id.mul1:
                str = str.append("*");
                numTxt.setText(str);
                break;
            case R.id.dieze1:
                str = str.append("#");
                numTxt.setText(str);
                break;
        }
    }
}


text:
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

                     User Profile

                    <img src="<?php echo asset_url('img/ajax-loader.gif'); ?>">

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
package com.vajda.spockExamples.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:org/jtransfo/spring/jTransfoContext.xml")
public class Application {

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


text:
<?php
$this->breadcrumbs=array(
	'Stories'=>array('index'),
	$model->id=>array('view','id'=>$model->id),
	'Update',
);

?>

Editar historia

<?php echo $project->key; ?>

<?php echo $project->name; ?>

<?php
    echo CHtml::link('Volver theme->baseUrl.'/img/system/volver.png"/>',
                        array('project/productbacklog/'.$project->id));
 ?>

<?php echo $this->renderPartial('_form', array('model'=>$model,'project'=>$project)); ?>


text:
package org.elasticsearch.cluster;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.cluster.health.ClusterIndexHealth;
import org.elasticsearch.action.admin.cluster.health.ClusterShardHealth;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.hamcrest.Matchers;
import org.junit.Test;

import java.io.IOException;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.empty;

public class ClusterHealthResponsesTests extends ElasticsearchTestCase {

    private void assertIndexHealth(ClusterIndexHealth indexHealth, ShardCounter counter, IndexMetaData indexMetaData) {
        assertThat(indexHealth.getStatus(), equalTo(counter.status()));
        assertThat(indexHealth.getNumberOfShards(), equalTo(indexMetaData.getNumberOfShards()));
        assertThat(indexHealth.getNumberOfReplicas(), equalTo(indexMetaData.getNumberOfReplicas()));
        assertThat(indexHealth.getActiveShards(), equalTo(counter.active));
        assertThat(indexHealth.getRelocatingShards(), equalTo(counter.relocating));
        assertThat(indexHealth.getInitializingShards(), equalTo(counter.initializing));
        assertThat(indexHealth.getUnassignedShards(), equalTo(counter.unassigned));
        assertThat(indexHealth.getShards().size(), equalTo(indexMetaData.getNumberOfShards()));
        assertThat(indexHealth.getValidationFailures(), empty());
        int totalShards = 0;
        for (ClusterShardHealth shardHealth : indexHealth.getShards().values()) {
            totalShards += shardHealth.getActiveShards() + shardHealth.getInitializingShards() + shardHealth.getUnassignedShards();
        }

        assertThat(totalShards, equalTo(indexMetaData.getNumberOfShards() * (1 + indexMetaData.getNumberOfReplicas())));
    }

    protected class ShardCounter {
        public int active;
        public int relocating;
        public int initializing;
        public int unassigned;
        public int primaryActive;
        public int primaryInactive;

        public ClusterHealthStatus status() {
            if (primaryInactive > 0) {
                return ClusterHealthStatus.RED;
            }
            if (unassigned > 0 || initializing > 0) {
                return ClusterHealthStatus.YELLOW;
            }
            return ClusterHealthStatus.GREEN;
        }

        public void update(ShardRouting shardRouting) {
            if (shardRouting.active()) {
                active++;
                if (shardRouting.primary()) {
                    primaryActive++;
                }
                if (shardRouting.relocating()) {
                    relocating++;
                }
                return;
            }

            if (shardRouting.primary()) {
                primaryInactive++;
            }
            if (shardRouting.initializing()) {
                initializing++;
            } else {
                unassigned++;
            }
        }
    }

    static int node_id = 1;

    private ImmutableShardRouting genShardRouting(String index, int shardId, boolean primary) {

        ShardRoutingState state;

        int i = randomInt(40);
        if (i > 5) {
            state = ShardRoutingState.STARTED;
        } else if (i > 3) {
            state = ShardRoutingState.RELOCATING;
        } else if (i > 1) {
            state = ShardRoutingState.INITIALIZING;
        } else {
            state = ShardRoutingState.UNASSIGNED;
        }

        switch (state) {
            case UNASSIGNED:
                return new MutableShardRouting(index, shardId, null, primary, ShardRoutingState.UNASSIGNED, 1);
            case STARTED:
                return new MutableShardRouting(index, shardId, "node_" + Integer.toString(node_id++), primary, ShardRoutingState.STARTED, 1);
            case INITIALIZING:
                return new MutableShardRouting(index, shardId, "node_" + Integer.toString(node_id++), primary, ShardRoutingState.INITIALIZING, 1);
            case RELOCATING:
                return new MutableShardRouting(index, shardId, "node_" + Integer.toString(node_id++), "node_" + Integer.toString(node_id++), primary, ShardRoutingState.RELOCATING, 1);
            default:
                throw new ElasticsearchException("Unknown state: " + state.name());
        }

    }

    private IndexShardRoutingTable genShardRoutingTable(String index, int shardId, int replicas, ShardCounter counter) {
        IndexShardRoutingTable.Builder builder = new IndexShardRoutingTable.Builder(new ShardId(index, shardId), true);
        ImmutableShardRouting shardRouting = genShardRouting(index, shardId, true);
        counter.update(shardRouting);
        builder.addShard(shardRouting);
        for (; replicas > 0; replicas--) {
            shardRouting = genShardRouting(index, shardId, false);
            counter.update(shardRouting);
            builder.addShard(shardRouting);
        }

        return builder.build();
    }

    IndexRoutingTable genIndexRoutingTable(IndexMetaData indexMetaData, ShardCounter counter) {
        IndexRoutingTable.Builder builder = IndexRoutingTable.builder(indexMetaData.index());
        for (int shard = 0; shard < indexMetaData.numberOfShards(); shard++) {
            builder.addIndexShard(genShardRoutingTable(indexMetaData.index(), shard, indexMetaData.getNumberOfReplicas(), counter));
        }
        return builder.build();
    }

    @Test
    public void testClusterIndexHealth() {
        int numberOfShards = randomInt(3) + 1;
        int numberOfReplicas = randomInt(4);
        IndexMetaData indexMetaData = IndexMetaData.builder("test1").settings(settings(Version.CURRENT)).numberOfShards(numberOfShards).numberOfReplicas(numberOfReplicas).build();
        ShardCounter counter = new ShardCounter();
        IndexRoutingTable indexRoutingTable = genIndexRoutingTable(indexMetaData, counter);

        ClusterIndexHealth indexHealth = new ClusterIndexHealth(indexMetaData, indexRoutingTable);
        logger.info("index status: {}, expected {}", indexHealth.getStatus(), counter.status());
        assertIndexHealth(indexHealth, counter, indexMetaData);
    }

    private void assertClusterHealth(ClusterHealthResponse clusterHealth, ShardCounter counter) {
        assertThat(clusterHealth.getStatus(), equalTo(counter.status()));
        assertThat(clusterHealth.getActiveShards(), equalTo(counter.active));
        assertThat(clusterHealth.getActivePrimaryShards(), equalTo(counter.primaryActive));
        assertThat(clusterHealth.getInitializingShards(), equalTo(counter.initializing));
        assertThat(clusterHealth.getRelocatingShards(), equalTo(counter.relocating));
        assertThat(clusterHealth.getUnassignedShards(), equalTo(counter.unassigned));
        assertThat(clusterHealth.getValidationFailures(), empty());
    }

    @Test
    public void testClusterHealth() throws IOException {
        ShardCounter counter = new ShardCounter();
        RoutingTable.Builder routingTable = RoutingTable.builder();
        MetaData.Builder metaData = MetaData.builder();
        for (int i = randomInt(4); i >= 0; i--) {
            int numberOfShards = randomInt(3) + 1;
            int numberOfReplicas = randomInt(4);
            IndexMetaData indexMetaData = IndexMetaData.builder("test_" + Integer.toString(i)).settings(settings(Version.CURRENT)).numberOfShards(numberOfShards).numberOfReplicas(numberOfReplicas).build();
            IndexRoutingTable indexRoutingTable = genIndexRoutingTable(indexMetaData, counter);
            metaData.put(indexMetaData, true);
            routingTable.add(indexRoutingTable);
        }
        ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
        int pendingTasks = randomIntBetween(0, 200);
        int inFlight = randomIntBetween(0, 200);
        ClusterHealthResponse clusterHealth = new ClusterHealthResponse("bla", clusterState.metaData().concreteIndices(IndicesOptions.strictExpand(), (String[]) null), clusterState, pendingTasks, inFlight);
        logger.info("cluster status: {}, expected {}", clusterHealth.getStatus(), counter.status());
        clusterHealth = maybeSerialize(clusterHealth);
        assertClusterHealth(clusterHealth, counter);
        assertThat(clusterHealth.getNumberOfPendingTasks(), Matchers.equalTo(pendingTasks));
        assertThat(clusterHealth.getNumberOfInFlightFetch(), Matchers.equalTo(inFlight));
    }

    ClusterHealthResponse maybeSerialize(ClusterHealthResponse clusterHealth) throws IOException {
        if (randomBoolean()) {
            BytesStreamOutput out = new BytesStreamOutput();
            clusterHealth.writeTo(out);
            StreamInput in = StreamInput.wrap(out.bytes());
            clusterHealth = ClusterHealthResponse.readResponseFrom(in);
        }
        return clusterHealth;
    }

    @Test
    public void testValidations() throws IOException {
        IndexMetaData indexMetaData = IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(2).numberOfReplicas(2).build();
        ShardCounter counter = new ShardCounter();
        IndexRoutingTable indexRoutingTable = genIndexRoutingTable(indexMetaData, counter);
        indexMetaData = IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(2).numberOfReplicas(3).build();

        ClusterIndexHealth indexHealth = new ClusterIndexHealth(indexMetaData, indexRoutingTable);
        assertThat(indexHealth.getValidationFailures(), Matchers.hasSize(2));

        RoutingTable.Builder routingTable = RoutingTable.builder();
        MetaData.Builder metaData = MetaData.builder();
        metaData.put(indexMetaData, true);
        routingTable.add(indexRoutingTable);
        ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
        ClusterHealthResponse clusterHealth = new ClusterHealthResponse("bla", clusterState.metaData().concreteIndices(IndicesOptions.strictExpand(), (String[]) null), clusterState, 0, 0);
        clusterHealth = maybeSerialize(clusterHealth);
        // currently we have no cluster level validation failures as index validation issues are reported per index.
        assertThat(clusterHealth.getValidationFailures(), Matchers.hasSize(0));
    }
}


text:
{% extends 'dash_base.html' %}
{% load parse_date %}
{% load sizeformat %}

{% block sidebar %}
  {% with current_sidebar="overview" %}
    {{block.super}}
  {% endwith %}
{% endblock %}

{% block page_header %}
  {# to make searchable false, just remove it from the include statement #}
  {% include "_page_header.html" with title="Overview" %}
{% endblock page_header %}

{% block dash_main %}

  {% if usage.instances %}

CPU

{{usage.total_active_vcpus|default:0}}Cores Active

{{usage.total_cpu_usage|floatformat|default:0}}CPU-HR Used

RAM

{{total_ram|default:0}}{{ram_unit}} Active

Disk

{{usage.total_active_disk_size|default:0}}GB Active

{{usage.total_disk_usage|floatformat|default:0}}GB-HR Used

Server Usage Summary

          {% if show_terminated %}
            ( Hide Terminated )
          {% else %}
            ( Show Terminated )
          {% endif %}

        ID
        Name
        User
        VCPUs
        Ram Size
        Disk Size
        Flavor
        Uptime
        Status

        {% for instance in instances %}
          {% if instance.ended_at %}

          {% else %}

          {% endif %}
            {{instance.id}}
            {{instance.name}}
            {{instance.user_id}}
            {{instance.vcpus}}
            {{instance.ram_size|mbformat}}
            {{instance.disk_size}}GB
            {{instance.flavor}}
            {{instance.uptime_at|timesince}}
            {{instance.state|lower|capfirst}}

        {% empty %}

               No active instances.

        {% endfor %}

  {% else %}

Info

There are currently no instances.

You can launch an instance from the  Images Page.

  {% endif %}

{% endblock %}


text:
#pragma once

#include "timestamp.h"

/**
 * Information about a file. Returned from the Path::info() member. Avoids calling exists(), cTime()
 * and mTime() separately if they are all needed.
 */
class FileInfo {
public:
	// Create.
	FileInfo(bool exists, Timestamp cTime = Timestamp(0), Timestamp mTime = Timestamp(0))
		: exists(exists), cTime(cTime), mTime(mTime) {}

	// Does the file exist?
	bool exists;

	// Created time. 0 if the file does not exist.
	Timestamp cTime;

	// Modified time. 0 if the file does not exist.
	Timestamp mTime;
};

/**
 * A class for managing path names.
 */
class Path {
	friend std::ostream &operator <<(std::ostream &to, const Path &path);
public:
	// Current working directory.
	static Path cwd();

	// User's home directory.
	static Path home();

	// Are the string equal regarding the current OS?
	static bool equal(const String &a, const String &b);
	static int compare(const String &a, const String &b);

	// Create an empty path.
	Path();

	// Create a path object from a string.
	explicit Path(const String &path);

	// Comparison.
	bool operator ==(const Path &o) const;
	inline bool operator !=(const Path &o) const { return !(*this == o); }
	bool operator <(const Path &o) const;
	bool operator >(const Path &o) const;

	// Concat this path with another path, the other path must be relative.
	Path operator +(const Path &other) const;
	Path &operator +=(const Path &other);

	// Add a string to go deeper into the hierarchy. If this object is not
	// a directory already, it will be made into one.
	Path operator +(const String &file) const;
	Path &operator +=(const String &file);

	// Status about this path.
	bool isDir() const;
	bool isAbsolute() const;
	bool isEmpty() const;

	// Make this obj a directory.
	inline void makeDir() { isDirectory = true; }

	// Get parent directory.
	Path parent() const;

	// Get first directory part.
	String first() const;

	// Get the title of this file or directory.
	String title() const;
	String titleNoExt() const;

	// Get file extension (always the last one).
	String ext() const;

	// Set the file extension (always the last one).
	void makeExt(const String &ext);

	// Set the title (includes ext).
	void makeTitle(const String &title);

	// Does the file exist?
	bool exists() const;

	// Delete the file.
	void deleteFile() const;
	void deleteDir() const;

	// Recursive removal of file/directory.
	void recursiveDelete() const;

	// Make this path relative to another path. Absolute-making is accomplished by
	// using the + operator above.
	Path makeRelative(const Path &to) const;

	// Make this path absolute if it is not already.
	Path makeAbsolute() const;
	Path makeAbsolute(const Path &abs) const;

	// Check if this path is a child of another path.
	bool isChild(const Path &to) const;

	// Find the children of this path.
	vector<Path> children() const;

	// Modified time.
	Timestamp mTime() const;

	// Created time.
	Timestamp cTime() const;

	// Get file information. Essentially calls cTime, mTime and exists at the same time.
	FileInfo info() const;

	// Create this path as directory if it does not already exist.
	void createDir() const;

	// Hash.
	size_t hash() const;

private:

	// Internal representation is a list of strings, one for each part of the pathname.
	vector<String> parts;

	// Is this a directory?
	bool isDirectory;

	// Parse a path string.
	void parseStr(const String &str);

	// Simplify a path string, which means to remove any . and ..
	void simplify();
};


text:
chessboard.js - JavaScript Chess Board
==================================================
A minimalistic fork of [oakmac/chessboardjs](https://github.com/oakmac/chessboardjs).

License
--------------------------------------
chessboard.js is released under the [MIT License](LICENSE).


text:
#import <Foundation/Foundation.h>

@protocol KAABase64

- (NSData *)decodeBase64:(NSData *)base64Data;
- (NSData *)decodeString:(NSString *)base64String;
- (NSData *)encodeBase64:(NSData *)binaryData;
- (NSString *)encodedString:(NSData *)binaryData;

@end

/**
 * Default platform Base64 implementation.
 */
@interface CommonBase64 : NSObject <KAABase64>

@end


text:
// MMRecordCache.h
//
// Copyright (c) 2013 Mutual Mobile (http://www.mutualmobile.com/)
//
// 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.

#import <CoreData/CoreData.h>

/**
 This class encapsulates the functionality for caching managed objects in correspondence to a
 particular NSURLRequest's NSCachedURLResponse. It is meant to be a private class used by MMRecord
 should you wish to enable caching support for a given entity type. However, it could be used as a
 standalone way to cache NSManagedObject's for a given NSURLRequest. Your milage may vary.

 ## Caching

 In general, the best way to implement caching is through the use of NSURLCache and the server's
 implementation of the HTTP Cache Control headers.  In the event that this is not enough, MMRecord
 does provide an additional level of caching support.  The caching provided by MMRecord is in
 accordance with the cache control headers and augments the system provided by NSURLCache.
 If caching is enabled then MMRecord will store the object IDs for each request/response pair that
 were parsed as part of the last response in a separate SQLite persistent store.  It's important to
 note that these are stored UNENCRYPTED.  IF DATA SECURITY IS A REQUIREMENT CACHING SHOULD NOT BE
 USED!

 ## Configuration

 Please see the MMRecord header for more information about configuring your app to support caching.
 */

@interface MMRecordCache : NSObject

/**
 This method returns YES if there are cached results for a given key. The key is typically the
 absolute URL for a given NSURLRequest. You can specify the key using the cacheRecords method below.
 @param cacheKey The key used to identify cached results.
 @return BOOL YES for has results, NO otherwise.
 */
+ (BOOL)hasResultsForKey:(NSString *)cacheKey;

/**
 This method retrieves cached results in a given context. If results are cached, it will fetch
 those objectIDs from the internal caching persistent store and attempt to obtain records matching
 those object IDs in the provided managed object context. Those records, along with the cached
 response object (if any) will be returned in the cache result block. This method will also respect
 the caching policy of the NSURLCache and of this NSURLRequest. If the response for that request is
 not cached, no results will be returned - regardless of what is found in the cache persistent store.
 @param request Request object to obtain cached results for.
 @param cacheKey Key used to identify the cached results.
 @param metaKeyPath Key used to identify metadata that may have been returned in the response.
 @param context managed object context to return cached results in.
 @param cacheResultBlock Result block that will be executed when this method finishes checking for
 cached results.
 */
+ (void)getCachedResultsForRequest:(NSURLRequest *)request
                          cacheKey:(NSString *)cacheKey
                       metaKeyPath:(NSString *)metaKeyPath
                           context:(NSManagedObjectContext *)context
                  cacheResultBlock:(void(^)(NSArray *cachedResults, id responseObject))cacheResultBlock;
/**
 This method caches the objectIDs of the given records. Those records should be subclasses of
 NSManagedObject. The key provided will be used to locate those records later if a subsequent
 request is made for a certain NSURLRequest which you wish to associate with that key.
 @param records An array of records that should be cached.
 @param metadata Metadata contained in the response that should also be cached.
 @param key A key that will be associated with and used to identify cached results.
 @param context A managed object context where these records exist.
 */
+ (void)cacheRecords:(NSArray *)records
        withMetadata:(NSDictionary *)metadata
              forKey:(NSString *)key
         fromContext:(NSManagedObjectContext *)context;

@end


text:
if [[ (-z $(git rev-parse HEAD 2>/dev/null)) ]]; then
	echo "$PWD is not a Git repository"
	[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

current=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
git fetch --all &>/dev/null &>/dev/null
if [[ "$?" -ne "0" ]]; then
	echo "git fetch --all failed"
	[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi

for branch in $(git branch -a | cut -b 2- | grep "remotes/origin" | cut -f 3 -d '/' | awk '{print $1}');
do
	# Skip anything that looks like Master
	if [[ ((-z "$branch") || ("$branch" = "master") || ("$branch" = "HEAD")) ]]; then
		continue;
	fi

	# Skip anything that looks like a release, like CRYPTOPP_5_6_3
	if [[ (! -z $(echo -n "$branch" | grep "CRYPTOPP_")) ]]; then
		continue;
	fi

	echo "**************** $branch *******************"

	git checkout -f "$branch" &>/dev/null
	if [[ "$?" -ne "0" ]]; then
		echo "git checkout $branch failed"
		continue;
	fi

	git rebase "origin/$branch"
	if [[ "$?" -ne "0" ]]; then
		echo "git rebase $branch failed"
		continue;
	fi

	git merge master -S -m "Merge branch 'master' into dev-branch '$branch'" &>/dev/null
	if [[ "$?" -ne "0" ]]; then
		echo "git merge $branch failed"
		continue;
	fi

	git push &>/dev/null
	if [[ "$?" -ne "0" ]]; then
		echo "git push $branch failed"
		continue;
	fi

	echo "Completed merging for '$branch'"

done

if [[ ! -z  "$current" ]]; then
	git checkout "$current" &>/dev/null
fi

echo "Back on branch $current"

[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    IPC_SAP.h
 *
 *  $Id: IPC_SAP.h 935 2008-12-10 21:47:27Z mitza $
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//=============================================================================

#ifndef ACE_IPC_SAP_H
#define ACE_IPC_SAP_H
#include /**/ "ace/pre.h"

#include "ace/Flag_Manip.h"
#include "ace/os_include/sys/os_types.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_IPC_SAP
 *
 * @brief Defines the member functions for the base class of the
 * ACE_IPC_SAP abstraction.
 */
class ACE_Export ACE_IPC_SAP
{
public:

  /// Interface for <ioctl>.
  int control (int cmd, void *) const;

  // = Common I/O handle options related to sockets.

  /**
   * Enable asynchronous I/O (ACE_SIGIO), urgent data (ACE_SIGURG),
   * non-blocking I/O (ACE_NONBLOCK), or close-on-exec (ACE_CLOEXEC),
   * which is passed as the @a value.
   */
  int enable (int value) const;

  /**
   * Disable asynchronous I/O (ACE_SIGIO), urgent data (ACE_SIGURG),
   * non-blocking I/O (ACE_NONBLOCK), or close-on-exec (ACE_CLOEXEC),
   * which is passed as the @a value.
   */
  int disable (int value) const;

  /// Get the underlying handle.
  ACE_HANDLE get_handle (void) const;

  /// Set the underlying handle.
  void set_handle (ACE_HANDLE handle);

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

protected:

  // = Ensure that ACE_IPC_SAP is an abstract base class.
  /// Default constructor.
  ACE_IPC_SAP (void);

  /// Protected destructor.
  /**
   * Not a virtual destructor.  Protected destructor to prevent
   * operator delete() from being called through a base class
   * ACE_IPC_SAP pointer/reference.
   */
  ~ACE_IPC_SAP (void);

private:
  /// Underlying I/O handle.
  ACE_HANDLE handle_;

  /// Cache the process ID.
  static pid_t pid_;
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/IPC_SAP.inl"
#endif /* __ACE_INLINE__ */

#include /**/ "ace/post.h"
#endif /* ACE_IPC_SAP_H */


text:
package org.apache.poi.hssf.usermodel;

/**
 * Represents a simple shape such as a line, rectangle or oval.
 *
 * @author Glen Stampoultzis (glens at apache.org)
 */
public class HSSFSimpleShape
    extends HSSFShape
{
    // The commented out ones haven't been tested yet or aren't supported
    // by HSSFSimpleShape.

    public final static short       OBJECT_TYPE_LINE               = 1;
    public final static short       OBJECT_TYPE_RECTANGLE          = 2;
    public final static short       OBJECT_TYPE_OVAL               = 3;
//    public final static short       OBJECT_TYPE_ARC                = 4;
//    public final static short       OBJECT_TYPE_CHART              = 5;
//    public final static short       OBJECT_TYPE_TEXT               = 6;
//    public final static short       OBJECT_TYPE_BUTTON             = 7;
    public final static short       OBJECT_TYPE_PICTURE            = 8;
//    public final static short       OBJECT_TYPE_POLYGON            = 9;
//    public final static short       OBJECT_TYPE_CHECKBOX           = 11;
//    public final static short       OBJECT_TYPE_OPTION_BUTTON      = 12;
//    public final static short       OBJECT_TYPE_EDIT_BOX           = 13;
//    public final static short       OBJECT_TYPE_LABEL              = 14;
//    public final static short       OBJECT_TYPE_DIALOG_BOX         = 15;
//    public final static short       OBJECT_TYPE_SPINNER            = 16;
//    public final static short       OBJECT_TYPE_SCROLL_BAR         = 17;
//    public final static short       OBJECT_TYPE_LIST_BOX           = 18;
//    public final static short       OBJECT_TYPE_GROUP_BOX          = 19;
//    public final static short       OBJECT_TYPE_COMBO_BOX          = 20;
    public final static short       OBJECT_TYPE_COMMENT            = 25;
//    public final static short       OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 30;

    int shapeType = OBJECT_TYPE_LINE;

    HSSFSimpleShape( HSSFShape parent, HSSFAnchor anchor )
    {
        super( parent, anchor );
    }

    /**
     * Gets the shape type.
     * @return  One of the OBJECT_TYPE_* constants.
     *
     * @see #OBJECT_TYPE_LINE
     * @see #OBJECT_TYPE_OVAL
     * @see #OBJECT_TYPE_RECTANGLE
     * @see #OBJECT_TYPE_PICTURE
     * @see #OBJECT_TYPE_COMMENT
     */
    public int getShapeType() { return shapeType; }

    /**
     * Sets the shape types.
     *
     * @param shapeType One of the OBJECT_TYPE_* constants.
     *
     * @see #OBJECT_TYPE_LINE
     * @see #OBJECT_TYPE_OVAL
     * @see #OBJECT_TYPE_RECTANGLE
     * @see #OBJECT_TYPE_PICTURE
     * @see #OBJECT_TYPE_COMMENT
     */
    public void setShapeType( int shapeType ){ this.shapeType = shapeType; }

}


text:
get '/views/:widget?.html' do
  widget = params[:widget]
  tilt_html_engines.each do |suffix, engines|
    file_name = "#{widget}.#{suffix}"
    file_override_path = File.join(settings.root, 'widgets', widget, file_name)
    return engines.first.new(file_override_path).render if File.exist?(file_override_path)

    file_path = File.join(File.dirname(__FILE__), 'assets', 'widgets', widget, file_name)
    return engines.first.new(file_path).render if File.exist?(file_path)
  end
end


text:
@page index testapp

This is a placeholder for the homepage of your documentation.


text:
layout: post
title: Les règles pour être humain
date: 2012-07-31 12:36:36.000000000 +02:00
categories:
- Textes
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '2'
author:
  first_name: Nico
excerpt:
---

Traduites du sanscrit

Tu recevras un corps

Que tu l’aimes ou non, il sera tien pour toute la période de ta vie.

Tu apprendras des leçons

Tu es engagé dans une école informelle appelée « vie ». Chaque jour dans cette école, tu auras l'opportunité d'apprendre des leçons. Il se peut que tu apprécies ces leçons ou, au contraire, que tu les trouves inappropriées ou même stupides.

Il n'y a pas d'erreurs, seulement des leçons

La croissance est un processus composé d'essais, d'erreurs et d'expérimentations. Les expériences « échouées » font partie du processus au même titre que les expériences qui finalement fonctionnent.

Une leçon est répétée jusqu'à ce qu'elle soit assimilée

Une leçon te sera proposée sous diverses formes jusqu'à ce que tu l'aies comprise. Alors seulement, tu pourras passer à la leçon suivante.

Apprendre des leçons est sans fin

Il n'y a pas une partie de la vie qui ne contienne pas de leçon. Si tu es en vie, il y a des leçons à apprendre.

Il n'y a rien de mieux qu'« ici »

Lorsque ton « là-bas » devient ton « ici », tu obtiendras simplement un autre « là-bas » qui semblera être plus attirant que l'« ici ».

Les autres ne sont que des miroirs de toi-même

Tu ne peux aimer ou détester quelque chose chez une autre personne sans que ceci se réfléchisse dans quelque chose que tu aimes ou que tu détestes à propos de toi-même.

Ce que tu fais de ta vie ne dépend que de toi

Tu possèdes tous les outils et les ressources dont tu as besoin. Ce que tu en fais n'appartient qu'à toi. Tu as le choix.

La réponse est en toi

Les réponses aux questions existentielles sont en toi. La seule chose que tu dois faire est d'observer, écouter et avoir confiance.


text:
import os
import shutil
import sys
import platform
import threading
import logging
from time import time
from Tkinter import *
import tkMessageBox, tkFileDialog
from settings import *

class UILabels:
	def __init__(self, textFrame, text, row_loc, column_loc):
		self.string = StringVar()
		self.label = Label(textFrame, textvariable=self.string)
		self.string.set(text)
		self.label.grid(row=row_loc, column=column_loc)

	def update_label(self, text):
		self.string.set(text)

class UIWidgets:
	def __init__(self, textFrame, row_loc, column_loc):
		self.widget = Entry(textFrame)
		self.widget.grid(row=row_loc, column=column_loc)

	def getText(self):
		return self.widget.get().strip()

	def insertText(self, text):
		self.widget.insert(INSERT, text)

class UIButton:
	def __init__(self, root, text, run, row_loc, column_loc):
		self.button = Button(root, text=text, command=run)
		self.button.grid(row=row_loc, column=column_loc)

	def change_state(self, state):
		self.button['state'] = state

class UIRadioButton:
	def __init__(self, root, string, var, val, row_loc, col_loc):
		self.button = Radiobutton(root, text=string, variable=var, value=val)
		self.button.grid(row=row_loc, column=col_loc)

class UIShowError:
	def __init__(self, errorType, message):
		tkMessageBox.showerror(errorType, message)

class UIGetDir:
	def __init__(self, root):
		self.window = tkFileDialog.askdirectory(initialdir="/",  title='Please select a directory')

	def get_dir(self):
		return self.window

class UIShowInfoWindow:
	@staticmethod
	def piracy():
		tkMessageBox.showinfo("Piracy Notice", """
1) Don't forget to support the artists of the music whenever you can by buying their music and albums.
\n2) Without those who create the music there would be no game at all.
\n3) Use of this program may count as piracy in your country.
""")

	@staticmethod
	def about():
		tkMessageBox.showinfo("About", """
OsuScraper {}\n
Copyright (c) 2015 Connor Oliver\n
skyllama@yandex.com\n
http://www.skyllama.com\n
See LICENSE.txt for license infomation
""".format(VERSION))

def create_save_dir():
	if save_location in os.listdir(cwd):
		pass
	else:
		try:
			os.mkdir(save_location)
			print("\nCreated \"{}\" dir\n".format(save_location))
		except:

			print("\nCould not make directory to store songs!\n")
	return

def delete_old_log():
	if "log.txt" in os.listdir(cwd):
		try:
			os.remove("log.txt")
			print("\nRemoved old log file, log.txt\n\n")
		except:
			print("\nUnable to remove old log file, log.txt!")
	else:
		pass
	return

def set_file_output_type(state):
	global better_names
	if (state == 0):
		better_names = True
		print("Using improved names...\n")
	elif (state == 1):
		better_names = False
		print("Using raw names...\n")
	return

def get_dir(obj):
	directory = UIGetDir(root).get_dir()
	if(directory != obj.getText()):
		obj.insertText(directory)
	else:
		pass

def logger(operation_info):
	if (logging == True):
		with open('log.txt', 'a') as log_file:
			log_file.write(operation_info + "\n")
	else:
		pass

def find_files(osu_dir, t0):
	for dir_name, subdir, filelist in os.walk(osu_dir):
		for filename in filelist: #Itterate through filenames
			#Decide why type of file name to use
			if better_names == True:
				out_name = dir_name.split(os.sep)[-1] + ".mp3"
			elif better_names == False:
				out_name = filename
			#Check if filename matches known ui audio
			if any(s in filename.lower() for s in skip_names) == True:
				if ("mp3" in filename):
					logger("Matched: " + filename)
				else:
					pass
			else: #If not known ui audio continue copying
				if ("mp3" in filename):
					file_name_progress.update_label(filename[:10])
					try:
						#Attempt to copy audio file with source folder name
						shutil.copy2(dir_name + os.sep + filename, save_location + os.sep + out_name)
						print(out_name + "\n")
						logger("Copied: " + out_name)
					except:
						print("Copy failed: " + out_name + "\n")
						logger("Failed: " + out_name)
	time_to_complete = "Operation completed in {} seconds.".format(time() - t0)
	logger("\n" + time_to_complete)
	print(time_to_complete)
	file_name_progress.update_label("Operation completed!")
	run_btn.change_state("normal")

def start_scrape():
	global text, input_dir, save_location
	if osuDirWidget.getText() == "":
		UIShowError("Error", "Please enter Osu! song directory!")
	else:
		run_btn.change_state("disabled")
		if saveDirWidget.getText() != "":
			save_location = saveDirWidget.getText()
		elif saveDirWidget.getText() == "":
			save_location = "songs"
		input_dir = osuDirWidget.getText()
		start_str = "\nRunning on: " + platform.system() + " " + platform.release() + " at " + run_time
		print(start_str)
		delete_old_log()
		logger(start_str)
		create_save_dir()
		set_file_output_type(radio_state.get())

		#Create actual thread for scraping that runs scrape_main, then start it.
		scrape_thread = threading.Thread(name="SCRAPINGTHREAD", target=scrape_main)
		scrape_thread.start()
	return

def scrape_main():
	t0 = time()
	find_files(input_dir, t0)
	return

def create_gui():
	global root, osuDirWidget, saveDirWidget, text, radio_state, textbox
	global file_name_progress, current_num_progress, run_btn
	#Create Window
	root = Tk()
	root.resizable(width=FALSE, height=FALSE)
	radio_state = IntVar()
	root.title(NAME + " " + VERSION)
	root["padx"] = 5
	root["pady"] = 5

	#Create elements For Osu dir selection
	UILabels(root, "Osu Song Directory:", 0, 0)
	osuDirWidget = UIWidgets(root, 0, 1)
	UIButton(root, "Select Dir...", lambda: get_dir(osuDirWidget), 0, 2)

	#Create elements for output dir selection
	UILabels(root, "Save Directory:", 1, 0)
	saveDirWidget = UIWidgets(root, 1, 1)
	UIButton(root, "Select Dir...", lambda: get_dir(saveDirWidget), 1, 2)

	#Create elements for output file name type selection
	UILabels(root, "Output Names:", 2, 0)

	#Create radio vuttons for file output type selection
	UIRadioButton(root, "Raw", radio_state, 1, 2, 1)
	UIRadioButton(root, "Improved", radio_state, 0, 3, 1)
	UILabels(root, "", 4, 0) #blank

	#Create elements for progress report
	UILabels(root, "Current File:", 5, 0)
	file_name_progress = UILabels(root, "None", 5, 1)
	UILabels(root, "", 6, 0) #blank

	#Option Buttons
	UIButton(root, "About", UIShowInfoWindow.about, 7, 0)
	UIButton(root, "Piracy", UIShowInfoWindow.piracy, 7, 1)
	run_btn = UIButton(root, "Run", start_scrape, 7, 2)

	root.mainloop()
	return

def main():
	create_gui()

if __name__ == "__main__":
	gui_thread = threading.Thread(name="GUITHREAD", target=main)
	gui_thread.start()


text:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Jini Print Service Tutorial -- Lesson 6. File Print Jobs</TITLE>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.util.Locale;
import javax.print.attribute.Attribute;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.standard.DocumentName;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.MediaColor;
import javax.print.attribute.standard.MediaKind;
import javax.print.attribute.standard.MediaOpacity;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.exception.PrintException;
import net.jini.core.entry.Entry;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.print.job.PrintRequest;
import net.jini.print.lookup.AttributeEntry;
import net.jini.print.lookup.FlavorEntry;
import net.jini.print.lookup.MediaEntry;
import net.jini.print.service.PrintService;
import org.jpwg.jini.print.data.InputStreamDoc;
. . .
try
    {
    Media theMedia = new Media
        (new Attribute[]
            {MediaSize.NA.LETTER,
             MediaColor.PINK,
             MediaOpacity.OPAQUE,
             MediaKind.SHEET});
    InputStreamDoc theDoc =
        new InputStreamDoc
            (new BufferedInputStream
                (new FileInputStream ("foobar.txt")),
             "text/plain; charset=us-ascii",
             new HashDocAttributeSet
                (new DocumentName
                    ("foobar.txt",
                     Locale.getDefault())));
    ServiceRegistrar theJLUS = // Obtain a Jini Lookup Service (JLUS) proxy
    ServiceTemplate theServiceTemplate =
        new ServiceTemplate
            (null,
             new Class[] {PrintService.class},
             new Entry[]
                {new FlavorEntry (theDoc.getDocFlavor()),
                 new MediaEntry (theMedia),
                 new AttributeEntry (OrientationRequested.LANDSCAPE)});
    PrintService thePrintService =
        (PrintService) theJLUS.lookup (theServiceTemplate);
    if (thePrintService != null)
        {
        PrintRequest thePrintRequest =
            thePrintService.createDocPrintRequest
                (theDoc,
                 new HashPrintRequestAttributeSet
                    (new PrintRequestAttribute[]
                        {theMedia,
                         OrientationRequested.LANDSCAPE,
                         new JobName
                            ("Test Job",
                             Locale.getDefault())}));
        thePrintRequest.print();
        }
    else
        {
        // This code executed if the JLUS couldn't find any print services
        }
    }
catch (PrintException exc)
    {
    // This code executed if a printing error occurred
    // Thrown by any of the above
    }
catch (RemoteException exc)
    {
    // This code executed if a remote error occurred
    // Thrown by any of the above
    }
catch (FileNotFoundException exc)
    {
    // This code executed if the file could not be opened
    // Thrown by new FileInputStream()
    }