text:
.. :changelog:

History
=======

1.3.3
-----

* Fix subprocess calls.

1.3.2
-----

* Jinja2 support is back.
* Many small improvements in documentation.

1.3.1
-----

* Improve exceptions hierarchy.
* Improve our sub-process calls.
* Update uglify-js documentation. Thanks to Andrey Antukh.

1.3.0
-----

* Add support Python 3, with some help from Alan Lu.
* Add support for Django 1.5.
* Remove support for Django < 1.4.
* Drop support for Python < 2.6.
* Drop support for ``staticfiles`` app, in favor of ``django.contrib.staticfiles``.
* Drop ``PIPELINE`` settings, in favor of ``DEBUG`` to avoid confusion.
* Drop support for ``jinja2`` temporarily.

1.2.24
------

* Fix yui/yuglify settings overriding each other. Thanks to Fábio Santos.

1.2.23
------

* Separate yuglify compressor from YUI compressor.
* Improve HTML compression middleware.

1.2.22
------

* Better compressor error messages. Thanks to Steven Cummings.
* Improve installation documentation. Thanks to Steven Cummings.
* Fix packaging metadata. Thanks to Rui Coelho for noticing it.
* Add documentation about non-packing storage.

1.2.21
------

* Run stylus even if file is considered outdated.

1.1.20
------

* Ensure yui-compressor can still use YUICompressor.

1.2.19
------

* **BACKWARD INCOMPATIBLE** : Replace python cssmin compressor to run the command (works for python or node implementation)

1.2.18
------

* **BACKWARD INCOMPATIBLE** : Replace yui-compressor by yuglify, check your configuration.
* Use finders in manifest. Thanks to Sjoerd Arendsen.

1.2.17
------

* Fully tested windows compatibility. Thanks to Idan Zalzberg.

1.2.16
------

* Fix manifesto module. Thanks to Zenobius Jiricek.
* Ensure coffee-script compiler don't try to overwrite file. Thanks to Teo Klestrup Röijezon.

1.2.15
------

* Ensure asset url are build with ``posixpath``.
* Deal with storage prefix properly.

1.2.14
------

* Jinja2 support, thanks to Christopher Reeves.
* Add read/save_file method to CompilerBase.

1.2.13
------

* Fix unicode bug in compressor. Thanks to Victor Shnayder.
* Fix outdated detection bug. Thanks to Victor Shnayder and Erwan Ameil.
* Add slimit compressor. Thanks to Brant Young.

1.2.12
------

* Fix IO error when creating new compiled file. Thanks to Melvin Laplanche.

1.2.11
------

* Add a small contribution guide
* Add mimetype settings for sass and scss
* Change compiler interface to let compiler determine if file is outdated

1.2.10
------

* Use ``/usr/bin/env`` by default to find compiler executable. Thanks to Michael Weibel.
* Allow to change embed settings : max size and directory. Thanks to Pierre Drescher.
* Some documentation improvements. Thanks to Florent Messa.

1.2.9
-----

* Don't compile non-outdated files.
* Add non-packing storage.

1.2.8
-----

* Fix bugs in our glob implementation.

1.2.7
-----

* Many documentation improvements. Thanks to Alexis Svinartchouk.
* Improve python packaging.
* Don't write silently to STATIC_ROOT when we shouldn't.
* Accept new .sass extension in SASSCompiler. Thanks to Jonas Geiregat for the report.

1.2.6
-----

* New lines in templates are now escaper rather than deleted. Thanks to Trey Smith for the report and the patch.
* Improve how we find where to write compiled file. Thanks to sirex for the patch.

1.2.5
-----

* Fix import error for cssmin and jsmin compressors. Thanks to Berker Peksag for the report.
* Fix error with default template function. Thanks to David Charbonnier for the patch and report.

1.2.4
-----

* Fix encoding problem.
* Improve storage documentation
* Add mention of the IRC channel #django-pipeline in documentation

1.2.3
-----

* Fix javascript mime type bug. Thanks to Chase Seibert for the report.

1.2.2.1
-------

* License clarification. Thanks to Dmitry Nezhevenko for the report.

1.2.2
-----

* Allow to disable javascript closure wrapper with ``PIPELINE_DISABLE_WRAPPER``.
* Various improvements to documentation.
* Slightly improve how we find where to write compiled file.
* Simplify module hierarchy.
* Allow templatetag to output mimetype to be able to use less.js and other javascript compilers.

1.2.1
-----

* Fixing a bug in ``FinderStorage`` when using prefix in staticfiles. Thanks to Christian Hammond for the report and testing.
* Make ``PIPELINE_ROOT`` defaults more sane. Thanks to Konstantinos Pachnis for the report.

1.2.0
-----

* Dropped ``synccompress`` command in favor of staticfiles ``collecstatic`` command.
* Added file versionning via staticfiles ``CachedStaticFilesStorage``.
* Added a default js template language.
* Dropped ``PIPELINE_AUTO`` settings in favor of simple ``PIPELINE``.
* Renamed ``absolute_asset_paths`` to ``absolute_paths`` for brevity.
* Made packages lazy to avoid doing unnecessary I/O.
* Dropped ``external_urls`` support for now.
* Add cssmin compressor. Thanks to Steven Cummings.
* Jsmin is no more bundle with pipeline.


text:
import React, { PropTypes } from 'react';
import InputSearch from '../../components/Input/InputSearch';
import InputSearchResult from '../../components/Input/InputSearchResult';
import Layout from '../../components/Layout/Layout';

class Index extends React.Component {

  static propTypes = {
    contacts: PropTypes.arrayOf(PropTypes.shape().isRequired).isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      contacts: this.props.contacts,
    };
  }

  handleKeyUp = (e) => {
    const query = e.target.value.toLowerCase();

    function filterInput(element) {
      return element.name.toLowerCase().includes(query);
    }

    const filtered = this.props.contacts.filter(filterInput);

    this.setState({
      contacts: filtered,
    });
  }

  render() {
    return (
      <Layout>

Contacts

        <InputSearch onKeyUp={this.handleKeyUp} />
        <InputSearchResult contacts={this.state.contacts} />
      </Layout>
    );
  }
}

export default Index;

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 336315 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="imagick.solarizeimage">
 <refnamediv>
  <refname>Imagick::solarizeImage</refname>
  <refpurpose>Applies a solarizing effect to the image</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>Imagick::solarizeImage</methodname>
   <methodparam><type>int</type><parameter>threshold</parameter></methodparam>
  </methodsynopsis>
  <para>
   Applies a special effect to the image, similar to the effect achieved in
   a photo darkroom by selectively exposing areas of photo sensitive paper
   to light. Threshold ranges from 0 to QuantumRange and is a measure of the
   extent of the solarization.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>threshold</parameter></term>
     <listitem>
      <para>
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &imagick.return.success;
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
    <example>
      <title> <function>Imagick::solarizeImage</function></title>
      <programlisting role="php">
      <![CDATA[
<?php
function solarizeImage($imagePath, $solarizeThreshold) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->solarizeImage($solarizeThreshold * \Imagick::getQuantum());
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>
]]>
      </programlisting>
    </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
@implementation YALBaseDataFlowController

#pragma mark - Input events

+ (void)inputDidBegin:(id<YALInput>)input {
    [input setFieldState:YALFieldStateClear];
}

+ (void)inputDidEnd:(id<YALInput>)input {
    if ([input validator]) {
        NSError *error;
        BOOL valid = [[input validator] isValid:input error:&error];

        if ([input conformsToProtocol:@protocol(YALFieldInput)]) {
            [input setFieldState:(valid) ? YALFieldStateValid : YALFieldStateInvalid];
        }
    }

    if ([input conformsToProtocol:@protocol(YALFieldInput)] &&
        [(UIControl<YALFieldInput> *)input inputEnabled] &&
        [[(UIControl<YALFieldInput> *)input textField] isFirstResponder])
    {
        [YALBaseFormController selectNextResponderInForm:[(UIControl<YALFieldInput> *)input form] afterInput:input];
    }
}

+ (void)inputDidReceiveTouchEvent:(id<YALInput>)input {
    if ([[input responder] respondsToSelector:@selector(becomeFirstResponder)]) {
        [[input responder] becomeFirstResponder];
    } else if ([[input responder] respondsToSelector:@selector(performAction:)]) {
        [[input responder] performAction:nil];
    } else if ([input inputEnabled] && [input conformsToProtocol:@protocol(YALFieldInput)]) {
        [[(UIControl<YALFieldInput> *)input textField] becomeFirstResponder];
    } else {
        [YALKeyboardHelper hideKeyboard];
    }
}

+ (BOOL)input:(UIControl<YALFieldInput> *)input shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString **)string {
    BOOL should = YES;

    id<YALFormatter> inputFormatter = [input formatter];
    if (inputFormatter) {
        should = [inputFormatter textField:input.textField shouldChangeCharactersInRange:range replacementString:string];

        // check if formatting is required after each data change action
        BOOL shouldFormatOnChange = NO;
        if ([inputFormatter respondsToSelector:@selector(shouldFormatValueOnChange)]) {
            shouldFormatOnChange = [inputFormatter shouldFormatValueOnChange];
        }
        if (should && shouldFormatOnChange) {
            // set new value directly to force formatting
            NSString *newString = [input.textField.text stringByReplacingCharactersInRange:range withString:*string];
            input.rawValue = newString;
            should = NO;
        }
    }

    return should;
}

#pragma mark - Formatting

+ (NSString *)rawValueFromFormattedValue:(NSString *)formattedValue forInput:(id<YALInput>)input {
    return ([input formatter]) ? [[input formatter] rawValueFromFormattedValue:formattedValue] : formattedValue;
}

+ (NSString *)formattedValueFromRawValue:(NSString *)rawValue forInput:(id<YALInput>)input {
    return ([input formatter]) ? [[input formatter] formattedValueFromRawValue:rawValue] : rawValue;
}

@end


