text:
/**
 * @flow
 */

import React, { Component } from 'react';
import {
  TouchableOpacity,
  AppRegistry,
  ScrollView,
  StyleSheet,
  Platform,
  WebView,
  Text,
  View
} from 'react-native';

import ImagePicker from 'react-native-image-picker';

const ICON_CHECK = String.fromCharCode(parseInt('e900', 16));
const ICON_UNCHECK = String.fromCharCode(parseInt('e901', 16));
const ICON_REDO = String.fromCharCode(parseInt('e902', 16));
const ICON_UNDO = String.fromCharCode(parseInt('e903', 16));
const ICON_HEADER1 = String.fromCharCode(parseInt('e904', 16));
const ICON_HEADER2 = String.fromCharCode(parseInt('e905', 16));
const ICON_HEADER3 = String.fromCharCode(parseInt('e906', 16));
const ICON_HEADER4 = String.fromCharCode(parseInt('e907', 16));
const ICON_IMAGEFILE = String.fromCharCode(parseInt('e908', 16));
const ICON_KEYBOARD = String.fromCharCode(parseInt('e909', 16));
const ICON_UNORDEREDLIST = String.fromCharCode(parseInt('e910', 16));
const ICON_ORDEREDLIST = String.fromCharCode(parseInt('e911', 16));
const ICON_INDENT = String.fromCharCode(parseInt('e912', 16));
const ICON_OUTDENT = String.fromCharCode(parseInt('e913', 16));
const ICON_BOLD = String.fromCharCode(parseInt('e914', 16));
const ICON_ITALIC = String.fromCharCode(parseInt('e915', 16));
const ICON_QUOTE = String.fromCharCode(parseInt('e916', 16));