text:
define('js/logic/page2.js',["src/widgets/widget.js","src/utils.js","js/data/dataB.js","js/src/utils/utils.js"],function(require){

  require("src/widgets/widget.js");
  require("src/utils.js");
 require("js/data/dataB.js");
 require("js/src/utils/util2.js");

});


text:
botox
=====

Remote Code Injection Tool - Windows C++

This code was written in 2010 and is not under development.

directory structure:

botox: contains the code to be injected into a another process in a dll

botoxconsole: tool to select a process

botoxdlltest: test if the dll can be loaded

botoxwomen: test application


text:
<!DOCTYPE html>

<link type="text/css" rel="stylesheet" href="../stylesheets/blog-stylesheet.css"/>
<meta charset="UTF-8">

Facebook

Linkedin

Twitter

 About

Blog

 Projects

 Home

  <title></title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog-stylesheet.css">

Enumerable Methods

Feb 8th, 2015

      So far in Ruby we've learned about a lot of cool things. One of the great characteristics of Ruby is that is often reads like plain english. As you know, in English we use verbs to create action. Likewise in Ruby we use methods. Here are some examples of the methods puts and +.

      Those two are regular, fairly common methods. A different more comples type of method is the Enumerable methods. These are slightly more comples than regular methods because they're slighly more powerful. In fact, they actually go by the term modules, because they're groups of methods packaged into one. Kind of like if we used one verb for three verbs: skip, sing, and smile becomes skingle.

      We use emnumerables when we iterate over Arrays and Hashes. The enumerable method #map is very similiar the the regular method collect because it iterates over the code and then collects the results. The example below maps a collection of books and returns only the books the have been read.

  Emily Boerner  ~    Emily.Boerner@gmail.com   ~     610.513.8501  ~      San Francisco, CA


text:
<?php

/**
 *
 * Example of a Captcha Controller
 * Created by Jordane JOUFFROY
 * contact@jordane.net
 *
 * Created with VisualCaptcha
 * A library from EmotionLoop
 * http://visualcaptcha.net
 *
 */

class CaptchaController extends BaseController {

	/**
	 * Generate a Captcha
	 * @return Response
	 */
	public function start($howmany)
	{
		$session = new SessionCaptcha();
		$captcha = new Captcha($session);
		$captcha->generate($howmany);
		return Response::json($captcha->getFrontEndData());
	}

	/**
	 * Get an audio file
	 * @param  string $type Song type (mp3/ogg)
	 * @return File
	 */
	public function audio($type = 'mp3')
	{
		$session = new SessionCaptcha();
		$captcha = new Captcha($session);
		return $captcha->streamAudio(array(), $type);
	}

	/**
	 * Get an image file
	 * @param  string $index  Image index
	 * @return File
	 */
	public function image($index)
	{
		$session = new SessionCaptcha();
		$captcha = new Captcha($session);
		return $captcha->streamImage(array(), $index, 0);
	}

	/**
	 * Check if the Captcha result is good
	 * @return Mixed
	 */
	public function send()
	{
		$session = new SessionCaptcha();
		$captcha = new Captcha($session);

	    $frontendData = $captcha->getFrontendData();

	    if ( ! $frontendData ) {
	        return Lang::get('error.captcha.none');
	    } else {
	        // If an image field name was submitted, try to validate it
	        if ( $imageAnswer = Input::get($frontendData[ 'imageFieldName' ]) ) {
	            if ( $captcha->validateImage( $imageAnswer ) ) {
	            	// Return false if the result is correct
	            	return false;
	            } else {
	                return Lang::get('error.captcha.image');
	            }
	        } else if ( $audioAnswer = Input::get($frontendData[ 'audioFieldName' ]) ) {
	            if ( $captcha->validateAudio( $audioAnswer ) ) {
	            	// Return false if the result is correct
	                return false;
	            } else {
	                return Lang::get('error.captcha.audio');
	            }
	        } else {
	           return Lang::get('error.captcha.incomplete');
	        }
	    }
	}

}


text:
class Spree::PageImage < Spree::Asset

  has_attached_file :attachment,
    :styles => Proc.new{ |clip| clip.instance.attachment_sizes },
    :url => '/spree/pages/:id/:style/:basename.:extension',
    :path => ':rails_root/public/spree/pages/:id/:style/:basename.:extension'

  validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
  validates :attachment, attachment_presence: true

  def image_content?
    attachment_content_type.to_s.match(/\/(jpeg|png|gif|tiff|x-photoshop)/)
  end

  def attachment_sizes
    sizes = {}
    if image_content?
      sizes.merge!(mini: '48x48>', small: '150x150>', medium: '420x300>', large: '900x650>')
      sizes.merge!(slide: '950x250#') if viewable.respond_to?(:root?) && viewable.root?
    end
    sizes
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/share_a_img"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="fitCenter"
        android:src="@drawable/sssssss"
        android:transitionName="share_img"/>

    <Button
        android:id="@+id/share_a_btn"
        android:layout_width="60dp"
        android:layout_height="50dp"
        android:text="点我"
        android:textSize="11dp"
        android:gravity="center"
        android:transitionName="share_btn"/>

</LinearLayout>


text:
<!doctype html>
<meta charset=utf-8>
<title>CloseEvent: historical initialization</title>


text:
import contextlib
import functools

import alembic
from alembic import context
from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine import reflection

# Neutron milestones for upgrade aliases
LIBERTY = 'liberty'
MITAKA = 'mitaka'

NEUTRON_MILESTONES = [
    # earlier milestones were not tagged
    LIBERTY,
    MITAKA,
]

CREATION_OPERATIONS = (sa.sql.ddl.CreateIndex,
                       sa.sql.ddl.CreateTable,
                       sa.sql.ddl.CreateColumn,
                       )
DROP_OPERATIONS = (sa.sql.ddl.DropConstraint,
                   sa.sql.ddl.DropIndex,
                   sa.sql.ddl.DropTable,
                   alembic.ddl.base.DropColumn)

def skip_if_offline(func):
    """Decorator for skipping migrations in offline mode."""
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        if context.is_offline_mode():
            return
        return func(*args, **kwargs)

    return decorator

def raise_if_offline(func):
    """Decorator for raising if a function is called in offline mode."""
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        if context.is_offline_mode():
            raise RuntimeError(_("%s cannot be called while in offline mode") %
                               func.__name__)
        return func(*args, **kwargs)

    return decorator

@raise_if_offline
def schema_has_table(table_name):
    """Check whether the specified table exists in the current schema.

    This method cannot be executed in offline mode.
    """
    bind = op.get_bind()
    insp = sa.engine.reflection.Inspector.from_engine(bind)
    return table_name in insp.get_table_names()

@raise_if_offline
def schema_has_column(table_name, column_name):
    """Check whether the specified column exists in the current schema.

    This method cannot be executed in offline mode.
    """
    bind = op.get_bind()
    insp = sa.engine.reflection.Inspector.from_engine(bind)
    # first check that the table exists
    if not schema_has_table(table_name):
        return
    # check whether column_name exists in table columns
    return column_name in [column['name'] for column in
                           insp.get_columns(table_name)]

@raise_if_offline
def alter_column_if_exists(table_name, column_name, **kwargs):
    """Alter a column only if it exists in the schema."""
    if schema_has_column(table_name, column_name):
        op.alter_column(table_name, column_name, **kwargs)

@raise_if_offline
def drop_table_if_exists(table_name):
    if schema_has_table(table_name):
        op.drop_table(table_name)

@raise_if_offline
def rename_table_if_exists(old_table_name, new_table_name):
    if schema_has_table(old_table_name):
        op.rename_table(old_table_name, new_table_name)

def alter_enum(table, column, enum_type, nullable):
    bind = op.get_bind()
    engine = bind.engine
    if engine.name == 'postgresql':
        values = {'table': table,
                  'column': column,
                  'name': enum_type.name}
        op.execute("ALTER TYPE %(name)s RENAME TO old_%(name)s" % values)
        enum_type.create(bind, checkfirst=False)
        op.execute("ALTER TABLE %(table)s RENAME COLUMN %(column)s TO "
                   "old_%(column)s" % values)
        op.add_column(table, sa.Column(column, enum_type, nullable=nullable))
        op.execute("UPDATE %(table)s SET %(column)s = "
                   "old_%(column)s::text::%(name)s" % values)
        op.execute("ALTER TABLE %(table)s DROP COLUMN old_%(column)s" % values)
        op.execute("DROP TYPE old_%(name)s" % values)
    else:
        op.alter_column(table, column, type_=enum_type,
                        existing_nullable=nullable)

def create_table_if_not_exist_psql(table_name, values):
    if op.get_bind().engine.dialect.server_version_info < (9, 1, 0):
        op.execute("CREATE LANGUAGE plpgsql")
    op.execute("CREATE OR REPLACE FUNCTION execute(TEXT) RETURNS VOID AS $$"
               "BEGIN EXECUTE $1; END;"
               "$$ LANGUAGE plpgsql STRICT;")
    op.execute("CREATE OR REPLACE FUNCTION table_exist(TEXT) RETURNS bool as "
               "$$ SELECT exists(select 1 from pg_class where relname=$1);"
               "$$ language sql STRICT;")
    op.execute("SELECT execute($$CREATE TABLE %(name)s %(columns)s $$) "
               "WHERE NOT table_exist(%(name)r);" %
               {'name': table_name,
                'columns': values})

def remove_foreign_keys(table, foreign_keys):
    for fk in foreign_keys:
        op.drop_constraint(
            constraint_name=fk['name'],
            table_name=table,
            type_='foreignkey'
        )

def create_foreign_keys(table, foreign_keys):
    for fk in foreign_keys:
        op.create_foreign_key(
            constraint_name=fk['name'],
            source_table=table,
            referent_table=fk['referred_table'],
            local_cols=fk['constrained_columns'],
            remote_cols=fk['referred_columns'],
            ondelete='CASCADE'
        )

@contextlib.contextmanager
def remove_fks_from_table(table):
    try:
        inspector = reflection.Inspector.from_engine(op.get_bind())
        foreign_keys = inspector.get_foreign_keys(table)
        remove_foreign_keys(table, foreign_keys)
        yield
    finally:
        create_foreign_keys(table, foreign_keys)


text:
title: Macでpkgからインストールしたアプリケーションを削除するpkgUninstallerを作りました
date: '2014-03-13'
tags:
- howto
- mac
- programming
- ruby
---

![pkgUninstaller](2014/pkguninstaller.png)

## pkgからのインストール

Macでpkgからアプリケーションのインストールをした時に、アンインストーラがついてくるものとついてこないものがあります。
ただ.appを削除すればいいというものではなく、他のディレクトリにもいろいろインストールしてくれるので不要なファイルが残ります。

## pkgutil

pkgutilコマンドを使えば、そのアプリケーションがどのようなファイルをどこにインストールしたのかがわかります。アンインストールするコマンドオプションもあったようですが、現在は削除されています。
参考:[新・OS X ハッキング! (94) pkgutilでインストーラパッケージを削除する   マイナビニュース](http://news.mynavi.jp/column/osxhack/094/)

## pkgUninstaller

上リンクでもスクリプトを用いてアプリケーションのアンインストールを行う方法を解説してはいますが、見る限りどうも怪しいです。
そこで、Rubyの勉強も兼ねて、pkgからインストールしたアプリケーションのアンインストールを行うpkgUninstaller.rbを作りました。
[unasuke/pkgUninstaller](https://github.com/unasuke/pkgUninstaller)

## 使い方

__こちらでも動作のテストはしていますが、予期せぬシステムの破損やデータの消去が発生する可能性があります。実行は自己責任でお願いします。__
まず、-sコマンドを用いてアンインストールするパッケージのIDを探します。部分一致で判定するので、メーカー名やアプリケーション名(アルファベット)を入力して下さい。
例

```shell
$ ruby pkgUninstaller.rb -s goo
shell(#<Th:0x007fcf090bc8b0>): /usr/sbin/pkgutil --pkgs
com.google.pkg.GoogleJapaneseInput
com.google.pkg.GoogleVoiceAndVideo
com.google.pkg.Keystone
```

お目当てのパッケージIDが見つかったら、-uコマンドでアンインストールを行います。まずは、--noopもつけて、実際にどのようなファイルやディレクトリが削除されようとしているのかを確認して下さい。
例

```shell
$ ruby pkgUninstaller.rb -u com.google.pkg.GoogleJapaneseInput -n
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputConverter.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputRenderer.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputTool.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputConverter.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Breakpad.nib
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputRenderer.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Breakpad.nib
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputTool.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Breakpad.nib
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputConverter.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/ReporterIcon.icns
中略
delete /Applications/GoogleJapaneseInput.localized
/Applications/GoogleJapaneseInput.localized is not empty.
delete /Library/Input Methods
/Library/Input Methods is not empty.
delete /Library/LaunchAgents
/Library/LaunchAgents is not empty.
delete /Applications
/Applications is not empty.
delete /Library
/Library is not empty.
160 files and 0 directories deleted.
```

ほにゃららis not empty.と書かれているディレクトリは、中身が空でないため削除されないディレクトリです。(実際の実行ではないため、本当に削除されないことを保証するものではありません)

それでは実際にアンインストールを行いますが、この時、管理者権限で実行しないとパッケージの情報の削除を行わないままファイルの削除がなされるため、えらいことになります。どんなことになるのかは僕も怖くてやったことがないのでわかりません。
例

```shell
$ sudo ruby pkgUninstaller.rb -u com.google.pkg.GoogleJapaneseInput
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputConverter.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputRenderer.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputTool.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Localizable.strings
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputConverter.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Breakpad.nib
delete /Library/Input Methods/GoogleJapaneseInput.app/Contents/Resources/GoogleJapaneseInputRenderer.app/Contents/Frameworks/GoogleBreakpad.framework/Versions/A/Resources/Reporter.app/Contents/Resources/English.lproj/Breakpad.nib
中略
delete /Applications/GoogleJapaneseInput.localized
/Applications/GoogleJapaneseInput.localized is not empty.
delete /Library/Input Methods
/Library/Input Methods is not empty.
delete /Library/LaunchAgents
/Library/LaunchAgents is not empty.
delete /Applications
/Applications is not empty.
delete /Library
/Library is not empty.
160 files and 52 directories deleted.
```

これでアンインストールが完了しました。それでも削除しきれないディレクトリなどが残ることがあるので、明らかに不要だと思われるものは手動で削除して下さい。

## コマンドオプション

### --serach(-s)

パッケージのIDを検索します。部分一致で検索します。

### --unlink(-u)

インストールされたファイルとディレクトリを削除します。

### --noop(-n)

--unlinkオプションと併用した時、ファイルとディレクトリの変更、及びパッケージ情報の削除を行いません。最後に削除されたファイル、ディレクトリ数を出力しますが、これは--noopオプション無しの実行と必ずしも一致しません。

### --quiet(-q)

--unlinkオプションと併用した時、削除されるファイルとディレクトリの名前、ディレクトリが空かどうかなどの情報を出力しません。削除されたファイル、ディレクトリ数は出力します。

### --help(-h)もしくはオプション無し

オプション一覧を出力します。

## 最後に

アンインストーラが付属する場合(virtualboxなど)は付属のそれを使って下さい。


text:
@(namesAndValues: (Any, Any)*)
@namesAndValues.map { case (name, value) =>
	<input type="hidden" name="@name" value="@value">
}


text:
"""Tests for thanks-related code."""
#
# (C) Pywikibot team, 2016-2022
#
# Distributed under the terms of the MIT license.
#
import unittest

from pywikibot.flow import Topic
from tests.aspects import TestCase

NO_THANKABLE_POSTS = 'There is no recent post which can be test thanked.'

class TestThankFlowPost(TestCase):

    """Test thanks for Flow posts."""

    family = 'wikipedia'
    code = 'test'

    write = True

    @classmethod
    def setUpClass(cls):
        """Set up class."""
        super().setUpClass()
        cls._topic_title = 'Topic:Tvkityksg1ukyrrw'

    def test_thank_post(self):
        """Test thanks for Flow posts."""
        site = self.get_site()
        topic = Topic(site, self._topic_title)
        for post in reversed(topic.replies()):
            user = post.creator
            if site.user() == user.username:
                continue
            if user.is_thankable:
                break
        else:
            self.skipTest(NO_THANKABLE_POSTS)
        before_time = site.getcurrenttimestamp()
        post.thank()
        log_entries = site.logevents(logtype='thanks', total=5, page=user,
                                     start=before_time, reverse=True)
        try:
            next(iter(log_entries))
        except StopIteration:
            found_log = False
        else:
            found_log = True
        self.assertTrue(found_log)

    def test_self_thank(self):
        """Test that thanking one's own Flow post causes an error."""
        site = self.get_site()
        topic = Topic(site, self._topic_title)
        my_reply = topic.reply('My attempt to thank myself.')
        self.assertAPIError('invalidrecipient', None, my_reply.thank)

if __name__ == '__main__':  # pragma: no cover
    try:
        unittest.main()
    except SystemExit:
        pass


text:
<!DOCTYPE html SYSTEM "about:legacy-compat">

<META http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
<title>Apache JMeter
          -
          Mailing Lists</title>
<meta name="author" value="Apache JMeter Project">
<meta name="email" value="dev.AT.jmeter.DOT.apache.DOT.org">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Merriweather:400normal" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="./css/new-style.css">
<link rel="apple-touch-icon-precomposed" href="./images/apple-touch-icon.png">
<link rel="icon" href="./images/favicon.png">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="./images/mstile-144x144.png">
<meta name="theme-color" content="#ffffff">

Main content

About

Overview

License

Download

Download Releases

Release Notes

Documentation

Get Started

User Manual

Best Practices

Component Reference

Functions Reference

Properties Reference

Change History

Javadocs

JMeter Wiki

FAQ (Wiki)

Tutorials

Distributed Testing

Recording Tests

JUnit Sampler

Access Log Sampler

Extending JMeter

Community

Issue Tracking

Security

Mailing Lists

Source Repositories

Building and Contributing

Project info at Apache

Contributors

Foundation

The Apache Software Foundation (ASF)

Get Involved in the ASF

Sponsorship

Thanks

Twitter

github

Mailing Lists - Guidelines

Before subscribing to any of the mailing lists, please make sure that you have
read and understand the guidelines.

Please note that usage of these mailing lists is subject to the
Public Forum Archive Policy.

For details of how to subscribe/unsubscribe please read
Subscribing and Unsubscribing

JMeter lists and archives at the ASF

The following mailing lists are available:

Apache JMeter User¶

This is the list where users of Apache JMeter meet and discuss issues.

Developers are also expected to be lurking on this list to offer support to users of JMeter.

This list starts part-way through Nov 2011, when JMeter became an independent Apache project.
For old postings, please see the Jakarta JMeter User list, below.

Subscribe at user-subscribe@jmeter.apache.org

Send your message to: user@jmeter.apache.org (after the subscription process)

Unsubscribe at user-unsubscribe@jmeter.apache.org

Archives at jmeter-user Archive

Apache JMeter Developer¶

This is the list where participating developers meet and discuss issues, code changes/additions etc.

Please do not send usage questions to this list, see user list above.

This list also collects Wiki update messages.

This list starts part-way through Nov 2011, when JMeter became an independent Apache project.
For earlier postings, please see below.

Subscribe at dev-subscribe@jmeter.apache.org

Send your message to: dev@jmeter.apache.org (after the subscription process)

Unsubscribe at dev-unsubscribe@jmeter.apache.org

Archives at jmeter-dev Archive

Apache JMeter Commits¶

SVN commit messages are sent here.

Prior to Nov 2011, they were sent to the Jakarta Notifications list, see below.

Subscribe at commits-subscribe@jmeter.apache.org

Unsubscribe at commits-unsubscribe@jmeter.apache.org

Archives at jmeter-commits Archive

Apache JMeter Issues¶

Bugzilla messages are sent here.

Prior to Nov 2011, they were sent to the Jakarta Notifications list, see below.

Subscribe at issues-subscribe@jmeter.apache.org

Unsubscribe at issues-unsubscribe@jmeter.apache.org

Archives at jmeter-issues Archive

Jakarta Developer¶

Combined Jakarta developer list, April 2010 to November 2011

Archives at jakarta-dev Archive

Jakarta JMeter User¶

This is the old JMeter user list from when JMeter was a sub-project of Apache Jakarta.

Archives at jakarta-jmeter-user Archive

Jakarta JMeter Developer¶

Historical list, up to April 2010.

Archives at jakarta-jmeter-dev Archive

Jakarta Notifications¶

Combined Jakarta notifications to November 2011.
Includes Bugzilla, SVN and Wiki commit mails for JMeter.

Archives at jakarta-notifications Archive

Other Archives and Searching

There are several 3rd party sites that archive and provide searching for our mailing lists:

Mark Mail

mail-archive.com

      Share this page:

share

tweet

Go to top

            Copyright ©
            1999 –
            2019
            , Apache Software Foundation

Apache, Apache JMeter, JMeter, the Apache
            feather, and the Apache JMeter logo are
            trademarks of the
            Apache Software Foundation.


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Game of life</title>

        Block size:
            <select id="blocksize">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="4" selected>3</option>
                <option value="8">4</option>
                <option value="16">5</option>
                <option value="32">6</option>
            </select>
        Frame rate:
            <select id="framerate">
                <option value="60">60</option>
                <option value="30">30</option>
                <option value="15" selected>15</option>
                <option value="10">10</option>
                <option value="5">5</option>
                <option value="1">1</option>
            </select>
        Actual framerate: ~ fps
        <button id="restart">Restart</button>

    <canvas id="canvas" width="1200px" height="600px" style="padding-top: 10px;"></canvas>


text:
<config>
    <executableName>${app.executable}</executableName>
    <mainClass>${app.mainclass}</mainClass>
    <os>ios</os>
    <arch>thumbv7</arch>
    <target>ios</target>
    <iosInfoPList>Info.plist.xml</iosInfoPList>
	<treeShaker>aggressive</treeShaker>
    <resources>
        <resource>
            <directory>resources</directory>
        </resource>
    </resources>
</config>


text:
from httplib import HTTPConnection
import os
from subprocess import Popen, PIPE
import sys
from time import sleep, time
from collections import defaultdict
import unittest
from nose import SkipTest

from swiftclient import get_auth, head_account

from swift.obj.diskfile import get_data_dir
from swift.common.ring import Ring
from swift.common.utils import readconf
from swift.common.manager import Manager
from swift.common.storage_policy import POLICIES, EC_POLICY, REPL_POLICY

from test.probe import CHECK_SERVER_TIMEOUT, VALIDATE_RSYNC

ENABLED_POLICIES = [p for p in POLICIES if not p.is_deprecated]
POLICIES_BY_TYPE = defaultdict(list)
for p in POLICIES:
    POLICIES_BY_TYPE[p.policy_type].append(p)

def get_server_number(port, port2server):
    server_number = port2server[port]
    server, number = server_number[:-1], server_number[-1:]
    try:
        number = int(number)
    except ValueError:
        # probably the proxy
        return server_number, None
    return server, number

def start_server(port, port2server, pids, check=True):
    server, number = get_server_number(port, port2server)
    err = Manager([server]).start(number=number, wait=False)
    if err:
        raise Exception('unable to start %s' % (
            server if not number else '%s%s' % (server, number)))
    if check:
        return check_server(port, port2server, pids)
    return None

def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT):
    server = port2server[port]
    if server[:-1] in ('account', 'container', 'object'):
        if int(server[-1]) > 4:
            return None
        path = '/connect/1/2'
        if server[:-1] == 'container':
            path += '/3'
        elif server[:-1] == 'object':
            path += '/3/4'
        try_until = time() + timeout
        while True:
            try:
                conn = HTTPConnection('127.0.0.1', port)
                conn.request('GET', path)
                resp = conn.getresponse()
                # 404 because it's a nonsense path (and mount_check is false)
                # 507 in case the test target is a VM using mount_check
                if resp.status not in (404, 507):
                    raise Exception(
                        'Unexpected status %s' % resp.status)
                break
            except Exception as err:
                if time() > try_until:
                    print err
                    print 'Giving up on %s:%s after %s seconds.' % (
                        server, port, timeout)
                    raise err
                sleep(0.1)
    else:
        try_until = time() + timeout
        while True:
            try:
                url, token = get_auth('http://127.0.0.1:8080/auth/v1.0',
                                      'test:tester', 'testing')
                account = url.split('/')[-1]
                head_account(url, token)
                return url, token, account
            except Exception as err:
                if time() > try_until:
                    print err
                    print 'Giving up on proxy:8080 after 30 seconds.'
                    raise err
                sleep(0.1)
    return None

def kill_server(port, port2server, pids):
    server, number = get_server_number(port, port2server)
    err = Manager([server]).kill(number=number)
    if err:
        raise Exception('unable to kill %s' % (server if not number else
                                               '%s%s' % (server, number)))
    try_until = time() + 30
    while True:
        try:
            conn = HTTPConnection('127.0.0.1', port)
            conn.request('GET', '/')
            conn.getresponse()
        except Exception as err:
            break
        if time() > try_until:
            raise Exception(
                'Still answering on port %s after 30 seconds' % port)
        sleep(0.1)

def kill_nonprimary_server(primary_nodes, port2server, pids):
    primary_ports = [n['port'] for n in primary_nodes]
    for port, server in port2server.iteritems():
        if port in primary_ports:
            server_type = server[:-1]
            break
    else:
        raise Exception('Cannot figure out server type for %r' % primary_nodes)
    for port, server in list(port2server.iteritems()):
        if server[:-1] == server_type and port not in primary_ports:
            kill_server(port, port2server, pids)
            return port

def build_port_to_conf(server):
    # map server to config by port
    port_to_config = {}
    for server_ in Manager([server]):
        for config_path in server_.conf_files():
            conf = readconf(config_path,
                            section_name='%s-replicator' % server_.type)
            port_to_config[int(conf['bind_port'])] = conf
    return port_to_config

def get_ring(ring_name, required_replicas, required_devices,
             server=None, force_validate=None):
    if not server:
        server = ring_name
    ring = Ring('/etc/swift', ring_name=ring_name)
    if not VALIDATE_RSYNC and not force_validate:
        return ring
    # easy sanity checks
    if ring.replica_count != required_replicas:
        raise SkipTest('%s has %s replicas instead of %s' % (
            ring.serialized_path, ring.replica_count, required_replicas))
    if len(ring.devs) != required_devices:
        raise SkipTest('%s has %s devices instead of %s' % (
            ring.serialized_path, len(ring.devs), required_devices))
    port_to_config = build_port_to_conf(server)
    for dev in ring.devs:
        # verify server is exposing mounted device
        conf = port_to_config[dev['port']]
        for device in os.listdir(conf['devices']):
            if device == dev['device']:
                dev_path = os.path.join(conf['devices'], device)
                full_path = os.path.realpath(dev_path)
                if not os.path.exists(full_path):
                    raise SkipTest(
                        'device %s in %s was not found (%s)' %
                        (device, conf['devices'], full_path))
                break
        else:
            raise SkipTest(
                "unable to find ring device %s under %s's devices (%s)" % (
                    dev['device'], server, conf['devices']))
        # verify server is exposing rsync device
        if port_to_config[dev['port']].get('vm_test_mode', False):
            rsync_export = '%s%s' % (server, dev['replication_port'])
        else:
            rsync_export = server
        cmd = "rsync rsync://localhost/%s" % rsync_export
        p = Popen(cmd, shell=True, stdout=PIPE)
        stdout, _stderr = p.communicate()
        if p.returncode:
            raise SkipTest('unable to connect to rsync '
                           'export %s (%s)' % (rsync_export, cmd))
        for line in stdout.splitlines():
            if line.rsplit(None, 1)[-1] == dev['device']:
                break
        else:
            raise SkipTest("unable to find ring device %s under rsync's "
                           "exported devices for %s (%s)" %
                           (dev['device'], rsync_export, cmd))
    return ring

def get_policy(**kwargs):
    kwargs.setdefault('is_deprecated', False)
    # go through the policies and make sure they match the
    # requirements of kwargs
    for policy in POLICIES:
        # TODO: for EC, pop policy type here and check it first
        matches = True
        for key, value in kwargs.items():
            try:
                if getattr(policy, key) != value:
                    matches = False
            except AttributeError:
                matches = False
        if matches:
            return policy
    raise SkipTest('No policy matching %s' % kwargs)

class ProbeTest(unittest.TestCase):
    """
    Don't instantiate this directly, use a child class instead.
    """

    def setUp(self):
        p = Popen("resetswift 2>&1", shell=True, stdout=PIPE)
        stdout, _stderr = p.communicate()
        print stdout
        Manager(['all']).stop()
        self.pids = {}
        try:
            self.account_ring = get_ring(
                'account',
                self.acct_cont_required_replicas,
                self.acct_cont_required_devices)
            self.container_ring = get_ring(
                'container',
                self.acct_cont_required_replicas,
                self.acct_cont_required_devices)
            self.policy = get_policy(**self.policy_requirements)
            self.object_ring = get_ring(
                self.policy.ring_name,
                self.obj_required_replicas,
                self.obj_required_devices,
                server='object')
            Manager(['main']).start(wait=False)
            self.port2server = {}
            for server, port in [('account', 6002), ('container', 6001),
                                 ('object', 6000)]:
                for number in xrange(1, 9):
                    self.port2server[port + (number * 10)] = \
                        '%s%d' % (server, number)
            for port in self.port2server:
                check_server(port, self.port2server, self.pids)
            self.port2server[8080] = 'proxy'
            self.url, self.token, self.account = \
                check_server(8080, self.port2server, self.pids)
            self.configs = defaultdict(dict)
            for name in ('account', 'container', 'object'):
                for server_name in (name, '%s-replicator' % name):
                    for server in Manager([server_name]):
                        for i, conf in enumerate(server.conf_files(), 1):
                            self.configs[server.server][i] = conf
            self.replicators = Manager(
                ['account-replicator', 'container-replicator',
                 'object-replicator'])
            self.updaters = Manager(['container-updater', 'object-updater'])
            self.server_port_to_conf = {}
            # get some configs backend daemon configs loaded up
            for server in ('account', 'container', 'object'):
                self.server_port_to_conf[server] = build_port_to_conf(server)
        except BaseException:
            try:
                raise
            finally:
                try:
                    Manager(['all']).kill()
                except Exception:
                    pass

    def tearDown(self):
        Manager(['all']).kill()

    def device_dir(self, server, node):
        conf = self.server_port_to_conf[server][node['port']]
        return os.path.join(conf['devices'], node['device'])

    def storage_dir(self, server, node, part=None, policy=None):
        policy = policy or self.policy
        device_path = self.device_dir(server, node)
        path_parts = [device_path, get_data_dir(policy)]
        if part is not None:
            path_parts.append(str(part))
        return os.path.join(*path_parts)

    def config_number(self, node):
        _server_type, config_number = get_server_number(
            node['port'], self.port2server)
        return config_number

    def get_to_final_state(self):
        # these .stop()s are probably not strictly necessary,
        # but may prevent race conditions
        self.replicators.stop()
        self.updaters.stop()

        self.replicators.once()
        self.updaters.once()
        self.replicators.once()

class ReplProbeTest(ProbeTest):

    acct_cont_required_replicas = 3
    acct_cont_required_devices = 4
    obj_required_replicas = 3
    obj_required_devices = 4
    policy_requirements = {'policy_type': REPL_POLICY}

class ECProbeTest(ProbeTest):

    acct_cont_required_replicas = 3
    acct_cont_required_devices = 4
    obj_required_replicas = 6
    obj_required_devices = 8
    policy_requirements = {'policy_type': EC_POLICY}

if __name__ == "__main__":
    for server in ('account', 'container'):
        try:
            get_ring(server, 3, 4,
                     force_validate=True)
        except SkipTest as err:
            sys.exit('%s ERROR: %s' % (server, err))
        print '%s OK' % server
    for policy in POLICIES:
        try:
            get_ring(policy.ring_name, 3, 4,
                     server='object', force_validate=True)
        except SkipTest as err:
            sys.exit('object ERROR (%s): %s' % (policy.name, err))
        print 'object OK (%s)' % policy.name


text:
<?php

namespace Fakerino\DataSource\File;

use Fakerino\DataSource\File\Exception\FileEmptyException;
use Fakerino\DataSource\File\Exception\FileLineNotFoundException;
use Fakerino\DataSource\File\Exception\FileNotFoundException;

/**
 * Class File
 *
 * @author Nicola Pietroluongo <nik.longstone@gmail.com>
 */
class File extends \SplFileInfo
{
    /**
     * Constructor
     *
     * @param string $path
     *
     * @throws FileNotFoundException
     */
    public function __construct($path)
    {
        if (!file_exists($path)) {
            throw new FileNotFoundException($path);
        }

        parent::__construct($path);
    }

    /**
     * @return string
     */
    public function getFileName()
    {
        return basename($this->getRealPath());
    }

    /**
     * @return mixed
     */
    public function getMimeType()
    {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);

        return finfo_file($finfo, $this->getRealPath());
    }

    /**
     * @return string
     */
    public function getExtension()
    {
        return pathinfo($this->getBasename(), PATHINFO_EXTENSION);
    }

    /**
     * @return string
     * @throws Exception\FileEmptyException
     */
    public function getContent()
    {
        if ($content = file_get_contents($this->getRealPath())) {

            return $content;
        } else {
            throw new FileEmptyException($this->getRealPath());
        }
    }

    /**
     * @param int $lineNumber
     *
     * @return string
     * @throws Exception\FileLineNotFoundException
     */
    public function readLine($lineNumber)
    {
        $content = $this->getContent();
        if (count($content) > $lineNumber) {

            return $content[$lineNumber];
        } else {
            throw new FileLineNotFoundException($this->getRealPath(), $lineNumber);
        }
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->getRealPath();
    }
}