export default class WebViewRichEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorStates: [],
      showToolBar: true,
      editorHtml: ''
    }

    this.onMessage = this.onMessage.bind(this);
    this.postMessage = this.postMessage.bind(this);
    this.initCommands = this.initCommands.bind(this);

    this.initCommands();
  }

  initCommands() {
    this.commands = [];
    Platform.select({
      ios: () => {
        this.commands.push({
          name: 'INSERTLOCALIMAGE', glyph: ICON_IMAGEFILE, command: JSON.stringify({
            command: 'insertLocalImage'
          })
        });
      },
      android: () => {
        if (Platform.Version >= 19) {
          this.commands.push({
            name: 'INSERTLOCALIMAGE', glyph: ICON_IMAGEFILE, command: JSON.stringify({
              command: 'insertLocalImage'
            })
          });
        }
      }
    })();
    this.commands.push({
      name: 'UNDO', glyph: ICON_UNDO, command: JSON.stringify({
        command: "undo"
      })
    });
    this.commands.push({
      name: 'REDO', glyph: ICON_REDO, command: JSON.stringify({
        command: "redo"
      })
    });
    this.commands.push({
      name: 'INDENT', glyph: ICON_INDENT, command:
      JSON.stringify({
        command: "indent"
      })
    });
    this.commands.push({
      name: 'OUTDENT', glyph: ICON_OUTDENT, command:
      JSON.stringify({
        command: "outdent"
      })
    });
    Platform.select({
      ios: () => {
        this.commands.push({
          name: 'BOLD', glyph: ICON_BOLD, command: JSON.stringify({
            command: "bold"
          })
        });
        this.commands.push({
          name: 'ITALIC', glyph: ICON_ITALIC, command: JSON.stringify({
            command: "italic"
          })
        });
      },
      android: () => {
        if (Platform.Version >= 19) {
          this.commands.push({
            name: 'BOLD', glyph: ICON_BOLD, command: JSON.stringify({
              command: "bold"
            })
          });
          this.commands.push({
            name: 'ITALIC', glyph: ICON_ITALIC, command: JSON.stringify({
              command: "italic"
            })
          });
        }
      }
    })();
    this.commands.push({
      name: 'H1', glyph: ICON_HEADER1, command: JSON.stringify({
        command: "heading1"
      })
    });
    this.commands.push({
      name: 'H2', glyph: ICON_HEADER2, command: JSON.stringify({
        command: "heading2"
      })
    });
    this.commands.push({
      name: 'H3', glyph: ICON_HEADER3, command: JSON.stringify({
        command: "heading3"
      })
    });
    this.commands.push({
      name: 'H4', glyph: ICON_HEADER4, command:
      JSON.stringify({
        command: "heading4"
      })
    });
    Platform.select({
      ios: () => {
        this.commands.push({
          name: 'UNORDERLIST', glyph: ICON_UNORDEREDLIST, command:
          JSON.stringify({
            command: "unorderList"
          })
        });
        this.commands.push({
          name: 'ORDERLIST', glyph: ICON_ORDEREDLIST, command:
          JSON.stringify({
            command: "orderList"
          })
        });
        this.commands.push({
          name: 'BLOCKQUOTE', glyph: ICON_QUOTE, command:
          JSON.stringify({
            command: "quote"
          })
        });
      },
      android: () => {
        if (Platform.Version >= 19) {
          this.commands.push({
            name: 'UNORDERLIST', glyph: ICON_UNORDEREDLIST, command: JSON.stringify({
              command: "unorderList"
            })
          });
          this.commands.push({
            name: 'ORDERLIST', glyph: ICON_ORDEREDLIST, command: JSON.stringify({
              command: "orderList"
            })
          })
          this.commands.push({
            name: 'BLOCKQUOTE', glyph: ICON_QUOTE, command: JSON.stringify({
              command: "quote"
            })
          });
        }
      }
    })();
  }

  componentDidMount() {
    this.initIntervalID = setInterval(() => {
      this.postMessage('init');
    }, 500)
  }

  onMessage(e) {
    let message = e.nativeEvent.data;
		console.log(message);

    if (message == 'loaded' && this.initIntervalID) {
      clearInterval(this.initIntervalID);
      this.initIntervalID = undefined;
      return
    }

    var command = null;
    try {
      command = JSON.parse(message);
    }
    catch (error) {
      return;
    }

    switch (command.command) {
      case 'STATES':
				console.log(command.states);
        this.setState({ editorStates: command.states });
        break;
      case 'HTML':
        this.setState({ editorHtml: command.html });
        break;
    }
  }

  postMessage(str) {
    if (this.webview) {
      this.webview.postMessage(str);
    }
  }

  renderButton() {
    if (this.commands && this.commands.length > 0) {
      return this.commands.map((item, index) => {
        let isChecked = this.state.editorStates.indexOf(item.name) != -1 ? true : false;
        let fontColor = isChecked ? { color: '#5fa137' } : { color: 'black' }

        return (<TouchableOpacity
          key={index}
          style={styles.button}
          onPress={() => {
            switch (item.name) {
              case 'INSERTLOCALIMAGE':
                const options = {
                  title: "选择图片",
                  cancelButtonTitle: "取消",
                  takePhotoButtonTitle: "从相机选择",
                  chooseFromLibraryButtonTitle: "从相册选择",
                  storageOptions: {
                    skipBackup: true,
                    path: 'images'
                  }
                };
                ImagePicker.showImagePicker(options, (response) => {
                  if (response.didCancel) {
                  } else if (response.error) {
                  } else if (response.customButton) {
                  } else {
                    let timestamp = new Date().getTime().toString();
                    let base64 = 'data:image/png;base64,' + response.data;
                    this.postMessage(
                      JSON.stringify({
                        command: 'insertLocalImage',
                        id: timestamp,
                        source: base64
                      })
                    );
                  }
                });

                break;
              case 'H1':
              case 'H2':
              case 'H3':
              case 'H4':
              case 'BLOCKQUOTE':
                for (let state of this.state.editorStates) {
                  if (state == item.name) {
                    this.postMessage(JSON.stringify({
                      command: "removeFormat"
                    }));
                    return;
                  }
                }
                this.postMessage(item.command);
                break;
              case 'HIDEKEYBOARD':
                this.webview.blur();
                return;
              default:
                this.postMessage(item.command);
                break;
            }
          } }>
          <Text style={[fontColor, styles.text]} >{item.glyph}</Text>
        </TouchableOpacity>);
      })
    }
    else {
      return null;
    }
  }

  render() {
    const {messagesReceivedFromWebView, message} = this.state;

    return (
      <View style={styles.container}>
        <WebView
          ref={webview => { this.webview = webview; } }
          source={require('./richeditor.html')}
          onMessage={this.onMessage}
          />
        {
          this.state.showToolBar ?
            <View style={{ height: 50 }}>
              <View style={{
                height: 1,
                alignItems: 'stretch',
                backgroundColor: '#D9E1E9',
              }} />
              <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
                <View style={styles.buttonContainer}>
                  {
                    this.renderButton()
                  }
                </View>
              </ScrollView>
            </View> : null
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  button: {
    backgroundColor: 'white',
    alignItems: 'center',
    justifyContent: 'center',
    width: 50,
    height: 50,
  },
  text: {
    fontSize: 24,
    fontFamily: "richeditor",
  }
});


text:
devmtn-exercises
================

misc exercises

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Models\Article;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Readability\Readability;
use GuzzleHttp\Client;
use Log;
use Cache;

class GetUrlContentAndSaveToArticle extends Job implements ShouldQueue {
    use InteractsWithQueue , SerializesModels;
    private $uri;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($uri) {
        //
        $this->uri = $uri;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {
        if ( Article::where('link' , $this->uri)->count() > 0 ) {
            Log::info('ÎÄÕÂÒÑ´æÔÚ' . $this->uri);
            return false;
        }
        $contentCacheKey = __CLASS__.md5($this->uri);
        $uri = $this->uri;
        $htmlContent = Cache::get($contentCacheKey,function() use($contentCacheKey,$uri){
            $client = new Client();
            $response = $client->get($uri);
            $htmlContent = $response->getBody()->getContents();
            Cache::put($contentCacheKey,$htmlContent,60*24*30);
            return $htmlContent;
        });
        $readability = new Readability($htmlContent);
        $result = $readability->init();
        if ( !$result ) {
            Log::info('½âÎöuriÕýÎÄʧ°Ü' . $this->uri);
            return false;
        }
        $title = $readability->getTitle()->textContent;
        $content = $readability->getContent()->textContent;

        $data = [
            'link'    => $this->uri ,
            'title'   => $title ,
            'content' => $content ,
        ];
        Article::create($data);
        return true;
    }
}


text:
    {% if post.image %}

    {% endif %}

{{ post.title }} — {{ post.content | strip_html | truncatewords: 35, "" }}


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

    <parent>
        <groupId>com.washingtonpost</groupId>
        <artifactId>wp-oss-parent-pom</artifactId>
        <version>0.0.8</version>
    </parent>

    <groupId>com.washingtonpost.dropwizard</groupId>
    <artifactId>dropwizard-peer-authenticator</artifactId>
    <version>3.0.2-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>dropwizard-peer-authenticator</name>
    <description>Dropwizard Authenticator that uses BasicAuth (user,pass) pairs to control access to your service</description>

    <scm>
        <connection>scm:git:git@github.com:washingtonpost/dropwizard-peer-authenticator.git</connection>
        <developerConnection>scm:git:git@github.com:washingtonpost/dropwizard-peer-authenticator.git</developerConnection>
        <tag>HEAD</tag>
        <url>http://github.com:washingtonpost/dropwizard-peer-authenticator</url>
    </scm>

    <properties>
        <version.dropwizard>1.0.5</version.dropwizard>
        <version.guava>20.0</version.guava>
        <version.jasypt>1.9.2</version.jasypt>
        <version.jcommander>1.48</version.jcommander>
        <version.maven.shade>2.4.2</version.maven.shade>
        <version.slf4j>1.7.21</version.slf4j>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${version.guava}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-auth</artifactId>
            <version>${version.dropwizard}</version>
        </dependency>
        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>${version.jasypt}</version>
        </dependency>
        <dependency>
            <groupId>com.beust</groupId>
            <artifactId>jcommander</artifactId>
            <version>${version.jcommander}</version>
        </dependency>

        <!-- TEST Scoped Dependencies -->
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>3.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!--
            Don't use this profile when deploying JARs to Nexus; this is only useful for localhost secret encryption workflows
            -->
            <id>executable-jar</id>
            <build>
                <plugins>
                   <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>${version.maven.shade}</version>
                        <configuration>
                            <createDependencyReducedPom>true</createDependencyReducedPom>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <transformers>
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                            <mainClass>com.washingtonpost.dw.auth.encryptor.JasyptEncryptor</mainClass>
                                        </transformer>
                                    </transformers>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
my about me 201d18 project

Driver: Christina Lee
Navigator: David Cole


text:
import os
import shutil
import stat
import unittest

from common import TestCase
import pyuv

# Make stat return integers
try:
    os.stat_float_times(False)
except AttributeError:
    pass
pyuv.fs.stat_float_times(False)

BAD_FILE = 'test_file_bad'
TEST_FILE = 'test_file_1234'
TEST_FILE2 = 'test_file_1234_2'
TEST_LINK = 'test_file_1234_link'
TEST_DIR = 'test-dir'
TEST_DIR2 = 'test-dir_2'
BAD_DIR = 'test-dir-bad'
MAX_INT32_VALUE = 2 ** 31 - 1
OFFSET_VALUE = MAX_INT32_VALUE if not os.name == 'nt' else 2 ** 8 - 1

class FileTestCase(TestCase):

    TEST_FILE_CONTENT = 'test'

    def setUp(self):
        super(FileTestCase, self).setUp()
        with open(TEST_FILE, 'w') as f:
            f.write(self.TEST_FILE_CONTENT)

    def tearDown(self):
        try:
            os.remove(TEST_FILE)
        except OSError:
            pass
        super(FileTestCase, self).tearDown()

class FSTestRequestDict(FileTestCase):

    def stat_cb(self, req):
        self.errorno = req.error
        self.assertEqual(req.test, 'test123')

    def test_request_dict(self):
        self.errorno = None
        req = pyuv.fs.stat(self.loop, TEST_FILE, self.stat_cb)
        req.test = 'test123'
        self.loop.run()
        self.assertEqual(self.errorno, None)

class FSTestStat(FileTestCase):

    def stat_cb(self, req):
        self.errorno = req.error

    def test_stat_error(self):
        self.errorno = None
        pyuv.fs.stat(self.loop, BAD_FILE, self.stat_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def test_stat(self):
        self.errorno = None
        pyuv.fs.stat(self.loop, TEST_FILE, self.stat_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

    def test_stat_sync(self):
        self.stat_data = pyuv.fs.stat(self.loop, TEST_FILE)
        self.assertNotEqual(self.stat_data, None)

    def test_stat_error_sync(self):
        try:
            pyuv.fs.stat(self.loop, BAD_FILE)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestLstat(FileTestCase):

    def setUp(self):
        super(FSTestLstat, self).setUp()
        try:
            pyuv.fs.symlink(self.loop, TEST_FILE, TEST_LINK, 0)
        except pyuv.error.FSError as e:
            if e.args[0] == pyuv.errno.UV_EPERM:
                raise unittest.SkipTest("Symlinks not permitted")

    def tearDown(self):
        try:
            os.remove(TEST_LINK)
        except OSError:
            pass
        super(FSTestLstat, self).tearDown()

    def stat_cb(self, req):
        self.errorno = req.error

    def test_lstat(self):
        self.errorno = None
        pyuv.fs.lstat(self.loop, TEST_LINK, self.stat_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

class FSTestFstat(FileTestCase):

    def fstat_cb(self, req):
        self.errorno = req.error

    def test_fstat(self):
        self.errorno = None
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.fstat(self.loop, fd, self.fstat_cb)
        self.loop.run()
        pyuv.fs.close(self.loop, fd)
        self.assertEqual(self.errorno, None)

    def test_fstat_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        self.stat_data = pyuv.fs.fstat(self.loop, fd)
        pyuv.fs.close(self.loop, fd)
        self.assertNotEqual(self.stat_data, None)

class FSTestUnlink(FileTestCase):

    def bad_unlink_cb(self, req):
        self.errorno = req.error

    def test_bad_unlink(self):
        self.errorno = None
        pyuv.fs.unlink(self.loop, BAD_FILE, self.bad_unlink_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def unlink_cb(self, req):
        self.errorno = req.error

    def test_unlink(self):
        self.errorno = None
        pyuv.fs.unlink(self.loop, TEST_FILE, self.unlink_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

    def test_unlink_sync(self):
        pyuv.fs.unlink(self.loop, TEST_FILE)

    def test_unlink_error_sync(self):
        try:
            pyuv.fs.unlink(self.loop, BAD_FILE)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestMkdir(TestCase):

    def setUp(self):
        super(FSTestMkdir, self).setUp()
        os.mkdir(BAD_DIR, 0o755)

    def tearDown(self):
        os.rmdir(BAD_DIR)
        try:
            os.rmdir(TEST_DIR)
        except OSError:
            pass
        super(FSTestMkdir, self).tearDown()

    def mkdir_cb(self, req):
        self.errorno = req.error

    def test_bad_mkdir(self):
        self.errorno = None
        pyuv.fs.mkdir(self.loop, BAD_DIR, 0o755, self.mkdir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_EEXIST)

    def test_mkdir(self):
        self.errorno = None
        pyuv.fs.mkdir(self.loop, TEST_DIR, 0o755, self.mkdir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertTrue(os.path.isdir(TEST_DIR))

    def test_mkdir_sync(self):
        pyuv.fs.mkdir(self.loop, TEST_DIR, 0o755)
        self.assertTrue(os.path.isdir(TEST_DIR))

    def test_mkdir_error_sync(self):
        try:
            pyuv.fs.mkdir(self.loop, BAD_DIR, 0o755)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_EEXIST)

class FSTestRmdir(TestCase):

    def setUp(self):
        super(FSTestRmdir, self).setUp()
        os.mkdir(TEST_DIR, 0o755)

    def tearDown(self):
        try:
            os.rmdir(TEST_DIR)
        except OSError:
            pass
        super(FSTestRmdir, self).tearDown()

    def rmdir_cb(self, req):
        self.errorno = req.error

    def test_bad_rmdir(self):
        self.errorno = None
        pyuv.fs.rmdir(self.loop, BAD_DIR, self.rmdir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def test_rmdir(self):
        self.errorno = None
        pyuv.fs.rmdir(self.loop, TEST_DIR, self.rmdir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertFalse(os.path.isdir(TEST_DIR))

    def test_rmdir_sync(self):
        pyuv.fs.rmdir(self.loop, TEST_DIR)
        self.assertFalse(os.path.isdir(TEST_DIR))

    def test_rmdir_error_sync(self):
        try:
            pyuv.fs.rmdir(self.loop, BAD_DIR)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestRename(FileTestCase):

    def tearDown(self):
        try:
            os.remove(TEST_FILE2)
        except OSError:
            pass
        super(FSTestRename, self).tearDown()

    def rename_cb(self, req):
        self.errorno = req.error

    def test_rename(self):
        self.errorno = None
        pyuv.fs.rename(self.loop, TEST_FILE, TEST_FILE2, self.rename_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertFalse(os.path.exists(TEST_FILE))
        self.assertTrue(os.path.exists(TEST_FILE2))

    def test_rename_sync(self):
        pyuv.fs.rename(self.loop, TEST_FILE, TEST_FILE2)
        self.assertFalse(os.path.exists(TEST_FILE))
        self.assertTrue(os.path.exists(TEST_FILE2))

class FSTestChmod(FileTestCase):

    def chmod_cb(self, req):
        self.errorno = req.error

    def test_chmod(self):
        self.errorno = None
        pyuv.fs.chmod(self.loop, TEST_FILE, 0o777, self.chmod_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        mode = os.stat(TEST_FILE).st_mode
        self.assertTrue(bool(mode & stat.S_IRWXU) and bool(mode & stat.S_IRWXG) and bool(mode & stat.S_IRWXO))

    def test_chmod_sync(self):
        pyuv.fs.chmod(self.loop, TEST_FILE, 0o777)
        mode = os.stat(TEST_FILE).st_mode
        self.assertTrue(bool(mode & stat.S_IRWXU) and bool(mode & stat.S_IRWXG) and bool(mode & stat.S_IRWXO))

class FSTestFchmod(FileTestCase):

    def fchmod_cb(self, req):
        self.errorno = req.error

    def test_fchmod(self):
        self.errorno = None
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD | stat.S_IWRITE)
        pyuv.fs.fchmod(self.loop, fd, 0o777, self.fchmod_cb)
        self.loop.run()
        pyuv.fs.close(self.loop, fd)
        self.assertEqual(self.errorno, None)
        mode = os.stat(TEST_FILE).st_mode
        self.assertTrue(bool(mode & stat.S_IRWXU) and bool(mode & stat.S_IRWXG) and bool(mode & stat.S_IRWXO))

    def test_fchmod_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD | stat.S_IWRITE)
        pyuv.fs.fchmod(self.loop, fd, 0o777)
        pyuv.fs.close(self.loop, fd)
        mode = os.stat(TEST_FILE).st_mode
        self.assertTrue(bool(mode & stat.S_IRWXU) and bool(mode & stat.S_IRWXG) and bool(mode & stat.S_IRWXO))

class FSTestLink(FileTestCase):

    def tearDown(self):
        os.remove(TEST_LINK)
        super(FSTestLink, self).tearDown()

    def link_cb(self, req):
        self.errorno = req.error

    def test_link(self):
        self.errorno = None
        pyuv.fs.link(self.loop, TEST_FILE, TEST_LINK, self.link_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertEqual(os.stat(TEST_FILE).st_ino, os.stat(TEST_LINK).st_ino)

    def test_link_sync(self):
        pyuv.fs.link(self.loop, TEST_FILE, TEST_LINK)
        self.assertEqual(os.stat(TEST_FILE).st_ino, os.stat(TEST_LINK).st_ino)

class FSTestSymlink(FileTestCase):

    def tearDown(self):
        try:
            os.remove(TEST_LINK)
        except OSError:
            pass
        super(FSTestSymlink, self).tearDown()

    def symlink_cb(self, req):
        self.errorno = req.error

    def test_symlink(self):
        self.errorno = None
        pyuv.fs.symlink(self.loop, TEST_FILE, TEST_LINK, 0, self.symlink_cb)
        self.loop.run()
        if self.errorno == pyuv.errno.UV_EPERM:
            raise unittest.SkipTest("Symlinks not permitted")
        self.assertEqual(self.errorno, None)
        self.assertTrue(os.stat(TEST_LINK).st_mode & stat.S_IFLNK)

    def test_symlink_sync(self):
        try:
            pyuv.fs.symlink(self.loop, TEST_FILE, TEST_LINK, 0)
        except pyuv.error.FSError as e:
            if e.args[0] == pyuv.errno.UV_EPERM:
                raise unittest.SkipTest("Symlinks not permitted")
        self.assertTrue(os.stat(TEST_LINK).st_mode & stat.S_IFLNK)

class FSTestReadlink(FileTestCase):

    def setUp(self):
        super(FSTestReadlink, self).setUp()
        try:
            pyuv.fs.symlink(self.loop, TEST_FILE, TEST_LINK, 0)
        except pyuv.error.FSError as e:
            if e.args[0] == pyuv.errno.UV_EPERM:
                raise unittest.SkipTest("Symlinks not permitted")

    def tearDown(self):
        try:
            os.remove(TEST_LINK)
        except OSError:
            pass
        super(FSTestReadlink, self).tearDown()

    def readlink_cb(self, req):
        self.errorno = req.error
        self.link_path = req.result

    def test_readlink(self):
        self.errorno = None
        self.link_path = None
        pyuv.fs.readlink(self.loop, TEST_LINK, self.readlink_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertEqual(self.link_path, TEST_FILE)

    def test_readlink_sync(self):
        self.link_path = pyuv.fs.readlink(self.loop, TEST_LINK)
        self.assertEqual(self.link_path, TEST_FILE)

class FSTestChown(FileTestCase):

    def chown_cb(self, req):
        self.errorno = req.error

    def test_chown(self):
        self.errorno = None
        pyuv.fs.chown(self.loop, TEST_FILE, -1, -1, self.chown_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

    def test_chown_sync(self):
        pyuv.fs.chown(self.loop, TEST_FILE, -1, -1)

class FSTestFchown(FileTestCase):

    def fchown_cb(self, req):
        self.errorno = req.error

    def test_fchown(self):
        self.errorno = None
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD | stat.S_IWRITE)
        pyuv.fs.fchown(self.loop, fd, -1, -1, self.fchown_cb)
        self.loop.run()
        pyuv.fs.close(self.loop, fd)
        self.assertEqual(self.errorno, None)

    def test_fchown_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD | stat.S_IWRITE)
        pyuv.fs.fchown(self.loop, fd, -1, -1)
        pyuv.fs.close(self.loop, fd)

class FSTestOpen(TestCase):

    def setUp(self):
        super(FSTestOpen, self).setUp()
        try:
            os.remove(TEST_FILE)
        except OSError:
            pass

    def tearDown(self):
        try:
            os.remove(TEST_FILE)
        except OSError:
            pass
        super(FSTestOpen, self).tearDown()

    def close_cb(self, req):
        self.errorno = req.error

    def open_cb(self, req):
        fd = req.result
        self.assertNotEqual(fd, None)
        self.assertEqual(req.error, None)
        pyuv.fs.close(self.loop, fd, self.close_cb)

    def test_open_create(self):
        self.errorno = None
        pyuv.fs.open(self.loop, TEST_FILE, os.O_WRONLY|os.O_CREAT, stat.S_IREAD|stat.S_IWRITE, self.open_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

    def open_noent_cb(self, req):
        self.fd = req.result
        self.errorno = req.error

    def test_open_noent(self):
        self.fd = None
        self.errorno = None
        pyuv.fs.open(self.loop, BAD_FILE, os.O_RDONLY, 0, self.open_noent_cb)
        self.loop.run()
        self.assertEqual(self.fd, None)
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def test_open_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.close(self.loop, fd)

    def test_open_error_sync(self):
        try:
            pyuv.fs.open(self.loop, BAD_FILE, os.O_RDONLY, 0)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestRead(FileTestCase):

    TEST_FILE_CONTENT = 'test1234567890'

    def read_cb(self, req):
        self.errorno = req.error
        self.data = req.result
        pyuv.fs.close(self.loop, self.fd)

    def test_read(self):
        self.data = None
        self.errorno = None
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDONLY, stat.S_IREAD)
        pyuv.fs.read(self.loop, self.fd, 4, -1, self.read_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertEqual(self.data, b'test')

    def test_read_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDONLY, stat.S_IREAD)
        self.data = pyuv.fs.read(self.loop, fd, 4, -1)
        pyuv.fs.close(self.loop, fd)
        self.assertEqual(self.data, b'test')

    def test_read_offset(self):
        with open(TEST_FILE, 'w') as f:
            f.seek(OFFSET_VALUE)
            f.write('test1234567890')
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDONLY, stat.S_IREAD)
        data = pyuv.fs.read(self.loop, fd, 4, OFFSET_VALUE + 4)
        pyuv.fs.close(self.loop, fd)
        self.assertEqual(data, b'1234')

class FSTestWrite(TestCase):

    def setUp(self):
        super(FSTestWrite, self).setUp()
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, stat.S_IWRITE|stat.S_IREAD)

    def tearDown(self):
        os.remove(TEST_FILE)
        super(FSTestWrite, self).tearDown()

    def write_cb(self, req):
        pyuv.fs.close(self.loop, self.fd)
        self.bytes_written = req.result
        self.errorno = req.error

    def test_write(self):
        self.bytes_written = None
        self.errorno = None
        pyuv.fs.write(self.loop, self.fd, b"TEST", -1, self.write_cb)
        self.loop.run()
        self.assertEqual(self.bytes_written, 4)
        self.assertEqual(self.errorno, None)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "TEST")

    def test_write_null(self):
        self.bytes_written = None
        self.errorno = None
        pyuv.fs.write(self.loop, self.fd, b"TES\x00T", -1, self.write_cb)
        self.loop.run()
        self.assertEqual(self.bytes_written, 5)
        self.assertEqual(self.errorno, None)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "TES\x00T")

    def test_write_sync(self):
        self.bytes_written = pyuv.fs.write(self.loop, self.fd, b"TEST", -1)
        pyuv.fs.close(self.loop, self.fd)
        self.assertEqual(self.bytes_written, 4)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "TEST")

    def test_write_offset(self):
        offset = OFFSET_VALUE + 4
        self.bytes_written = pyuv.fs.write(self.loop, self.fd, b"TEST", offset)
        pyuv.fs.close(self.loop, self.fd)
        with open(TEST_FILE, 'r') as fobj:
            fobj.seek(offset)
            self.assertEqual(fobj.read(), "TEST")

class FSTestFsync(TestCase):

    def write_cb(self, req):
        self.assertEqual(req.result, 4)
        self.assertEqual(req.error, None)
        pyuv.fs.fdatasync(self.loop, self.fd, self.fdatasync_cb)

    def fdatasync_cb(self, req):
        self.assertEqual(req.error, None)
        pyuv.fs.fsync(self.loop, self.fd, self.fsync_cb)

    def fsync_cb(self, req):
        self.assertEqual(req.error, None)

    def test_fsync(self):
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR|os.O_CREAT|os.O_TRUNC, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.write(self.loop, self.fd, b"TEST", -1, self.write_cb)
        self.loop.run()
        pyuv.fs.close(self.loop, self.fd)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "TEST")

    def test_fsync_sync(self):
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR|os.O_CREAT|os.O_TRUNC, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.write(self.loop, self.fd, b"TEST", -1)
        pyuv.fs.fdatasync(self.loop, self.fd)
        pyuv.fs.fsync(self.loop, self.fd)
        pyuv.fs.close(self.loop, self.fd)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "TEST")

class FSTestFtruncate(FileTestCase):

    TEST_FILE_CONTENT = "test-data"

    def ftruncate_cb(self, req):
        self.errorno = req.error
        pyuv.fs.close(self.loop, self.fd)

    def test_ftruncate1(self):
        self.errorno = None
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.ftruncate(self.loop, self.fd, 4, self.ftruncate_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "test")

    def test_ftruncate2(self):
        self.errorno = None
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.ftruncate(self.loop, self.fd, 0, self.ftruncate_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "")

    def test_ftruncate_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.ftruncate(self.loop, fd, 0)
        pyuv.fs.close(self.loop, fd)
        with open(TEST_FILE, 'r') as fobj:
            self.assertEqual(fobj.read(), "")

class FSTestScandir(TestCase):

    def setUp(self):
        super(FSTestScandir, self).setUp()
        os.mkdir(TEST_DIR, 0o755)
        os.mkdir(os.path.join(TEST_DIR, TEST_DIR2), 0o755)
        with open(os.path.join(TEST_DIR, TEST_FILE), 'w') as f:
            f.write('test')
        with open(os.path.join(TEST_DIR, TEST_FILE2), 'w') as f:
            f.write('test')

    def tearDown(self):
        shutil.rmtree(TEST_DIR)
        super(FSTestScandir, self).tearDown()

    def scandir_cb(self, req):
        self.errorno = req.error
        self.files = req.result

    def test_bad_scandir(self):
        self.errorno = None
        self.files = None
        pyuv.fs.scandir(self.loop, BAD_DIR, self.scandir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def test_scandir(self):
        self.errorno = None
        self.files = None
        pyuv.fs.scandir(self.loop, TEST_DIR, self.scandir_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertTrue(TEST_FILE in [f.name for f in self.files])
        self.assertTrue(TEST_FILE2 in [f.name for f in self.files])
        self.assertTrue(TEST_DIR2 in [f.name for f in self.files])

    def test_scandir_sync(self):
        self.files = pyuv.fs.scandir(self.loop, TEST_DIR)
        self.assertNotEqual(self.files, None)
        self.assertTrue(TEST_FILE in [f.name for f in self.files])
        self.assertTrue(TEST_FILE2 in [f.name for f in self.files])
        self.assertTrue(TEST_DIR2 in [f.name for f in self.files])

    def test_scandir_error_sync(self):
        try:
            pyuv.fs.scandir(self.loop, BAD_DIR)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestSendfile(TestCase):

    def setUp(self):
        super(FSTestSendfile, self).setUp()
        with open(TEST_FILE, 'w') as f:
            f.write("begin\n")
            os.lseek(f.fileno(), 65536, os.SEEK_CUR)
            f.write("end\n")
            f.flush()

    def tearDown(self):
        os.remove(TEST_FILE)
        os.remove(TEST_FILE2)
        super(FSTestSendfile, self).tearDown()

    def sendfile_cb(self, req):
        self.bytes_written = req.result
        self.errorno = req.error

    def test_sendfile(self):
        self.result = None
        self.errorno = None
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        fd2 = pyuv.fs.open(self.loop, TEST_FILE2, os.O_RDWR|os.O_CREAT, stat.S_IREAD|stat.S_IWRITE)
        pyuv.fs.sendfile(self.loop, fd2, fd, 0, 131072, self.sendfile_cb)
        self.loop.run()
        pyuv.fs.close(self.loop, fd)
        pyuv.fs.close(self.loop, fd2)
        self.assertEqual(self.errorno, None)
        with open(TEST_FILE, 'r') as fobj1:
            with open(TEST_FILE2, 'r') as fobj2:
                self.assertEqual(fobj1.read(), fobj2.read())

    def test_sendfile_sync(self):
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        fd2 = pyuv.fs.open(self.loop, TEST_FILE2, os.O_RDWR|os.O_CREAT, stat.S_IREAD|stat.S_IWRITE)
        self.bytes_written = pyuv.fs.sendfile(self.loop, fd2, fd, 0, 131072)
        pyuv.fs.close(self.loop, fd)
        pyuv.fs.close(self.loop, fd2)
        with open(TEST_FILE, 'r') as fobj1:
            with open(TEST_FILE2, 'r') as fobj2:
                self.assertEqual(fobj1.read(), fobj2.read())

    def test_sendfile_offset(self):
        offset = OFFSET_VALUE + 1
        with open(TEST_FILE, 'w') as f:
            f.seek(offset)
            f.write("test")
            f.flush()
        fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IREAD|stat.S_IWRITE)
        fd2 = pyuv.fs.open(self.loop, TEST_FILE2, os.O_RDWR|os.O_CREAT, stat.S_IREAD|stat.S_IWRITE)
        self.bytes_written = pyuv.fs.sendfile(self.loop, fd2, fd, offset, 4)
        pyuv.fs.close(self.loop, fd)
        pyuv.fs.close(self.loop, fd2)
        with open(TEST_FILE, 'r') as fobj1:
            fobj1.seek(offset)
            with open(TEST_FILE2, 'r') as fobj2:
                self.assertEqual(fobj1.read(), fobj2.read())

class FSTestUtime(FileTestCase):

    def setUp(self):
        super(FSTestUtime, self).setUp()
        self.fd = None

    def utime_cb(self, req):
        self.errorno = req.error
        if self.fd is not None:
            pyuv.fs.close(self.loop, self.fd)

    def test_utime(self):
        self.errorno = None
        atime = mtime = 400497753
        pyuv.fs.utime(self.loop, TEST_FILE, atime, mtime, self.utime_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        s = os.stat(TEST_FILE)
        self.assertEqual(s.st_atime, atime)
        self.assertEqual(s.st_mtime, mtime)

    def test_futime(self):
        self.errorno = None
        atime = mtime = 400497753
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IWRITE|stat.S_IREAD)
        pyuv.fs.futime(self.loop, self.fd, atime, mtime, self.utime_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        s = os.stat(TEST_FILE)
        self.assertTrue(s.st_atime == atime and s.st_mtime == mtime)

    def test_utime_sync(self):
        atime = mtime = 400497753
        pyuv.fs.utime(self.loop, TEST_FILE, atime, mtime)
        s = os.stat(TEST_FILE)
        self.assertEqual(s.st_atime, atime)
        self.assertEqual(s.st_mtime, mtime)

    def test_futime_sync(self):
        atime = mtime = 400497753
        self.fd = pyuv.fs.open(self.loop, TEST_FILE, os.O_RDWR, stat.S_IWRITE|stat.S_IREAD)
        pyuv.fs.futime(self.loop, self.fd, atime, mtime)
        pyuv.fs.close(self.loop, self.fd)
        s = os.stat(TEST_FILE)
        self.assertEqual(s.st_atime, atime)
        self.assertEqual(s.st_mtime, mtime)

class FSTestAccess(TestCase):

    def setUp(self):
        super(FSTestAccess, self).setUp()
        with open(TEST_FILE, 'w') as f:
            f.write("test")

    def tearDown(self):
        try:
            os.remove(TEST_FILE)
        except OSError:
            pass
        super(FSTestAccess, self).tearDown()

    def access_cb(self, req):
        self.errorno = req.error

    def test_bad_access(self):
        self.errorno = None
        pyuv.fs.access(self.loop, BAD_FILE, os.F_OK, self.access_cb)
        self.loop.run()
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

    def test_access(self):
        self.errorno = None
        pyuv.fs.access(self.loop, TEST_FILE, os.F_OK, self.access_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)

    def test_access_sync(self):
        pyuv.fs.access(self.loop, TEST_FILE, os.F_OK)

    def test_access_error_sync(self):
        try:
            pyuv.fs.access(self.loop, BAD_FILE, os.F_OK)
        except pyuv.error.FSError as e:
            self.errorno = e.args[0]
        else:
            self.errorno = None
        self.assertEqual(self.errorno, pyuv.errno.UV_ENOENT)

class FSTestRealpath(TestCase):

    def realpath_cb(self, req):
        self.errorno = req.error
        self.result = req.result

    def test_realpath(self):
        self.errorno = None
        self.result = None
        pyuv.fs.realpath(self.loop, '.', self.realpath_cb)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertNotEqual(self.result, '.')

    def test_realpath_sync(self):
        result = pyuv.fs.realpath(self.loop, '.')
        self.assertNotEqual(result, '.')

class FSEventTestBasic(FileTestCase):

    def tearDown(self):
        try:
            os.remove(TEST_FILE2)
        except OSError:
            pass
        super(FSEventTestBasic, self).tearDown()

    def on_fsevent_cb(self, handle, filename, events, errorno):
        handle.stop()
        handle.close()
        self.filename = filename
        self.events = events
        self.errorno = errorno

    def timer_cb(self, timer):
        timer.close()
        os.rename(TEST_FILE, TEST_FILE2)

    def test_fsevent_basic(self):
        self.errorno = None
        self.events = None
        self.filename = None
        fs_event = pyuv.fs.FSEvent(self.loop)
        fs_event.start(TEST_FILE, 0, self.on_fsevent_cb)
        self.assertEqual(fs_event.path, TEST_FILE)
        timer = pyuv.Timer(self.loop)
        timer.start(self.timer_cb, 1, 0)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertTrue(self.filename in (None, TEST_FILE, TEST_FILE2))
        self.assertTrue(self.events in (pyuv.fs.UV_CHANGE, pyuv.fs.UV_RENAME))

class FSEventTest(FileTestCase):

    def setUp(self):
        super(FSEventTest, self).setUp()
        os.mkdir(TEST_DIR, 0o755)
        with open(os.path.join(TEST_DIR, TEST_FILE), 'w') as f:
            f.write("test")

    def tearDown(self):
        shutil.rmtree(TEST_DIR)
        try:
            os.remove(TEST_FILE2)
        except OSError:
            pass
        super(FSEventTest, self).tearDown()

    def on_fsevent_cb(self, handle, filename, events, errorno):
        handle.stop()
        handle.close()
        self.filename = filename
        self.events = events
        self.errorno = errorno

    def timer_cb2(self, timer):
        timer.close()
        os.rename(os.path.join(TEST_DIR, TEST_FILE), os.path.join(TEST_DIR, TEST_FILE2))

    def test_fsevent_dir(self):
        self.errorno = None
        self.events = None
        self.filename = None
        fs_event = pyuv.fs.FSEvent(self.loop)
        fs_event.start(TEST_DIR, 0, self.on_fsevent_cb)
        timer = pyuv.Timer(self.loop)
        timer.start(self.timer_cb2, 1, 0)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertTrue(self.filename == None or self.filename == TEST_FILE)
        self.assertTrue(self.events & pyuv.fs.UV_RENAME)

    def timer_cb3(self, timer):
        timer.close()
        os.utime(os.path.join(TEST_DIR, TEST_FILE), None)

    def test_fsevent_nrefile(self):
        self.errorno = None
        self.events = None
        self.filename = None
        fs_event = pyuv.fs.FSEvent(self.loop)
        fs_event.start(os.path.join(TEST_DIR, TEST_FILE), 0, self.on_fsevent_cb)
        timer = pyuv.Timer(self.loop)
        timer.start(self.timer_cb3, 1, 0)
        self.loop.run()
        self.assertEqual(self.errorno, None)
        self.assertTrue(self.filename == None or self.filename == TEST_FILE)
        self.assertTrue(self.events & pyuv.fs.UV_CHANGE)

class FSPollTest(TestCase):

    def tearDown(self):
        try:
            os.remove(TEST_FILE)
        except OSError:
            pass
        super(FSPollTest, self).tearDown()

    def _touch_file(self):
        with open(TEST_FILE, 'w+') as f:
            self.count += 1
            for i in range(self.count+1):
                f.write('*')

    def on_timer(self, timer):
        self._touch_file()

    def on_fspoll(self, handle, prev_stat, curr_stat, error):
        if self.poll_cb_called == 0:
            self.assertEqual(error, pyuv.errno.UV_ENOENT)
            self._touch_file()
        elif self.poll_cb_called == 1:
            self.timer.start(self.on_timer, 0.02, 0.0)
        elif self.poll_cb_called == 2:
            self.timer.start(self.on_timer, 0.2, 0.0)
        elif self.poll_cb_called == 3:
            os.remove(TEST_FILE)
        elif self.poll_cb_called == 4:
            self.assertEqual(error, pyuv.errno.UV_ENOENT)
            self.fs_poll.close()
            self.timer.close()
        else:
            self.fail('This should not happen')
        self.poll_cb_called += 1

    def test_fspoll1(self):
        self.count = 0
        self.poll_cb_called = 0
        self.timer = pyuv.Timer(self.loop)
        self.fs_poll = pyuv.fs.FSPoll(self.loop)
        self.fs_poll.start(TEST_FILE, 0.1, self.on_fspoll)
        self.assertEqual(self.fs_poll.path, TEST_FILE)
        self.loop.run()
        self.assertEqual(self.poll_cb_called, 5)

if __name__ == '__main__':
    unittest.main(verbosity=2)


text:
(function(){
'use strict';

angular.module('coding.coding')
	.controller('CodingCodingCtrl', CodingCodingCtrl)
	.controller('CodingSidebarCtrl', CodingSidebarCtrl)
	.controller('CodingMainContentCtrl', CodingMainContentCtrl)
	.controller('CommentCodeInstanceCtrl', CommentCodeInstanceCtrl)
	.controller('SubmissionCodeInstanceCtrl', SubmissionCodeInstanceCtrl)
	.controller('CommentCodeInstanceListCtrl', CommentCodeInstanceListCtrl);

CodingCodingCtrl.$inject = [
	'$stateParams',
	'$scope',
	'$rootScope',
	'$document',
	'$anchorScroll',
	'$location',
	'ResourceHelperService',
	'Comment',
	'Submission',
	'CommentCodeInstance',
	'CodeableCommentModel',
	'AssignmentModel'
];
function CodingCodingCtrl(
		$stateParams,
		$scope,
		$rootScope,
		$document,
		$anchorScroll,
		$location,
		ResourceHelperService,
		Comment,
		Submission,
		CommentCodeInstance,
		CodeableCommentModel,
		AssignmentModel) {
	var vm = this;

	vm.rootCommentId = $stateParams.id;
	vm.assignmentId = $stateParams.aid;
	vm.assignment = new AssignmentModel();
	vm.nextAssignment = null;
	vm.previousAssignment = null;
	vm.submission = null;
	vm.loading_progress = {
		count: null,
		total: null
	}

	//console.dir(this);
	//console.dir($scope);

	vm.commentsList = [];
	vm.rootComment = new CodeableCommentModel();
	vm.selectedIndex = 0;
	vm.codeInstances = [];
	vm.codes = [];
	vm.codeKeyMap = {};
	vm.selectedCodeHiearachy = [];

	/*
	*
	*
	*
	*/
	vm.toggleCode = function(code) {
		if(vm.selectedIndex >= 0) {
			var comment = getSelectedComment();

			comment.codeInstanceList.toggleCode(comment.data.id, code, vm.assignment.data.id);

			buildHierarchicalCodeList();
		} else {
			// submission
		}
	}

	vm.expandComment = function() {
		var node = getSelectedComment();
		if(node != null) {
			node.expanded = true;
		}
	}

	vm.collapseComment = function() {
		var node = getSelectedComment();
		if(node != null) {
			node.expanded = false;
		}
	}

	function getSelectedComment() {
		if(vm.selectedIndex >= 0 &&
				vm.selectedIndex < vm.commentsList.length) {
			return vm.commentsList[vm.selectedIndex];
		}
		return null;
	}

	function joinCodes() {
		for(var i = 0; i < vm.assignment.data.code_schemes.length; i++) {
			var scheme = vm.assignment.data.code_schemes[i];

			// append them to our list
			Array.prototype.push.apply(vm.codes, scheme.code_set);
		}
	}

	function createKeyMap() {
		vm.codes.forEach(function(d){
			vm.codeKeyMap[d.key.charCodeAt()] = d;
		})
	}

	function checkCodeHotKeys(event) {
		var key = event.key || event.keyCode;
		if(key in vm.codeKeyMap) {
			vm.toggleCode(vm.codeKeyMap[key].id);
		}
	}

	function buildHierarchicalCodeList() {
		var curNode = vm.commentsList[vm.selectedIndex];

		vm.selectedCodeHiearachy = [];
		while(curNode != null) {
			if(curNode.codeInstanceList != null && curNode.codeInstanceList.instances.length > 0) {
				var tmp = curNode.codeInstanceList.instances.slice(0);
				vm.selectedCodeHiearachy.unshift(tmp);
			} else {
				vm.selectedCodeHiearachy.unshift([]);
			}

			curNode = curNode.parent;
		}

	}

	/*
	* onKeyDown
	*
	*
	*/
	vm.onKeyDown = function(event) {
		// handles keydown events
		// must be wrapped in an apply because the way its handled.
		$scope.$apply(function(){
			if($rootScope.block_key_handler !== true) {
				var key = event.key || event.keyCode;

				switch(key) {
					case 221: vm.selectNext(); event.preventDefault(); break;
					case 219: vm.selectPrevious(); event.preventDefault(); break;
					case 187: vm.expandComment(); event.preventDefault(); break;
					case 189: vm.collapseComment(); event.preventDefault(); break;
					default:
						checkCodeHotKeys(event);
						console.log("keydown: ");
						console.dir(event);
						break;
				}
			}
		})
	}

	/*
	* requestSubmission
	*
	*
	*/
	function requestSubmission(id) {
		vm.submission = Submission.get({id:vm.submission_id});

		return vm.submission.$promise;
	}

	/*
	* setSelection
	*
	*
	*/
	function setSelection(idx, value) {
		if(idx == -1) {
			vm.submission.selected = value;
			return vm.submission.id;
		} else if(vm.commentsList && vm.commentsList.length > idx) {
			vm.commentsList[idx].selected = value;
			return vm.commentsList[idx].data.id;
		}
	}

	/*
	* changeSelection
	*
	*
	*/
	vm.changeSelection = function(idx, force) {
		if(idx != vm.selectedIndex || force) {

			// unselect old item
			setSelection(vm.selectedIndex, false);

			// select new item
			vm.selectedIndex = idx;
			var id = setSelection(vm.selectedIndex, true);

			buildHierarchicalCodeList();

			$location.hash(id);
			$anchorScroll.yOffset = 200;
			$anchorScroll();
		}
	}

	/*
	* selectId
	*
	*
	*/
	vm.selectId = function(id) {
		var idx = null;
		if(id == vm.submission.id) {
			idx = -1;
		} else {
			// try to find the id
			for(var i = 0; i < vm.commentsList.length; i++) {
				if(vm.commentsList[i].data.id == id) {
					idx = i;
					break;
				}
			}
		}

		vm.changeSelection(idx);
	}

	/*
	* onClick
	*
	*
	*/
	vm.onClick = function($event, id) {
		var el = angular.element($event.srcElement);
		while(el.length > 0) {
			var tagName = el[0].tagName.toLowerCase();

			if(tagName == "a" || tagName == "input" || tagName == "button") return;
			if(el.hasClass("comment")) {
				var id = el.attr('id');
				if(id) {
					vm.selectId(id);
					return;
				}
			}
			if(el.parent() === undefined || el.parent() === null || el.parent() == document) {
				return;
			}
			el = angular.element(el.parent());
		}
		//vm.selectId(id);
	}

	function getNext(node) {
		if(node.children.length > 0) {
			return node.children[0];
		}

		if(node.nextSibling != null) {
			return node.nextSibling;
		}

		// find next parent
		while(node.parent != null) {
			if(node.parent != null && node.parent.nextSibling != null) {
				return node.parent.nextSibling;
			}
			// step up again
			node = node.parent;
		}

		return null;
	}

	function getPrevious(node) {
		if(node.prevSibling != null) {
			// move to previous node
			node = node.prevSibling;

			// if there are children, walk downwards until we find a leaf
			while(node.children.length > 0) {
				node = node.children[node.children.length-1];
			}
			return node;
		}

		// find next parent
		if(node.parent != null) {
			// step up again
			return node.parent;
		}

		// we didn't find one
		return null;
	}

	/*
	* selectNext
	*
	*
	*/
	vm.selectNext = function() {
		var curNode = vm.commentsList[vm.selectedIndex];
		var nextNode = getNext(curNode);

		while(nextNode != null && !nextNode.isVisible()) {
			nextNode = getNext(nextNode);
		}

		if(nextNode) {
			vm.selectId(nextNode.data.id);
		}

	}

	/*
	* selectPrevious
	*
	*
	*/
	vm.selectPrevious = function() {
		var curNode = vm.commentsList[vm.selectedIndex];
		var prevNode = getPrevious(curNode);

		while(prevNode != null && !prevNode.isVisible()) {
			prevNode = getPrevious(prevNode);
		}

		if(prevNode) {
			vm.selectId(prevNode.data.id);
		}
	}

	/*
	* loadingFinished
	*
	*
	*/
	function loadingFinished() {
		vm.rootComment = buildCommentTree();
		buildCommentListFromTree();
		vm.changeSelection(0, true);
	}

	/*
	* init
	*
	*
	*/
	function init() {
		// start data requests

		vm.assignment.get(
			{id: vm.assignmentId}
		).$promise.then(function(data){
			// deal with the codes
			joinCodes();
			createKeyMap();

			vm.nextAssignment = vm.assignment.getNextComment(vm.rootCommentId);
			vm.prevAssignment = vm.assignment.getPreviousComment(vm.rootCommentId);

			return vm.rootComment.getEntireThread(vm.rootCommentId);
		}).then(function(data) {
			//
			vm.commentsList = vm.rootComment.commentsList;
			if(vm.commentsList && vm.commentsList.length > 0) {
				vm.submission_id = vm.commentsList[0].data.article;
				return requestSubmission();
			}
			return data;
		}).then(function(data){
			vm.changeSelection(0,true);
		})
		.catch(function(error){
			console.error("failed to load items: " + error);
		})

		// handle code toggle message
		$rootScope.$on("code:toggle", function(event, code){
			console.log("toggleCode");
			vm.toggleCode(code);
		});

		// attach hot key listener
		var $doc = angular.element(document);
		$doc.on('keydown', vm.onKeyDown);

		// make sure to remove it!
		$scope.$on("$destroy", function() {
			var $doc = angular.element(document);
			$doc.off('keydown', vm.onKeyDown);
		});
	}

	// start the ball rolling
	init();

}

CodingSidebarCtrl.$inject = ['$scope', '$rootScope', 'AssignmentModel'];
function CodingSidebarCtrl($scope, $rootScope, AssignmentModel ) {
	console.log("CodingSidebar!");

}

CodingMainContentCtrl.$inject = ['$scope'];
function CodingMainContentCtrl($scope) {
	console.log("CodingMainContent!");
}

CommentCodeInstanceListCtrl.$inject = ['$scope', 'CommentCodeInstance', 'CodeableCommentModel'];
function CommentCodeInstanceListCtrl($scope, CommentCodeInstance, CodeableCommentModel) {
	//console.log("CodeInstanceListCtrl!!");
	//console.dir($scope);
	//console.dir(this);

	var vm = this;

	vm.data = 0;

	//vm.codeInstances.control = vm;

	vm.test = new CodeableCommentModel({test: 0});

	function findInstanceById(id) {
		vm.codeInstances.forEach(function(d,i){
			if(d.id == id) {
				return d;
			}
		});

		return null;
	}

	function addCommentCodeInstance(comment, code, assignment) {
		var _assignment = assignment || null,
			ci = new CommentCodeInstance({
			comment: comment.data.id,
			code: code,
			assignment: _assignment
		})
		.$save()
		.then(function(data){
			comment.codeInstanceList.addExistingInstance(data);
		}, function(error){
			console.error(error);
		});
	}

	vm.removeCode = function($event, instance) {
		console.log("CCILC removeCode");
		console.dir(instance);

		vm.codeInstances.deleteInstance(instance);
	}
}

CommentCodeInstanceCtrl.$inject = ['$scope', 'CommentCodeInstance'];
function CommentCodeInstanceCtrl($scope, CommentCodeInstance) {
	var vm = this;

	vm.clickTest = function($event, codeid) {
		console.log("clicktest");
		console.dir($event)
		console.dir(codeid);
	}
}

SubmissionCodeInstanceCtrl.$inject = ['$scope', 'SubmissionCodeInstance'];
function SubmissionCodeInstanceCtrl($scope, SubmissionCodeInstance) {

}

})();


text:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils';
import { Observable } from 'rxjs';
import {
  AccountTwoFaSettings,
  TwoFactorAuthAccountConfig,
  TwoFactorAuthProviderType,
  TwoFactorAuthSettings
} from '@shared/models/two-factor-auth.models';
import { isDefinedAndNotNull } from '@core/utils';

@Injectable({
  providedIn: 'root'
})
export class TwoFactorAuthenticationService {

  constructor(
    private http: HttpClient
  ) {
  }

  getTwoFaSettings(config?: RequestConfig): Observable<TwoFactorAuthSettings> {
    return this.http.get<TwoFactorAuthSettings>(`/api/2fa/settings`, defaultHttpOptionsFromConfig(config));
  }

  saveTwoFaSettings(settings: TwoFactorAuthSettings, config?: RequestConfig): Observable<TwoFactorAuthSettings> {
    return this.http.post<TwoFactorAuthSettings>(`/api/2fa/settings`, settings, defaultHttpOptionsFromConfig(config));
  }

  getAvailableTwoFaProviders(config?: RequestConfig): Observable<Array<TwoFactorAuthProviderType>> {
    return this.http.get<Array<TwoFactorAuthProviderType>>(`/api/2fa/providers`, defaultHttpOptionsFromConfig(config));
  }

  generateTwoFaAccountConfig(providerType: TwoFactorAuthProviderType, config?: RequestConfig): Observable<TwoFactorAuthAccountConfig> {
    return this.http.post<TwoFactorAuthAccountConfig>(`/api/2fa/account/config/generate?providerType=${providerType}`,
      defaultHttpOptionsFromConfig(config));
  }

  getAccountTwoFaSettings(config?: RequestConfig): Observable<AccountTwoFaSettings> {
    return this.http.get<AccountTwoFaSettings>(`/api/2fa/account/settings`, defaultHttpOptionsFromConfig(config));
  }

  updateTwoFaAccountConfig(providerType: TwoFactorAuthProviderType, useByDefault: boolean,
                           config?: RequestConfig): Observable<AccountTwoFaSettings> {
    return this.http.put<AccountTwoFaSettings>(`/api/2fa/account/config?providerType=${providerType}`, {useByDefault},
      defaultHttpOptionsFromConfig(config));
  }

  submitTwoFaAccountConfig(authConfig: TwoFactorAuthAccountConfig, config?: RequestConfig): Observable<any> {
    return this.http.post(`/api/2fa/account/config/submit`, authConfig, defaultHttpOptionsFromConfig(config));
  }

  verifyAndSaveTwoFaAccountConfig(authConfig: TwoFactorAuthAccountConfig, verificationCode?: number,
                                  config?: RequestConfig): Observable<AccountTwoFaSettings> {
    let url = '/api/2fa/account/config';
    if (isDefinedAndNotNull(verificationCode)) {
      url += `?verificationCode=${verificationCode}`;
    }
    return this.http.post<AccountTwoFaSettings>(url, authConfig, defaultHttpOptionsFromConfig(config));
  }

  deleteTwoFaAccountConfig(providerType: TwoFactorAuthProviderType, config?: RequestConfig): Observable<AccountTwoFaSettings> {
    return this.http.delete<AccountTwoFaSettings>(`/api/2fa/account/config?providerType=${providerType}`,
      defaultHttpOptionsFromConfig(config));
  }

  requestTwoFaVerificationCodeSend(providerType: TwoFactorAuthProviderType, config?: RequestConfig) {
    return this.http.post(`/api/auth/2fa/verification/send?providerType=${providerType}`, defaultHttpOptionsFromConfig(config));
  }

}


text:
layout: post
title: "Subconscious Learning"
date: 2016-03-16 02:22:00
summary: I've been learning about... learning lately, specifically subconscious learning. Here's what I've found!
categories: learning
---

One of the things I've done lately is try to passively learn Morse code. I added
a bunch of custom vibrations for each letter of the alphabet to my phone, and
when I add someone to my contact book, I assign them the custom vibration. So,
as people text or call me, I'm slowly but surely learning Morse code because of
their names. Now I definitely know some letters, like J and C, a lot more than
others like Q or V. But hey, it's something!

We're all exposed to subliminal messages. Due to the massive amounts of
information we're exposed to every single day, and our limited capacity to
actively, consciously register it, there's always small changes in our minds.
But, if you're exposed to the same information again and again over time,
there's more lasting changes. So, like in my example above, I've been constantly
hearing vibrations for people every day, and the repetition has led to my
learning without my having to think about it.

When a person is stressed, they use both their conscious memory and their
subconscious memory to compensate for all of the stress. The switch from totally
conscious learning to conscious+subconscious learning is triggered by
[mineralocorticoid receptors](http://en.wikipedia.org/wiki/Mineralocorticoid_receptor),
which are released in response to stress. The switches are controlled by the
[amygdala](http://en.wikipedia.org/wiki/Amygdala), the part of the brain that's
responsible for both memory and emotional reactions. There's a really
interesting study by Schwabe, Tegenthoff, and Hoffken that talks about this. You
can read it [here](http://www.biologicalpsychiatryjournal.com/article/S0006-3223(13)00513-1/abstract).
So, it turns out that when I said that I "operate well under stress" in college,
I wasn't actually making that up!

There's probably a lot more to learn about subconscious learning. Please feel
free to send me anything you've found on the subject!


text:
package org.apache.flink.contrib.streaming.state;

import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import org.apache.flink.runtime.state.internal.InternalListState;

import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDBException;
import org.rocksdb.WriteOptions;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * {@link ListState} implementation that stores state in RocksDB.
 *
 * <p>{@link RocksDBStateBackend} must ensure that we set the
 * {@link org.rocksdb.StringAppendOperator} on the column family that we use for our state since
 * we use the {@code merge()} call.
 *
 * @param <K> The type of the key.
 * @param <N> The type of the namespace.
 * @param <V> The type of the values in the list state.
 */
public class RocksDBListState<K, N, V>
	extends AbstractRocksDBState<K, N, ListState<V>, ListStateDescriptor<V>, List<V>>
	implements InternalListState<N, V> {

	/** Serializer for the values. */
	private final TypeSerializer<V> valueSerializer;

	/**
	 * We disable writes to the write-ahead-log here. We can't have these in the base class
	 * because JNI segfaults for some reason if they are.
	 */
	private final WriteOptions writeOptions;

	/**
	 * Creates a new {@code RocksDBListState}.
	 *
	 * @param namespaceSerializer The serializer for the namespace.
	 * @param stateDesc The state identifier for the state. This contains name
	 *                     and can create a default state value.
	 */
	public RocksDBListState(ColumnFamilyHandle columnFamily,
			TypeSerializer<N> namespaceSerializer,
			ListStateDescriptor<V> stateDesc,
			RocksDBKeyedStateBackend<K> backend) {

		super(columnFamily, namespaceSerializer, stateDesc, backend);
		this.valueSerializer = stateDesc.getElementSerializer();

		writeOptions = new WriteOptions();
		writeOptions.setDisableWAL(true);
	}

	@Override
	public Iterable<V> get() {
		try {
			writeCurrentKeyWithGroupAndNamespace();
			byte[] key = keySerializationStream.toByteArray();
			byte[] valueBytes = backend.db.get(columnFamily, key);

			if (valueBytes == null) {
				return null;
			}

			ByteArrayInputStream bais = new ByteArrayInputStream(valueBytes);
			DataInputViewStreamWrapper in = new DataInputViewStreamWrapper(bais);

			List<V> result = new ArrayList<>();
			while (in.available() > 0) {
				result.add(valueSerializer.deserialize(in));
				if (in.available() > 0) {
					in.readByte();
				}
			}
			return result;
		} catch (IOException | RocksDBException e) {
			throw new RuntimeException("Error while retrieving data from RocksDB", e);
		}
	}

	@Override
	public void add(V value) throws IOException {
		try {
			writeCurrentKeyWithGroupAndNamespace();
			byte[] key = keySerializationStream.toByteArray();
			keySerializationStream.reset();
			DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(keySerializationStream);
			valueSerializer.serialize(value, out);
			backend.db.merge(columnFamily, writeOptions, key, keySerializationStream.toByteArray());

		} catch (Exception e) {
			throw new RuntimeException("Error while adding data to RocksDB", e);
		}
	}

	@Override
	public void mergeNamespaces(N target, Collection<N> sources) throws Exception {
		if (sources == null || sources.isEmpty()) {
			return;
		}

		// cache key and namespace
		final K key = backend.getCurrentKey();
		final int keyGroup = backend.getCurrentKeyGroupIndex();

		try {
			// create the target full-binary-key
			writeKeyWithGroupAndNamespace(
					keyGroup, key, target,
					keySerializationStream, keySerializationDataOutputView);
			final byte[] targetKey = keySerializationStream.toByteArray();

			// merge the sources to the target
			for (N source : sources) {
				if (source != null) {
					writeKeyWithGroupAndNamespace(
							keyGroup, key, source,
							keySerializationStream, keySerializationDataOutputView);

					byte[] sourceKey = keySerializationStream.toByteArray();
					byte[] valueBytes = backend.db.get(columnFamily, sourceKey);

					if (valueBytes != null) {
						backend.db.merge(columnFamily, writeOptions, targetKey, valueBytes);
					}
				}
			}
		}
		catch (Exception e) {
			throw new Exception("Error while merging state in RocksDB", e);
		}
	}
}


text:
@inject('module', 'scaffold.module')
@inject('actions', 'scaffold.actions')

        key }}">
            <input type="checkbox" name="collection[]" id="collection_{{ $item->key }}" value="{{ $item->key }}" class="collection-item simple">

    {{ $item['key'] }}

        <?php $locales = $item->locales->groupBy('locale');?>

        @foreach($module->activeLocales() as $locale => $title)
            <textarea name="translates[{{ $item->key }}][{{ $locale }}]" class="form-control translate-area" data-locale="{{ $locale }}"{!! $locale === app('translator')->getLocale() ? '' : ' style="display: none;"' !!}>{{ $locales->has($locale) ? $locales[$locale]->first()['value'] : null }}</textarea>
        @endforeach

        @if(count($module->activeLocales()) > 1)

                @foreach($module->activeLocales() as $locale => $title)
                    <button type="button" class="btn btn-default btn-sm{{ $locale === app('translator')->getLocale() ? ' active' : '' }}" data-locale="{{ $locale }}">{{ $title }}</button>
                @endforeach

        @endif

            @foreach($actions->actions()->authorized(auth('admin')->user(), $item) as $action)

                    {!! $action->render($item) !!}

            @endforeach


text:
/*
 * imap/util.c - misc imap utility functions
 */
#define _POSIX_C_SOURCE 200809L

#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "imap/imap.h"
#include "email/headers.h"
#include "util/list.h"

static int get_mbox_compare(const void *_mbox, const void *_name) {
	const struct mailbox *mbox = _mbox;
	const char *name = _name;
	return strcmp(mbox->name, name);
}

struct mailbox *get_mailbox(struct imap_connection *imap, const char *name) {
	int i = list_seq_find(imap->mailboxes, get_mbox_compare, name);
	if (i == -1) {
		return NULL;
	}
	return imap->mailboxes->items[i];
}

struct mailbox *get_or_make_mailbox(struct imap_connection *imap,
		const char *name) {
	struct mailbox *mbox = get_mailbox(imap, name);
	if (!mbox) {
		mbox = malloc(sizeof(struct mailbox));
		mbox->name = strdup(name);
		mbox->flags = create_list();
		mbox->messages = create_list();
		mbox->exists = mbox->unseen = mbox->recent = -1;
		list_add(imap->mailboxes, mbox);
	}
	return mbox;
}

struct mailbox_flag *mailbox_get_flag(struct imap_connection *imap,
		const char *mbox, const char *flag) {
	const struct mailbox *box = get_mailbox(imap, mbox);
	if (!box) {
		return NULL;
	}
	for (size_t i = 0; i < box->flags->length; ++i) {
		struct mailbox_flag *f = box->flags->items[i];
		if (strcasecmp(f->name, flag) == 0) {
			return f;
		}
	}
	return NULL;
}

struct mailbox_message *get_message(struct mailbox *mbox, long index) {
	struct mailbox_message *msg = NULL;
	for (size_t i = 0; i < mbox->messages->length; ++i) {
		msg = mbox->messages->items[i];
		if (msg->index == index) {
			return msg;
		}
	}
	return NULL;
}

void message_part_free(struct message_part *msg) {
	if (!msg) {
		return;
	}
	free(msg->type);
	free(msg->subtype);
	free(msg->body_id);
	free(msg->body_description);
	free(msg->body_encoding);
	free(msg->content);
	for (size_t i = 0; msg->parameters && i < msg->parameters->length; ++i) {
		struct message_parameter *param = msg->parameters->items[i];
		free(param->key);
		free(param->value);
		free(param);
	}
	list_free(msg->parameters);
	free(msg);
}

void mailbox_message_free(struct mailbox_message *msg) {
	for (size_t i = 0; msg->flags && i < msg->flags->length; ++i) {
		char *f = msg->flags->items[i];
		free(f);
	}
	list_free(msg->flags);
	for (size_t i = 0; msg->parts && i < msg->parts->length; ++i) {
		struct message_part *part = msg->parts->items[i];
		message_part_free(part);
	}
	list_free(msg->parts);
	free_headers(msg->headers);
	free(msg->internal_date);
	free(msg);
}

void mailbox_free(struct mailbox *mbox) {
	for (size_t i = 0; i < mbox->flags->length; ++i) {
		struct mailbox_flag *f = mbox->flags->items[i];
		free(f->name);
		free(f);
	}
	list_free(mbox->flags);
	for (size_t i = 0; i < mbox->messages->length; ++i) {
		struct mailbox_message *m = mbox->messages->items[i];
		mailbox_message_free(m);
	}
	list_free(mbox->messages);
	free(mbox->name);
	free(mbox);
}