text:
package xyy.note.jdbc.model;

/**
 * Created by xyy on 2017/3/2.
 */
public class TransInfo {
}


text:
<?php

namespace spec\CodingBerlin\ExtraPromotionPlugin\Promotion\Rule;

use CodingBerlin\ExtraPromotionPlugin\Promotion\Rule\BirthdayRuleChecker;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;

class BirthdayRuleCheckerSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(BirthdayRuleChecker::class);
    }

    function it_is_a_rule_checker()
    {
        $this->shouldImplement(RuleCheckerInterface::class);
    }

    function it_allows_the_customer_having_birthday_today_to_receive_a_promotion(
        OrderInterface $order,
        CustomerInterface $customer
    ) {
        $order->getCustomer()->willReturn($customer);
        $customer->getBirthday()->willReturn(new \DateTime());
        $this->isEligible($order, [])->shouldReturn(true);
    }

    function it_does_not_allow_the_customer_not_having_birthday_today_to_receive_a_promotion(
        OrderInterface $order,
        CustomerInterface $customer
    ) {
        $birthday = new \DateTime();
        $birthday->add(new \DateInterval('P01D'));

        $order->getCustomer()->willReturn($customer);
        $customer->getBirthday()->willReturn($birthday);
        $this->isEligible($order, [])->shouldReturn(false);
    }
}


text:
'use strict'

const log = require('loglevel')

module.exports = log


text:
import os
import json
import functools
import pickle
import pytest
import yaml
import numpy as np
import pandas as pd
import lightgbm as lgb
import matplotlib as mpl
from packaging.version import Version
from sklearn import datasets
from unittest import mock

import mlflow
import mlflow.lightgbm
from mlflow.lightgbm import _autolog_callback
from mlflow.models import Model
from mlflow.models.utils import _read_example
from mlflow import MlflowClient
from mlflow.utils.autologging_utils import picklable_exception_safe_function, BatchMetricsLogger
from unittest.mock import patch

mpl.use("Agg")

def get_latest_run():
    client = MlflowClient()
    return client.get_run(client.search_runs(["0"])[0].info.run_id)

def get_model_conf(artifact_uri, model_subpath="model"):
    model_conf_path = os.path.join(artifact_uri, model_subpath, "MLmodel")
    return Model.load(model_conf_path)

@pytest.fixture(scope="module")
def bst_params():
    return {
        "objective": "multiclass",
        "num_class": 3,
    }

@pytest.fixture(scope="module")
def train_set():
    iris = datasets.load_iris()
    X = pd.DataFrame(iris.data[:, :2], columns=iris.feature_names[:2])
    y = iris.target
    # set free_raw_data False to use raw data later.
    return lgb.Dataset(X, y, free_raw_data=False)

def test_lgb_autolog_ends_auto_created_run(bst_params, train_set):
    mlflow.lightgbm.autolog()
    lgb.train(bst_params, train_set, num_boost_round=1)
    assert mlflow.active_run() is None

def test_lgb_autolog_persists_manually_created_run(bst_params, train_set):
    mlflow.lightgbm.autolog()
    with mlflow.start_run() as run:
        lgb.train(bst_params, train_set, num_boost_round=1)
        assert mlflow.active_run()
        assert mlflow.active_run().info.run_id == run.info.run_id

def test_lgb_autolog_logs_default_params(bst_params, train_set):
    mlflow.lightgbm.autolog()
    lgb.train(bst_params, train_set)
    run = get_latest_run()
    params = run.data.params

    expected_params = {
        "num_boost_round": 100,
        "feature_name": "auto",
        "categorical_feature": "auto",
        "keep_training_booster": False,
    }
    if Version(lgb.__version__) <= Version("3.3.1"):
        # The parameter `verbose_eval` in `lightgbm.train` is removed in this PR:
        # https://github.com/microsoft/LightGBM/pull/4878
        expected_params["verbose_eval"] = (
            # The default value of `verbose_eval` in `lightgbm.train` has been changed to 'warn'
            # in this PR: https://github.com/microsoft/LightGBM/pull/4577
            "warn"
            if Version(lgb.__version__) > Version("3.2.1")
            else True
        )
    expected_params.update(bst_params)

    for key, val in expected_params.items():
        assert key in params
        assert params[key] == str(val)

    unlogged_params = [
        "params",
        "train_set",
        "valid_sets",
        "valid_names",
        "fobj",
        "feval",
        "init_model",
        "learning_rates",
        "callbacks",
    ]
    if Version(lgb.__version__) <= Version("3.3.1"):
        # The parameter `evals_result` in `lightgbm.train` is removed in this PR:
        # https://github.com/microsoft/LightGBM/pull/4882
        unlogged_params.append("evals_result")

    for param in unlogged_params:
        assert param not in params

def test_lgb_autolog_logs_specified_params(bst_params, train_set):
    mlflow.lightgbm.autolog()
    expected_params = {
        "num_boost_round": 10,
    }
    if Version(lgb.__version__) <= Version("3.3.1"):
        # The parameter `verbose_eval` in `lightgbm.train` is removed in this PR:
        # https://github.com/microsoft/LightGBM/pull/4878
        # The parameter `early_stopping_rounds` in `lightgbm.train` is removed in this PR:
        # https://github.com/microsoft/LightGBM/pull/4908
        expected_params["verbose_eval"] = False
        expected_params["early_stopping_rounds"] = 5
    lgb.train(bst_params, train_set, valid_sets=[train_set], **expected_params)
    run = get_latest_run()
    params = run.data.params

    expected_params.update(bst_params)

    for key, val in expected_params.items():
        assert key in params
        assert params[key] == str(val)

    unlogged_params = [
        "params",
        "train_set",
        "valid_sets",
        "valid_names",
        "fobj",
        "feval",
        "init_model",
        "learning_rates",
        "callbacks",
    ]
    if Version(lgb.__version__) <= Version("3.3.1"):
        # The parameter `evals_result` in `lightgbm.train` is removed in this PR:
        # https://github.com/microsoft/LightGBM/pull/4882
        unlogged_params.append("evals_result")

    for param in unlogged_params:
        assert param not in params

def test_lgb_autolog_sklearn():

    mlflow.lightgbm.autolog()

    X, y = datasets.load_iris(return_X_y=True)
    params = {"n_estimators": 10, "reg_lambda": 1}
    model = lgb.LGBMClassifier(**params)

    with mlflow.start_run() as run:
        model.fit(X, y)
        model_uri = mlflow.get_artifact_uri("model")

    client = MlflowClient()
    run = client.get_run(run.info.run_id)
    assert run.data.metrics.items() <= params.items()
    artifacts = {x.path for x in client.list_artifacts(run.info.run_id)}
    assert artifacts >= {
        "feature_importance_gain.png",
        "feature_importance_gain.json",
        "feature_importance_split.png",
        "feature_importance_split.json",
    }
    loaded_model = mlflow.lightgbm.load_model(model_uri)
    np.testing.assert_allclose(loaded_model.predict(X), model.predict(X))

def test_lgb_autolog_with_sklearn_outputs_do_not_reflect_training_dataset_mutations():
    original_lgb_classifier_fit = lgb.LGBMClassifier.fit
    original_lgb_classifier_predict = lgb.LGBMClassifier.predict

    def patched_lgb_classifier_fit(self, *args, **kwargs):
        X = args[0]
        X["TESTCOL"] = 5
        return original_lgb_classifier_fit(self, *args, **kwargs)

    def patched_lgb_classifier_predict(self, *args, **kwargs):
        X = args[0]
        X["TESTCOL"] = 5
        return original_lgb_classifier_predict(self, *args, **kwargs)

    with mock.patch("lightgbm.LGBMClassifier.fit", patched_lgb_classifier_fit), mock.patch(
        "lightgbm.LGBMClassifier.predict", patched_lgb_classifier_predict
    ):
        mlflow.lightgbm.autolog(log_models=True, log_model_signatures=True, log_input_examples=True)

        X = pd.DataFrame(
            {
                "Total Volume": [64236.62, 54876.98, 118220.22],
                "Total Bags": [8696.87, 9505.56, 8145.35],
                "Small Bags": [8603.62, 9408.07, 8042.21],
                "Large Bags": [93.25, 97.49, 103.14],
                "XLarge Bags": [0.0, 0.0, 0.0],
            }
        )
        y = pd.Series([1, 0, 1])

        params = {"n_estimators": 10, "reg_lambda": 1}
        model = lgb.LGBMClassifier(**params)
        model.fit(X, y)

        run_artifact_uri = mlflow.last_active_run().info.artifact_uri
        model_conf = get_model_conf(run_artifact_uri)
        input_example = pd.read_json(
            os.path.join(run_artifact_uri, "model", "input_example.json"), orient="split"
        )
        model_signature_input_names = [inp.name for inp in model_conf.signature.inputs.inputs]
        assert "XLarge Bags" in model_signature_input_names
        assert "XLarge Bags" in input_example.columns
        assert "TESTCOL" not in model_signature_input_names
        assert "TESTCOL" not in input_example.columns

def test_lgb_autolog_logs_metrics_with_validation_data(bst_params, train_set):
    mlflow.lightgbm.autolog()
    evals_result = {}
    if Version(lgb.__version__) <= Version("3.3.1"):
        lgb.train(
            bst_params,
            train_set,
            num_boost_round=10,
            valid_sets=[train_set],
            valid_names=["train"],
            evals_result=evals_result,
        )
    else:
        lgb.train(
            bst_params,
            train_set,
            num_boost_round=10,
            valid_sets=[train_set],
            valid_names=["train"],
            callbacks=[lgb.record_evaluation(evals_result)],
        )
    run = get_latest_run()
    data = run.data
    client = MlflowClient()
    metric_key = "train-multi_logloss"
    metric_history = [x.value for x in client.get_metric_history(run.info.run_id, metric_key)]
    assert metric_key in data.metrics
    assert len(metric_history) == 10
    assert metric_history == evals_result["train"]["multi_logloss"]

def test_lgb_autolog_logs_metrics_with_multi_validation_data(bst_params, train_set):
    mlflow.lightgbm.autolog()
    evals_result = {}
    # If we use [train_set, train_set] here, LightGBM ignores the first dataset.
    # To avoid that, create a new Dataset object.
    valid_sets = [train_set, lgb.Dataset(train_set.data)]
    valid_names = ["train", "valid"]
    if Version(lgb.__version__) <= Version("3.3.1"):
        lgb.train(
            bst_params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            evals_result=evals_result,
        )
    else:
        lgb.train(
            bst_params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            callbacks=[lgb.record_evaluation(evals_result)],
        )
    run = get_latest_run()
    data = run.data
    client = MlflowClient()
    for valid_name in valid_names:
        metric_key = "{}-multi_logloss".format(valid_name)
        metric_history = [x.value for x in client.get_metric_history(run.info.run_id, metric_key)]
        assert metric_key in data.metrics
        assert len(metric_history) == 10
        assert metric_history == evals_result[valid_name]["multi_logloss"]

def test_lgb_autolog_logs_metrics_with_multi_metrics(bst_params, train_set):
    mlflow.lightgbm.autolog()
    evals_result = {}
    params = {"metric": ["multi_error", "multi_logloss"]}
    params.update(bst_params)
    valid_sets = [train_set]
    valid_names = ["train"]
    if Version(lgb.__version__) <= Version("3.3.1"):
        lgb.train(
            params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            evals_result=evals_result,
        )
    else:
        lgb.train(
            params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            callbacks=[lgb.record_evaluation(evals_result)],
        )
    run = get_latest_run()
    data = run.data
    client = MlflowClient()
    for metric_name in params["metric"]:
        metric_key = "{}-{}".format(valid_names[0], metric_name)
        metric_history = [x.value for x in client.get_metric_history(run.info.run_id, metric_key)]
        assert metric_key in data.metrics
        assert len(metric_history) == 10
        assert metric_history == evals_result["train"][metric_name]

def test_lgb_autolog_logs_metrics_with_multi_validation_data_and_metrics(bst_params, train_set):
    mlflow.lightgbm.autolog()
    evals_result = {}
    params = {"metric": ["multi_error", "multi_logloss"]}
    params.update(bst_params)
    valid_sets = [train_set, lgb.Dataset(train_set.data)]
    valid_names = ["train", "valid"]
    if Version(lgb.__version__) <= Version("3.3.1"):
        lgb.train(
            params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            evals_result=evals_result,
        )
    else:
        lgb.train(
            params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            callbacks=[lgb.record_evaluation(evals_result)],
        )
    run = get_latest_run()
    data = run.data
    client = MlflowClient()
    for valid_name in valid_names:
        for metric_name in params["metric"]:
            metric_key = "{}-{}".format(valid_name, metric_name)
            metric_history = [
                x.value for x in client.get_metric_history(run.info.run_id, metric_key)
            ]
            assert metric_key in data.metrics
            assert len(metric_history) == 10
            assert metric_history == evals_result[valid_name][metric_name]

def test_lgb_autolog_batch_metrics_logger_logs_expected_metrics(bst_params, train_set):
    patched_metrics_data = []

    # Mock patching BatchMetricsLogger.record_metrics()
    # to ensure that expected metrics are being logged.
    original = BatchMetricsLogger.record_metrics

    with patch(
        "mlflow.utils.autologging_utils.BatchMetricsLogger.record_metrics", autospec=True
    ) as record_metrics_mock:

        def record_metrics_side_effect(self, metrics, step=None):
            patched_metrics_data.extend(metrics.items())
            original(self, metrics, step)

        record_metrics_mock.side_effect = record_metrics_side_effect

        mlflow.lightgbm.autolog()
        evals_result = {}
        params = {"metric": ["multi_error", "multi_logloss"]}
        params.update(bst_params)
        valid_sets = [train_set, lgb.Dataset(train_set.data)]
        valid_names = ["train", "valid"]
        if Version(lgb.__version__) <= Version("3.3.1"):
            lgb.train(
                params,
                train_set,
                num_boost_round=10,
                valid_sets=valid_sets,
                valid_names=valid_names,
                evals_result=evals_result,
            )
        else:
            lgb.train(
                params,
                train_set,
                num_boost_round=10,
                valid_sets=valid_sets,
                valid_names=valid_names,
                callbacks=[lgb.record_evaluation(evals_result)],
            )

    run = get_latest_run()
    original_metrics = run.data.metrics
    patched_metrics_data = dict(patched_metrics_data)
    for metric_name in original_metrics:
        assert metric_name in patched_metrics_data
        assert original_metrics[metric_name] == patched_metrics_data[metric_name]

    assert "train-multi_logloss" in original_metrics
    assert "train-multi_logloss" in patched_metrics_data

def ranking_dataset(num_rows=100, num_queries=10):
    # https://stackoverflow.com/a/67621253
    num_rows_per_query = num_rows // num_queries
    df = pd.DataFrame(
        {
            "query_id": [i for i in range(num_queries) for _ in range(num_rows_per_query)],
            "f1": np.random.random(size=(num_rows,)),
            "f2": np.random.random(size=(num_rows,)),
            "relevance": np.random.randint(2, size=(num_rows,)),
        }
    )
    train_size = int(num_rows * 0.75)
    df_train = df[:train_size]
    df_valid = df[train_size:]
    # Train
    group_train = df_train.groupby("query_id")["query_id"].count().to_numpy()
    X_train = df_train.drop(["query_id", "relevance"], axis=1)
    y_train = df_train["relevance"]
    train_set = lgb.Dataset(X_train, y_train, group=group_train)
    # Validation
    group_val = df_valid.groupby("query_id")["query_id"].count().to_numpy()
    X_valid = df_valid.drop(["query_id", "relevance"], axis=1)
    y_valid = df_valid["relevance"]
    valid_set = lgb.Dataset(X_valid, y_valid, group=group_val)
    return train_set, valid_set

def test_lgb_autolog_atsign_metrics(train_set):
    train_set, valid_set = ranking_dataset()
    mlflow.lightgbm.autolog()
    params = {"objective": "regression", "metric": ["map"], "eval_at": [1]}
    lgb.train(
        params,
        train_set,
        valid_sets=[valid_set],
        valid_names=["valid"],
        num_boost_round=5,
    )
    run = get_latest_run()
    assert set(run.data.metrics) == {"valid-map_at_1"}

def test_lgb_autolog_logs_metrics_with_early_stopping(bst_params, train_set):
    mlflow.lightgbm.autolog()
    evals_result = {}
    params = {"metric": ["multi_error", "multi_logloss"]}
    params.update(bst_params)
    valid_sets = [train_set, lgb.Dataset(train_set.data)]
    valid_names = ["train", "valid"]
    if Version(lgb.__version__) <= Version("3.3.1"):
        model = lgb.train(
            params,
            train_set,
            num_boost_round=10,
            early_stopping_rounds=5,
            valid_sets=valid_sets,
            valid_names=valid_names,
            evals_result=evals_result,
        )
    else:
        model = lgb.train(
            params,
            train_set,
            num_boost_round=10,
            valid_sets=valid_sets,
            valid_names=valid_names,
            callbacks=[
                lgb.record_evaluation(evals_result),
                lgb.early_stopping(5),
            ],
        )
    run = get_latest_run()
    data = run.data
    client = MlflowClient()
    assert "best_iteration" in data.metrics
    assert int(data.metrics["best_iteration"]) == model.best_iteration
    assert "stopped_iteration" in data.metrics
    assert int(data.metrics["stopped_iteration"]) == len(evals_result["train"]["multi_logloss"])

    for valid_name in valid_names:
        for metric_name in params["metric"]:
            metric_key = "{}-{}".format(valid_name, metric_name)
            metric_history = [
                x.value for x in client.get_metric_history(run.info.run_id, metric_key)
            ]
            assert metric_key in data.metrics

            best_metrics = evals_result[valid_name][metric_name][model.best_iteration - 1]
            assert metric_history == evals_result[valid_name][metric_name] + [best_metrics]

def test_lgb_autolog_logs_feature_importance(bst_params, train_set):
    mlflow.lightgbm.autolog()
    model = lgb.train(bst_params, train_set, num_boost_round=10)
    run = get_latest_run()
    run_id = run.info.run_id
    artifacts_dir = run.info.artifact_uri.replace("file://", "")
    client = MlflowClient()
    artifacts = [x.path for x in client.list_artifacts(run_id)]

    for imp_type in ["split", "gain"]:
        plot_name = "feature_importance_{}.png".format(imp_type)
        assert plot_name in artifacts

        json_name = "feature_importance_{}.json".format(imp_type)
        assert json_name in artifacts

        json_path = os.path.join(artifacts_dir, json_name)
        with open(json_path, "r") as f:
            loaded_imp = json.load(f)

        features = model.feature_name()
        importance = model.feature_importance(importance_type=imp_type)
        imp = dict(zip(features, importance.tolist()))

        assert loaded_imp == imp

def test_no_figure_is_opened_after_logging(bst_params, train_set):
    mlflow.lightgbm.autolog()
    lgb.train(bst_params, train_set, num_boost_round=10)
    assert mpl.pyplot.get_fignums() == []

def test_lgb_autolog_loads_model_from_artifact(bst_params, train_set):
    mlflow.lightgbm.autolog()
    model = lgb.train(bst_params, train_set, num_boost_round=10)
    run = get_latest_run()
    run_id = run.info.run_id

    loaded_model = mlflow.lightgbm.load_model("runs:/{}/model".format(run_id))
    np.testing.assert_array_almost_equal(
        model.predict(train_set.data), loaded_model.predict(train_set.data)
    )

def test_lgb_autolog_gets_input_example(bst_params):
    # we need to check the example input against the initial input given to train function.
    # we can't use the train_set fixture for this as it defines free_raw_data=False but this
    # feature should work even if it is True
    iris = datasets.load_iris()
    X = pd.DataFrame(iris.data[:, :2], columns=iris.feature_names[:2])
    y = iris.target
    dataset = lgb.Dataset(X, y, free_raw_data=True)

    mlflow.lightgbm.autolog(log_input_examples=True)
    lgb.train(bst_params, dataset)
    run = get_latest_run()

    model_path = os.path.join(run.info.artifact_uri, "model")
    model_conf = Model.load(os.path.join(model_path, "MLmodel"))

    input_example = _read_example(model_conf, model_path)

    pd.testing.assert_frame_equal(input_example, (X[:5]))

    pyfunc_model = mlflow.pyfunc.load_model(os.path.join(run.info.artifact_uri, "model"))

    # make sure reloading the input_example and predicting on it does not error
    pyfunc_model.predict(input_example)

def test_lgb_autolog_infers_model_signature_correctly(bst_params):
    iris = datasets.load_iris()
    X = pd.DataFrame(iris.data[:, :2], columns=iris.feature_names[:2])
    y = iris.target
    dataset = lgb.Dataset(X, y, free_raw_data=True)

    mlflow.lightgbm.autolog(log_model_signatures=True)
    lgb.train(bst_params, dataset)
    run = get_latest_run()
    run_id = run.info.run_id
    artifacts_dir = run.info.artifact_uri.replace("file://", "")
    client = MlflowClient()
    artifacts = [x.path for x in client.list_artifacts(run_id, "model")]

    ml_model_filename = "MLmodel"
    assert str(os.path.join("model", ml_model_filename)) in artifacts
    ml_model_path = os.path.join(artifacts_dir, "model", ml_model_filename)

    data = None
    with open(ml_model_path, "r") as f:
        data = yaml.load(f, Loader=yaml.FullLoader)

    assert data is not None
    assert "signature" in data
    signature = data["signature"]
    assert signature is not None

    assert "inputs" in signature
    assert json.loads(signature["inputs"]) == [
        {"name": "sepal length (cm)", "type": "double"},
        {"name": "sepal width (cm)", "type": "double"},
    ]

    assert "outputs" in signature
    assert json.loads(signature["outputs"]) == [
        {"type": "tensor", "tensor-spec": {"dtype": "float64", "shape": [-1, 3]}},
    ]

def test_lgb_autolog_continues_logging_even_if_signature_inference_fails(tmpdir):
    tmp_csv = tmpdir.join("data.csv")
    tmp_csv.write("2,6.4,2.8,5.6,2.2\n")
    tmp_csv.write("1,5.0,2.3,3.3,1.0\n")
    tmp_csv.write("2,4.9,2.5,4.5,1.7\n")
    tmp_csv.write("0,4.9,3.1,1.5,0.1\n")
    tmp_csv.write("0,5.7,3.8,1.7,0.3\n")

    # signature and input example inference should fail here since the dataset is given
    #   as a file path
    dataset = lgb.Dataset(tmp_csv.strpath)

    bst_params = {
        "objective": "multiclass",
        "num_class": 3,
    }

    mlflow.lightgbm.autolog(log_model_signatures=True)
    lgb.train(bst_params, dataset)
    run = get_latest_run()
    run_id = run.info.run_id
    artifacts_dir = run.info.artifact_uri.replace("file://", "")
    client = MlflowClient()
    artifacts = [x.path for x in client.list_artifacts(run_id, "model")]

    ml_model_filename = "MLmodel"
    assert os.path.join("model", ml_model_filename) in artifacts
    ml_model_path = os.path.join(artifacts_dir, "model", ml_model_filename)

    data = None
    with open(ml_model_path, "r") as f:
        data = yaml.load(f, Loader=yaml.FullLoader)

    assert data is not None
    assert "run_id" in data
    assert "signature" not in data

@pytest.mark.parametrize("log_input_examples", [True, False])
@pytest.mark.parametrize("log_model_signatures", [True, False])
def test_lgb_autolog_configuration_options(bst_params, log_input_examples, log_model_signatures):
    iris = datasets.load_iris()
    X = pd.DataFrame(iris.data[:, :2], columns=iris.feature_names[:2])
    y = iris.target

    with mlflow.start_run() as run:
        mlflow.lightgbm.autolog(
            log_input_examples=log_input_examples, log_model_signatures=log_model_signatures
        )
        dataset = lgb.Dataset(X, y)
        lgb.train(bst_params, dataset)
    model_conf = get_model_conf(run.info.artifact_uri)
    assert ("saved_input_example_info" in model_conf.to_dict()) == log_input_examples
    assert ("signature" in model_conf.to_dict()) == log_model_signatures

@pytest.mark.parametrize("log_models", [True, False])
def test_lgb_autolog_log_models_configuration(bst_params, log_models):
    iris = datasets.load_iris()
    X = pd.DataFrame(iris.data[:, :2], columns=iris.feature_names[:2])
    y = iris.target

    with mlflow.start_run() as run:
        mlflow.lightgbm.autolog(log_models=log_models)
        dataset = lgb.Dataset(X, y)
        lgb.train(bst_params, dataset)

    run_id = run.info.run_id
    client = MlflowClient()
    artifacts = [f.path for f in client.list_artifacts(run_id)]
    assert ("model" in artifacts) == log_models

def test_lgb_autolog_does_not_break_dataset_instantiation_with_data_none():
    """
    This test verifies that `lightgbm.Dataset(None)` doesn't fail after patching.
    LightGBM internally calls `lightgbm.Dataset(None)` to create a subset of `Dataset`:
    https://github.com/microsoft/LightGBM/blob/v3.0.0/python-package/lightgbm/basic.py#L1381
    """
    mlflow.lightgbm.autolog()
    lgb.Dataset(None)

def test_callback_func_is_pickable():
    cb = picklable_exception_safe_function(
        functools.partial(_autolog_callback, BatchMetricsLogger(run_id="1234"), eval_results={})
    )
    pickle.dumps(cb)

def test_sklearn_api_autolog_registering_model():
    registered_model_name = "test_autolog_registered_model"
    mlflow.lightgbm.autolog(registered_model_name=registered_model_name)

    X, y = datasets.load_iris(return_X_y=True)
    params = {"n_estimators": 10, "reg_lambda": 1}
    model = lgb.LGBMClassifier(**params)

    with mlflow.start_run():
        model.fit(X, y)

        registered_model = MlflowClient().get_registered_model(registered_model_name)
        assert registered_model.name == registered_model_name

def test_lgb_api_autolog_registering_model(bst_params, train_set):
    registered_model_name = "test_autolog_registered_model"
    mlflow.lightgbm.autolog(registered_model_name=registered_model_name)

    with mlflow.start_run():
        lgb.train(bst_params, train_set, num_boost_round=1)

        registered_model = MlflowClient().get_registered_model(registered_model_name)
        assert registered_model.name == registered_model_name


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jogl.materials;

import org.jogl.api.PhongMaterial;
import org.jogl.api.Shader;
import org.jogl.api.Texture;
import org.joml.Vector3f;

/**
 *
 * @author luis
 */
public class SmoothMaterial implements PhongMaterial {

    private final Vector3f ambientMaterial;
    private final Vector3f diffuseMaterial;
    private final Vector3f specularMaterial;
    private final float specularPower;
    private Texture texture;

    public SmoothMaterial() {
        this(new Vector3f());
    }

    public SmoothMaterial(Vector3f color) {
        this(color, null);
    }

    public SmoothMaterial(Vector3f color, Texture texture) {
        this(new Vector3f(0.2f, 0.2f, 0.2f), new Vector3f(0.7f, 0.7f, 0.7f), new Vector3f(0.5f, 0.5f, 0.5f), 100.0f, color, texture);
    }

    public SmoothMaterial(Vector3f ambientMaterial, Vector3f diffuseMaterial, Vector3f specularMaterial, float specularPower, Vector3f color, Texture texture) {
        this.ambientMaterial = ambientMaterial.mul(color);
        this.diffuseMaterial = diffuseMaterial.mul(color);
        this.specularMaterial = specularMaterial.mul(color);
        this.specularPower = specularPower;
    }

    @Override
    public Shader getShader() {
        return null;
    }

    @Override
    public Texture getTexture() {
        return texture;
    }

    public SmoothMaterial setTexture(Texture texture) {
        this.texture = texture;
        return this;
    }

    @Override
    public Vector3f getAmbientMaterial() {
        return ambientMaterial;
    }

    @Override
    public Vector3f getDiffuseMaterial() {
        return diffuseMaterial;
    }

    @Override
    public Vector3f getSpecularMaterial() {
        return specularMaterial;
    }

    @Override
    public float getSpecularPower() {
        return specularPower;
    }

}


text:
package org.slf4j.impl;

import java.util.Optional;
import org.apache.maven.logwrapper.LogLevelRecorder;
import org.apache.maven.logwrapper.MavenSlf4jWrapperFactory;
import org.slf4j.Logger;

/**
 * LogFactory for Maven which can create a simple logger or one which, if set, fails the build on a severity threshold.
 */
public class MavenLoggerFactory extends SimpleLoggerFactory implements MavenSlf4jWrapperFactory {
    private LogLevelRecorder logLevelRecorder = null;

    @Override
    public void setLogLevelRecorder(LogLevelRecorder logLevelRecorder) {
        if (this.logLevelRecorder != null) {
            throw new IllegalStateException("LogLevelRecorder has already been set.");
        }

        this.logLevelRecorder = logLevelRecorder;
    }

    @Override
    public Optional<LogLevelRecorder> getLogLevelRecorder() {
        return Optional.ofNullable(logLevelRecorder);
    }

    /**
     * Return an appropriate {@link MavenSimpleLogger} instance by name.
     */
    @Override
    public Logger getLogger(String name) {
        Logger simpleLogger = loggerMap.get(name);
        if (simpleLogger != null) {
            return simpleLogger;
        } else {
            Logger newInstance = getNewLoggingInstance(name);
            Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
            return oldInstance == null ? newInstance : oldInstance;
        }
    }

    private Logger getNewLoggingInstance(String name) {
        if (logLevelRecorder == null) {
            return new MavenSimpleLogger(name);
        } else {
            return new MavenFailOnSeverityLogger(name, logLevelRecorder);
        }
    }
}


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Components/TargetingSystemComponent.h"
#include "ConicalTargetingSystemComponent.generated.h"

/**
 *
 */
UCLASS()
class TWOBROTHERS_API UConicalTargetingSystemComponent : public UTargetingSystemComponent
{
	GENERATED_BODY()

public:

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		float RadiusAtStart;

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		float RadiusAtEnd;

	virtual void SetCurrentTarget() override;

};


text:
<?php

namespace Lunr\Gravity\Database\MySQL\Tests;

use Lunr\Gravity\Database\MySQL\MySQLDMLQueryBuilder;
use ReflectionClass;

/**
 * This class contains select tests for the MySQLSimpleDMLQueryBuilder class.
 *
 * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder
 */
class MySQLSimpleDMLQueryBuilderSelectTest extends MySQLSimpleDMLQueryBuilderTest
{

    /**
     * Test get_insert_query() gets called correctly.
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::get_select_query
     */
    public function testGetSelectQuery(): void
    {
        $this->builder->expects($this->once())
                      ->method('get_select_query')
                      ->willReturn('');

        $this->class->get_select_query();
    }

    /**
     * Test select_mode() gets called correctly.
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::select_mode
     */
    public function testSelectMode(): void
    {
        $this->builder->expects($this->once())
                      ->method('select_mode')
                      ->with('ALL')
                      ->will($this->returnSelf());

        $this->class->select_mode('ALL');
    }

    /**
     * Test select() with one input column.
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::select
     */
    public function testSelectWithOneColumn(): void
    {
        $this->escaper->expects($this->once())
                      ->method('result_column')
                      ->with($this->equalTo('col'))
                      ->will($this->returnValue('`col`'));

        $this->builder->expects($this->once())
                      ->method('select')
                      ->with($this->equalTo('`col`'))
                      ->will($this->returnSelf());

        $this->class->select('col');
    }

    /**
     * Test select() with multiple input columns.
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::select
     */
    public function testSelectWithMultipleColumns(): void
    {
        $this->escaper->expects($this->exactly(2))
                      ->method('result_column')
                      ->withConsecutive([ 'col' ], [ ' col' ])
                      ->will($this->returnValue('`col`'));

        $this->builder->expects($this->once())
                      ->method('select')
                      ->with($this->equalTo('`col`, `col`'))
                      ->willReturn($this->returnSelf());

        $this->class->select('col, col');
    }

    /**
     * Test from().
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::from
     */
    public function testFrom(): void
    {
        $this->escaper->expects($this->once())
                      ->method('table')
                      ->with($this->equalTo('table'))
                      ->will($this->returnValue('`table`'));

        $this->builder->expects($this->once())
                      ->method('from')
                      ->with($this->equalTo('`table`'))
                      ->will($this->returnSelf());

        $this->class->from('table');
    }

    /**
     * Test join().
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::join
     */
    public function testJoin(): void
    {
        $this->escaper->expects($this->once())
                      ->method('table')
                      ->with($this->equalTo('table'))
                      ->will($this->returnValue('`table`'));

        $this->builder->expects($this->once())
                      ->method('join')
                      ->with($this->equalTo('`table`'))
                      ->will($this->returnSelf());

        $this->class->join('table');
    }

    /**
     * Test group_by().
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::group_by
     */
    public function testGroupBy(): void
    {
        $this->escaper->expects($this->once())
                      ->method('column')
                      ->with($this->equalTo('col'))
                      ->will($this->returnValue('`col`'));

        $this->builder->expects($this->once())
                      ->method('group_by')
                      ->with($this->equalTo('`col`'))
                      ->will($this->returnSelf());

        $this->class->group_by('col');
    }

    /**
     * Test order_by().
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::order_by
     */
    public function testOrderBy(): void
    {
        $this->escaper->expects($this->once())
                      ->method('column')
                      ->with($this->equalTo('col'))
                      ->will($this->returnValue('`col`'));

        $this->builder->expects($this->once())
                      ->method('order_by')
                      ->with($this->equalTo('`col`'), $this->equalTo(TRUE))
                      ->will($this->returnSelf());

        $this->class->order_by('col');
    }

    /**
     * Test limit().
     *
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::limit
     */
    public function testLimit(): void
    {
        $this->escaper->expects($this->exactly(2))
                      ->method('intvalue')
                      ->withConsecutive([ 10 ], [ -1 ])
                      ->will($this->returnArgument(0));

        $this->builder->expects($this->once())
                      ->method('limit')
                      ->with($this->equalTo(10))
                      ->will($this->returnSelf());

        $this->class->limit(10);
    }

    /**
     * Test union().
     * @dataProvider unionOperatorProvider
     * @covers Lunr\Gravity\Database\MySQL\MySQLSimpleDMLQueryBuilder::union
     */
    public function testUnion($operators): void
    {
        $this->escaper->expects($this->once())
                      ->method('query_value')
                      ->with('query')
                      ->willReturn('(query)');

        $this->builder->expects($this->once())
                      ->method('union')
                      ->with('(query)', $operators)
                      ->willReturnSelf();

        $this->class->union('query', $operators);
    }

}

?>