text:
<?php

namespace Fmt;

final class ConstructorPass extends FormatterPass
{
    const TYPE_CAMEL_CASE = 'camel';

    const TYPE_GOLANG = 'golang';

    const TYPE_SNAKE_CASE = 'snake';

    private $type;

    public function __construct($type = self::TYPE_CAMEL_CASE)
    {
        $this->type = self::TYPE_CAMEL_CASE;
        if (self::TYPE_CAMEL_CASE == $type || self::TYPE_SNAKE_CASE == $type || self::TYPE_GOLANG == $type) {
            $this->type = $type;
        }
    }

    public function candidate($source, $foundTokens)
    {
        if (isset($foundTokens[T_CLASS])) {
            return true;
        }

        return false;
    }

    public function format($source)
    {
        $this->tkns = token_get_all($source);
        $this->code = '';

        $classAttributes = [];
        $functionList = [];
        $touchedVisibility = false;
        $touchedFunction = false;
        $curlyCount = null;

        while (list($index, $token) = each($this->tkns)) {
            list($id, $text) = $this->getToken($token);
            $this->ptr = $index;
            switch ($id) {
                case T_CLASS:
                    $classAttributes = [];
                    $functionList = [];
                    $touchedVisibility = false;
                    $touchedFunction = false;
                    $curlyCount = null;
                    $this->appendCode($text);
                    while (list($index, $token) = each($this->tkns)) {
                        list($id, $text) = $this->getToken($token);
                        $this->ptr = $index;
                        if (ST_CURLY_OPEN == $id) {
                            ++$curlyCount;
                        }
                        if (ST_CURLY_CLOSE == $id) {
                            --$curlyCount;
                        }
                        if (0 === $curlyCount) {
                            break;
                        }
                        $this->appendCode($text);
                        if (T_PUBLIC == $id) {
                            $touchedVisibility = T_PUBLIC;
                        } elseif (T_PRIVATE == $id) {
                            $touchedVisibility = T_PRIVATE;
                        } elseif (T_PROTECTED == $id) {
                            $touchedVisibility = T_PROTECTED;
                        }
                        if (
                            T_VARIABLE == $id &&
                            (
                                T_PUBLIC == $touchedVisibility ||
                                T_PRIVATE == $touchedVisibility ||
                                T_PROTECTED == $touchedVisibility
                            )
                        ) {
                            $classAttributes[] = $text;
                            $touchedVisibility = null;
                        } elseif (T_FUNCTION == $id) {
                            $touchedFunction = true;
                        } elseif ($touchedFunction && T_STRING == $id) {
                            $functionList[] = $text;
                            $touchedVisibility = null;
                            $touchedFunction = false;
                        }
                    }
                    $functionList = array_combine($functionList, $functionList);
                    if (!isset($functionList['__construct'])) {
                        $this->appendCode('function __construct('.implode(', ', $classAttributes).'){'.$this->newLine);
                        foreach ($classAttributes as $var) {
                            $this->appendCode($this->generate($var));
                        }
                        $this->appendCode('}'.$this->newLine);
                    }

                    $this->appendCode($text);
                    break;
                default:
                    $this->appendCode($text);
                    break;
            }
        }

        return $this->code;
    }

    private function generate($var)
    {
        switch ($this->type) {
            case self::TYPE_SNAKE_CASE:
                $ret = $this->generateSnakeCase($var);
                break;
            case self::TYPE_GOLANG:
                $ret = $this->generateGolang($var);
                break;
            case self::TYPE_CAMEL_CASE:
            default:
                $ret = $this->generateCamelCase($var);
                break;
        }

        return $ret;
    }

    private function generateCamelCase($var)
    {
        $str = '$this->set'.ucfirst(str_replace('$', '', $var)).'('.$var.');'.$this->newLine;

        return $str;
    }

    private function generateGolang($var)
    {
        $str = '$this->Set'.ucfirst(str_replace('$', '', $var)).'('.$var.');'.$this->newLine;

        return $str;
    }

    private function generateSnakeCase($var)
    {
        $str = '$this->set_'.(str_replace('$', '', $var)).'('.$var.');'.$this->newLine;

        return $str;
    }
}


text:
#include "FileLoadCommand.h"
#include "OpenVDBItem.h"

CCommandLoadFile::CCommandLoadFile ()
{
	/*
	*	The constructor is a good place to add arguments and
	*	set flags for those arguments. This command will have
	*	a single argument for the filename. The flags will mark
	*	the argument as optional. This will prevent modo from
	*	launching a dialog to ask for a filename string and
	*	instead allow the command to handle the missing argument
	*	value by spawning a file dialog.
	*/

	dyna_Add(ARG_FILENAME, LXsTYPE_FILEPATH);
	basic_SetFlags(ARGi_FILENAME, LXfCMDARG_OPTIONAL);
}

	int
CCommandLoadFile::basic_CmdFlags ()
{
	/*
	*	The flags define if this should be an undoable command
	*	or not. If the command changes the state of the scene,
	*	then it should implement both the MODEL and UNDO flags.
	*/

	return LXfCMD_MODEL | LXfCMD_UNDO;
}

	bool
CCommandLoadFile::basic_Enable (
	CLxUser_Message &msg)
{
	/*
	*	In practice, a command usually has an enabled state and
	*	a disabled state. This function allows you to return True
	*	or False to enable/disable the command. A message interface
	*	is provided to allow you to pass detailed information about
	*	the enable state back to the user. This command is always
	*	enabled.
	*/

	return true;
}

	void
CCommandLoadFile::cmd_Interact ()
{
	/*
	*	When the command is executed, this function is first called.
	*	It's the ideal place to open a file dialog and ask for user
	*	interaction. The resulting path can then be passed to the
	*	commands execute method using the filename argument.
	*
	*	No scene or state altering code should be performed here.
	*/

	CLxUser_CommandService	 cmd_svc;
	CLxUser_Command		 command;
	CLxUser_ValueArray	 val_array;

	std::string		 filename = "";
	unsigned		 n = 0;

	/*
	*	Check if the filename argument is set, if it is, return early.
	*/

	if (dyna_IsSet (ARGi_FILENAME))
		return;

	/*
	*	Fire the commands to open the file dialog.
	*/

	cmd_svc.ExecuteArgString (-1, LXiCTAG_NULL, "dialog.setup fileOpen");
	cmd_svc.ExecuteArgString (-1, LXiCTAG_NULL, "dialog.title {Browse For Files...}");
	cmd_svc.ExecuteArgString (-1, LXiCTAG_NULL, "dialog.fileTypeCustom model {OpenVDB model} {*.vdb} vdb");
	cmd_svc.ExecuteArgString (-1, LXiCTAG_NULL, "dialog.open");

	/*
	*	Spawn a command that can be queried for the result.
	*/

	if (LXx_FAIL(cmd_svc.NewCommand (command, "dialog.result")))
		return;

	/*
	*	Query the first argument on the dialog.result command
	*	and store the results in a value array.
	*/

	if (LXx_FAIL(cmd_svc.QueryIndex (command, 0, val_array)))
		return;

	/*
	*	Get the number of elements in the array. There should
	*	only be one. If there are none, return early.
	*/

	n = val_array.Count ();

	if (!n)
		return;

	/*
	*	Read the string from the value array and set the filename
	*	argument to the value of the string.
	*/

	val_array.String (0, filename);
	attr_SetString (ARGi_FILENAME, filename.c_str ());
}

	void
CCommandLoadFile::cmd_Execute (
	unsigned	 flags)
{
	CLxUser_ItemPacketTranslation	 itemPkt;
	CLxUser_SelectionService	 srv_sel;
	CLxUser_ChannelWrite		 chanWrite;
	CLxUser_ChannelWrite		 chanWriteEdit;
	CLxSceneSelection		 scene_sel;
	CLxUser_Scene			 scene;
	CLxUser_Item			 item;
	CLxUser_ItemGraph		 graph;
	LXtID4				 selID_item;
	std::string			 filename = "";
	std::string			 currentFeature;
	void				*pkt;

	/*
	*	Use selection system to get current VDBVoxelItem
	*	for executing the command.
	*/

	selID_item = srv_sel.LookupType (LXsSELTYP_ITEM);
	pkt = srv_sel.Recent (selID_item);
	scene_sel.Get (scene);
	itemPkt.autoInit ();
	itemPkt.GetItem (pkt, item);

	if (pkt != NULL) {
		attr_GetString (ARGi_FILENAME, filename);
		chanWrite.setupFrom (scene);
		if (filename != "") {

			/*
			*	Update schematic graph link
			*/

			CLxUser_Scene		 scene;
			CLxUser_ItemGraph	 graph;
			CLxUser_Item		 old;

			if (scene.from (item) && graph.from (scene, GRAPH_VOXELITEM))
				while (graph.Reverse (item)) {
					graph.Reverse (item, 0, old);
					graph.DeleteLink (old, item);
				}

			/*
			*	Read only a small part of data from a VDB file for loading feature list.
			*	no voxel data is stored.
			*/

			OpenVDBItemPreLoader itemPreLoader (filename);
			chanWrite.Set (item, CN_DATA_FILE_NAME, filename.c_str());
			chanWrite.Set (item, CN_FILE_NAME, filename.c_str());

			std::string featureList;
			currentFeature = itemPreLoader.getFeatureNameList (featureList);
			chanWrite.Set (item, FEATURE_NAME_LIST, featureList.c_str());

			chanWriteEdit.from (item);
			chanWriteEdit.Set (item, CURRENT_FEATURE, currentFeature.c_str());
		}

	}
}

	LXtTagInfoDesc
CCommandLoadFile::descInfo[] = {
	{ 0 }
};

redpajama_set_name: RedPajamaGithub


text:
This is a sankey diagram visType plugin for Kibana 4.3+, 5.x.

This plugin was developped from <https://github.com/elastic/kibana/pull/4832>.

![](https://cloud.githubusercontent.com/assets/1219655/21418571/29e596d8-c85d-11e6-8060-11c0add8bf5b.png)

# Install

```
cd KIBANA_FOLDER_PATH/plugins/
git clone https://github.com/chenryn/kbn_sankey_vis.git
```

# Uninstall

```
bin/kibana plugin  --remove kbn_sankey_vis
```


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.Diagnostics.Runtime.Utilities
{
    /// <summary>
    /// A helper class to represent ELF program headers.
    /// </summary>
    public sealed class ElfProgramHeader
    {
        private readonly ElfProgramHeaderAttributes _attributes;

        internal IAddressSpace AddressSpace { get; }

        /// <summary>
        /// The type of header this is.
        /// </summary>
        public ElfProgramHeaderType Type { get; }

        /// <summary>
        /// The VirtualAddress of this header.
        /// </summary>
        public ulong VirtualAddress { get; }

        /// <summary>
        /// The size of this header.
        /// </summary>
        public ulong VirtualSize { get; }

        /// <summary>
        /// The offset of this header within the file.
        /// </summary>
        public ulong FileOffset { get; }

        /// <summary>
        /// The size of this header within the file.
        /// </summary>
        public ulong FileSize { get; }

        /// <summary>
        /// Whether this section of memory is executable.
        /// </summary>
        public bool IsExecutable => (_attributes & ElfProgramHeaderAttributes.Executable) != 0;

        /// <summary>
        /// Whether this section of memory is writable.
        /// </summary>
        public bool IsWritable => (_attributes & ElfProgramHeaderAttributes.Writable) != 0;

        internal ElfProgramHeader(Reader reader, bool is64bit, ulong headerPositon, long loadBias, bool isVirtual = false)
        {
            if (is64bit)
            {
                var header = reader.Read<ElfProgramHeader64>(headerPositon);
                _attributes = (ElfProgramHeaderAttributes)header.Flags;
                Type = header.Type;
                VirtualAddress = header.VirtualAddress;
                VirtualSize = header.VirtualSize;
                FileOffset = header.FileOffset;
                FileSize = header.FileSize;
            }
            else
            {
                var header = reader.Read<ElfProgramHeader32>(headerPositon);
                _attributes = (ElfProgramHeaderAttributes)header.Flags;
                Type = header.Type;
                VirtualAddress = header.VirtualAddress;
                VirtualSize = header.VirtualSize;
                FileOffset = header.FileOffset;
                FileSize = header.FileSize;
            }

            if (isVirtual)
            {
                ulong offset = (loadBias < 0) ? (ulong)((long)VirtualAddress + loadBias) : VirtualAddress + (ulong)loadBias;
                AddressSpace = new RelativeAddressSpace(reader.DataSource, "ProgramHeader", offset, VirtualSize);
            }
            else
            {
                ulong offset = (loadBias < 0) ? (ulong)((long)FileOffset + loadBias) : FileOffset + (ulong)loadBias;
                AddressSpace = new RelativeAddressSpace(reader.DataSource, "ProgramHeader", offset, FileSize);
            }
        }
    }
}


text: chrome extension to show your spotify playlist in the browser


text:
layout: "docs_api"
title: Supersonic API reference
header_sub_title: <%= apiPath %> overview
section_id: <%= section %>
subsection_id: <%= subsection %>
---
{% assign entry = <%= liquidDataPath %> %}
## Namespace: {{entry.namespace}}.{{entry.name}}

{{entry.description}}


text:
namespace base {
class FilePath;
}

namespace disk_cache {

// Performs all necessary disk IO to upgrade the cache structure if it is
// needed.
//
// Returns true iff no errors were found during consistency checks and all
// necessary transitions succeeded. If this function fails, there is nothing
// left to do other than dropping the whole cache directory.
NET_EXPORT_PRIVATE bool UpgradeSimpleCacheOnDisk(
    const base::FilePath& path,
    const SimpleExperiment& experiment);

struct NET_EXPORT_PRIVATE FakeIndexData {
  FakeIndexData();

  // Must be equal to simplecache_v4::kSimpleInitialMagicNumber.
  uint64_t initial_magic_number;

  // Must be equal kSimpleVersion when the cache backend is instantiated.
  uint32_t version;

  // The experiment that the cache was created for.
  SimpleExperimentType experiment_type;

  // The experiment's parameter.
  uint32_t experiment_param;
};

// Exposed for testing.
NET_EXPORT_PRIVATE bool UpgradeIndexV5V6(const base::FilePath& cache_directory);

}  // namespace disk_cache

#endif  // NET_DISK_CACHE_SIMPLE_SIMPLE_VERSION_UPGRADE_H_


text:
import * as React from 'react';
const PageNotFound = ({ location }: any) => (

    Page not found - the path, {location.pathname}, did not match any
    React Router routes.

);

export default PageNotFound;


text:
<?xml version="1.0" encoding="utf-8"?>

<ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/place_photo"
        android:layout_gravity="center_horizontal"
        android:adjustViewBounds="true"/>


text:
/**
 * @author Igor V. Stolyarov
 */
package com.google.code.appengine.awt;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;

import com.google.code.appengine.awt.Component;
import com.google.code.appengine.awt.Image;
import com.google.code.appengine.awt.MediaTracker;
import com.google.code.appengine.awt.image.ImageObserver;

public class MediaTracker implements Serializable {

    private static final long serialVersionUID = -483174189758638095L;

    public static final int ABORTED = 2;

    public static final int COMPLETE = 8;

    public static final int ERRORED = 4;

    public static final int LOADING = 1;

    Component owner;
    LinkedList<TrackingImage> trackingObjects = new LinkedList<TrackingImage>();

    public MediaTracker(Component comp) {
        owner = comp;
    }

    public void addImage(Image image, int id) {
        addImage(image, id, -1, -1);
    }

    public synchronized void addImage(Image image, int id, int w, int h) {
        int idx = 0;
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(id < node.getID()){
                idx = li.previousIndex();
                break;
            }
            idx = li.nextIndex();
        }
        trackingObjects.add(idx, new TrackingImage(this, image, id, w, h));
    }

    public boolean checkAll() {
        return checkAll(false);
    }

    public boolean checkAll(boolean load) {
        boolean result = true;
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(load) {
                node.loadMedia();
            }
            if((node.getState() & TrackingNode.LOADING_DONE) == 0){
                result = false;
            }
        }
        return result;
    }

    public boolean checkID(int id) {
        return checkID(id, false);
    }

    public boolean checkID(int id, boolean load) {
        boolean result = true;
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node.getID() == id){
                if(load) {
                    node.loadMedia();
                }
                if((node.getState() & TrackingNode.LOADING_DONE) == 0){
                    result = false;
                }
            }
        }
        return result;
    }

    public synchronized Object[] getErrorsAny() {
        ArrayList<Object> errors = new ArrayList<Object>();
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if((node.getState() & ERRORED) != 0){
                errors.add(node.getMediaObject());
            }
        }
        if(errors.size() == 0) {
            return null;
        }
        return errors.toArray();
    }

    public synchronized Object[] getErrorsID(int id) {
        ArrayList<Object> errors = new ArrayList<Object>();
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node.getID() == id){
                if((node.getState() & ERRORED) != 0){
                    errors.add(node.getMediaObject());
                }
            }
        }
        if(errors.size() == 0) {
            return null;
        }
        return errors.toArray();
    }

    public synchronized boolean isErrorAny() {
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if((node.getState() & ERRORED) != 0) {
                return true;
            }
        }
        return false;
    }

    public synchronized boolean isErrorID(int id) {
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node.getID() == id){
                if((node.getState() & ERRORED) != 0) {
                    return true;
                }
            }
        }
        return false;
    }

    public synchronized void removeImage(Image image) {
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node.getMediaObject() == image) {
                li.remove();
            }
        }
    }

    public synchronized void removeImage(Image image, int id) {
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node.getID() == id && node.getMediaObject() == image) {
                li.remove();
            }
        }
    }

    public synchronized void removeImage(Image image, int id, int width,
            int height) {
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(node instanceof TrackingImage){
                TrackingImage ti = (TrackingImage) node;
                if(ti.equals(image, id, width, height)) {
                    li.remove();
                }
            }
        }
    }

    public int statusAll(boolean load) {
        int status = 0;
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(load) {
                node.loadMedia();
            }
            status |= node.getState();
        }
        return status;
    }

    public int statusID(int id, boolean load) {
        int status = 0;
        ListIterator<TrackingImage> li = trackingObjects.listIterator();
        while(li.hasNext()){
            TrackingNode node = li.next();
            if(id == node.getID()){
                if(load) {
                    node.loadMedia();
                }
                status |= node.getState();
            }
        }
        return status;
    }

    public void waitForAll() throws InterruptedException {
        waitForAll(0);
    }

    public synchronized boolean waitForAll(long ms) throws InterruptedException {
        boolean needLoad = true;
        long finishtime = System.currentTimeMillis() + ms;
        while(true){
            int status = statusAll(needLoad);
            if((status & LOADING) == 0){
                return (status == COMPLETE);
            }
            needLoad = false;
            long timeout;
            if(ms == 0){
                timeout = 0;
            }else{
                long curtime = System.currentTimeMillis();
                if(finishtime <= curtime) {
                    return false;
                }
                timeout = finishtime - curtime;
            }
            wait(timeout);
        }
    }

    public void waitForID(int id) throws InterruptedException {
        waitForID(id , 0);
    }

    public synchronized boolean waitForID(int id, long ms)
            throws InterruptedException {
        boolean needLoad = true;
        long finishtime = System.currentTimeMillis() + ms;
        while(true){
            int status = statusID(id, needLoad);
            if((status & LOADING) == 0){
                return (status == COMPLETE);
            }
            needLoad = false;
            long timeout;
            if(ms == 0){
                timeout = 0;
            }else{
                long curtime = System.currentTimeMillis();
                if(finishtime <= curtime) {
                    return false;
                }
                timeout = finishtime - curtime;
            }
            wait(timeout);
        }
    }

    synchronized void refresh(){
        notifyAll();
    }

    abstract class TrackingNode{
        final static int LOADING_DONE = ABORTED | ERRORED | COMPLETE;
        final static int LOADING_STARTED = LOADING | ERRORED | COMPLETE;

        MediaTracker tracker;
        int id;
        int state;
        TrackingNode next;

        TrackingNode(MediaTracker tracker, int id){
            this.tracker = tracker;
            this.id = id;
        }

        abstract Object getMediaObject();
        abstract void loadMedia();
        abstract int getState();

        int getID(){
            return id;
        }

        void updateState(int state){
            synchronized(this){
                this.state = state;
            }
            tracker.refresh();
        }

    }

    class TrackingImage extends TrackingNode implements ImageObserver{
        Image img;
        int w, h;

        TrackingImage(MediaTracker tracker, Image image, int id, int w, int h) {
            super(tracker, id);
            img = image;
            this.w = w;
            this.h = h;
        }

        @Override
        Object getMediaObject() {
            return img;
        }

        @Override
        void loadMedia() {
            if((state & LOADING_STARTED) == 0){
                state = (state & ~ABORTED) | LOADING;
                if(tracker.owner.prepareImage(img, w, h, this)){
                    updateState(COMPLETE);
                }
            }
        }

        @Override
        synchronized int getState(){
            int infoflags = tracker.owner.checkImage(img, w, h, this);
            int st = translateFlags(infoflags);
            if(st != 0 && st != state) {
                updateState(st);
            }
            return state;
        }

        int translateFlags(int infoflags){
            if((infoflags & ERROR) != 0) {
                return ERRORED;
            } else if((infoflags & ABORT) != 0) {
                return ABORTED;
            } else if((infoflags & (ALLBITS | FRAMEBITS)) != 0) {
                return COMPLETE;
            } else {
                return 0;
            }
        }

        boolean equals(Image image, int id, int width, int height){
            return (image == img && this.id == id && w == width && h == height);
        }

        public boolean imageUpdate(Image image, int infoflags, int x, int y, int w, int h) {
            int st = translateFlags(infoflags);
            if(st != 0 && st != state) {
                updateState(st);
            }
            return ((state & LOADING) != 0);
        }

    }

}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Bash Script to Monitor Messages Log (Warning, Error and Critical) on Linux)
[#]: via: (https://www.2daygeek.com/linux-bash-script-to-monitor-messages-log-warning-error-critical-send-email/)
[#]: author: (Magesh Maruthamuthu https://www.2daygeek.com/author/magesh/)

Bash Script to Monitor Messages Log (Warning, Error and Critical) on Linux
======

There are many open source monitoring tools are currently available in market to monitor Linux systems performance.

It will send an email alert when the system reaches the specified threshold limit.

It monitors everything such as CPU utilization, Memory utilization, swap utilization, disk space utilization and much more.

If you only have few systems and want to monitor them then writing a small shell script can make your task very easy.

In this tutorial we have added a shell script to monitor Messages Log on Linux system.

We had added many useful shell scripts in the past. If you want to check those, navigate to the below link.

  * **[How to automate day to day activities using shell scripts?][1]**

This script will check **"warning, error and critical"** in the `/var/log/messages` file and trigger a mail to given email id, if it's found anything related it.

We can't run this script frequently that may fill up your inbox if the server has many matching strings, instead we can run once in a day.

To overcome this issue, i made the script to trigger an email in a different manner.

If any given strings are found in the **"/var/log/messages"** file for yesterday's date then the script will send an email alert to given email id.

**Note:** You need to change the email id instead of ours. Also, you can change the Memory utilization threshold value as per your requirement.

```
# vi /opt/scripts/os-log-alert.sh

#!/bin/bash

#Set the variable which equal to zero

prev_count=0

count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | egrep -wi 'warning|error|critical' | wc -l)

if [ "$prev_count" -lt "$count" ] ; then

# Send a mail to given email id when errors found in log

SUBJECT="WARNING: Errors found in log on "`date --date='yesterday' '+%b %e'`""

# This is a temp file, which is created to store the email message.

MESSAGE="/tmp/logs.txt"

TO="[email protected]"

echo "ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin." >> $MESSAGE

echo  "Hostname: `hostname`" >> $MESSAGE

echo -e "\n" >> $MESSAGE

echo "+------------------------------------------------------------------------------------+" >> $MESSAGE

echo "Error messages in the log file as below" >> $MESSAGE

echo "+------------------------------------------------------------------------------------+" >> $MESSAGE

grep -i "`date --date='yesterday' '+%b %e'`" /var/log/messages | awk '{ $3=""; print}' | egrep -wi 'warning|error|critical' >>  $MESSAGE

mail -s "$SUBJECT" "$TO" < $MESSAGE

#rm $MESSAGE

fi
```

Set an executable permission to `os-log-alert.sh` file.

```
$ chmod +x /opt/scripts/os-log-alert.sh
```

Finally add a cronjob to automate this. It will run everyday at 7'o clock.

```
# crontab -e
0 7 * * * /bin/bash /opt/scripts/os-log-alert.sh
```

**Note:** You will be getting an email alert everyday at 7 o'clock, which is for yesterday's log.

**Output:** You will be getting an email alert similar to below.

```
ATTENTION: Errors are found in /var/log/messages. Please Check with Linux admin.

+-----------------------------------------------------+
Error messages in the log file as below
+-----------------------------------------------------+
Jul  3 02:40:11 ns1 kernel: php-fpm[3175]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000]
Jul  3 02:50:14 ns1 kernel: lmtp[8249]: segfault at 20 ip 00007f9cc05295e4 sp 00007ffc57bca1a0 error 4 in libdovecot-storage.so.0.0.0[7f9cc04df000+148000]
Jul  3 15:36:09 ns1 kernel: php-fpm[17846]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000]
Jul  3 15:45:54 ns1 pure-ftpd: ([email protected]) [WARNING] Authentication failed for user [daygeek]
Jul  3 16:25:36 ns1 pure-ftpd: ([email protected]) [WARNING] Sorry, cleartext sessions and weak ciphers are not accepted on this server.#012Please reconnect using TLS security mechanisms.
Jul  3 16:44:20 ns1 kernel: php-fpm[8979]: segfault at 299 ip 000055dfe7cc7e25 sp 00007ffd799d7d38 error 4 in php-fpm[55dfe7a89000+3a7000]
```

--------------------------------------------------------------------------------

via: https://www.2daygeek.com/linux-bash-script-to-monitor-messages-log-warning-error-critical-send-email/

作者:[Magesh Maruthamuthu][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://www.2daygeek.com/author/magesh/
[b]: https://github.com/lujun9972
[1]: https://www.2daygeek.com/category/shell-script/


text:
[Title](Title.md)

[Foreward](Foreward.md)

[Introduction](Introduction.md)

[Terminology](Terminology.md)

- [Settting Up a Gopherbot Robot](Installation.md)
    - [Gopherbot Requirements](install/Requirements.md)
    - [Manual Installation](install/ManualInstall.md)
    - [Initial Robot Configuration](RobotInstall.md)
        - [Requirements](botsetup/Requirements.md)
        - [Robot Directory Structure](botsetup/gopherhome.md)
        - [Quick Start with Autosetup](botsetup/Plugin.md)
        - [Setting up a Robot with Gitpod](botsetup/Gitpod.md)
        - [Setup with Containers](botsetup/ContainerSetup.md)
        - [Manual Setup](botsetup/ManualSetup.md)
            - [Create the `GOPHER_HOME` directory](botsetup/bothome.md)
            - [Create the Initial `.env` File](botsetup/initenv.md)
            - [Initialize Encryption](botsetup/initcrypt.md)
            - [Copy the Standard Robot](botsetup/copystd.md)
            - [Generate SSH Keypairs](botsetup/sshkeys.md)
            - [Finish the `.env` File](botsetup/finalenv.md)
            - [Connect Robot to Team](botsetup/connect.md)
            - [Saving Your Robot to Git](botsetup/saverobot.md)
            - [Finished](botsetup/finished.md)

- [Upgrading from Version 1](Upgrading.md)
    - [Required Bot Info](upgrade/BotInfo.md)
    - [External Plugin Configuration](upgrade/External-Plugin.md)
    - [Custom Configuration Directory](upgrade/Custom-Dir.md)
    - [Main Configuration File Rename](upgrade/robot-yaml.md)
    - [Early Encryption Initialization](upgrade/Encryption.md)
    - [Long-Term Memories](upgrade/Memories.md)

- [Deploying and Running Your Robot](RunRobot.md)
    - [Running with Systemd](deploy/systemd.md)
    - [Running in a Container](deploy/Container.md)
    - [Deploying to Kubernetes](deploy/Kubernetes.md)

- [Robot Basics](Basics.md)
    - [Addressing your Robot](basics/ping.md)
    - [Command Matching](basics/matching.md)
    - [Availability by Channel](basics/channels.md)
    - [The built-in Help System](basics/help.md)
    - [Standard Commands](basics/stdplugins.md)
    - [Context](basics/context.md)

- [Robot Administration](Admin.md)
    # TODO: move the stuff below from deploy to admin or elsewhere...
    - [CLI Operation](deploy/CLI.md)
        - [Local Install](deploy/local.md)
        - [Container Operation](deploy/containercli.md)
        - [Using Gitpod](deploy/gitpodcli.md)
        - [Encrypting Secrets](deploy/secrets.md)
    - [Updating from Git](usage/update.md)
    - [Using the Terminal Connector](usage/terminal.md)
    - [Administrator Commands](usage/admin.md)
    - [Command-Line Use](usage/cli.md)
    - [Logging](usage/logging.md)

- [Developing Extensions for Your Robot](botprogramming.md)

- [Gopherbot Configuration Reference](Configuration.md)
    - [Environment Variables](Environment-Variables.md)
    - [Configuration File Loading](config/file.md)
    - [Job and Plugin Configuration](config/job-plug.md)
    - [Troubleshooting](config/troubleshooting.md)

- [Pipelines, Plugins, Jobs and Tasks](pipelines/jobspipes.md)
    - [The Primary Pipeline](pipelines/primary.md)
    - [The Final Pipeline](pipelines/final.md)
    - [The Fail Pipeline](pipelines/fail.md)
    - [Task Environment Variables](pipelines/TaskEnvironment.md)
    - [All Included Tasks](pipelines/tasks.md)

- [Gopherbot Tool Integrations](pipelines/integrations.md)
    - [Integrating with SSH](pipelines/ssh.md)

- [Gopherbot API](api/API-Introduction.md)
    - [Language Templates](api/Languages.md)
    - [Attribute Retrieval](api/Attribute-Retrieval-API.md)
    - [Brain Methods](api/Brain-API.md)
    - [Message Sending](api/Message-Sending-API.md)
    - [Pipeline Construction](api/Pipeline-API.md)
    - [Requesting Responses](api/Response-Request-API.md)
    - [Utility](api/Utility-API.md)

- [Module Support](Modules.md)

## Appendix
- [Appendix](appendices/Appendix.md)
    - [A - Protocols](appendices/Protocols.md)
        - [A.1 - Slack](appendices/slack.md)
        - [A.2 - Rocket.Chat](appendices/rocket.md)
        - [A.3 - Terminal](appendices/terminal.md)
        - [A.4 - Test](appendices/testproto.md)
        - [A.5 - Nullconn](appendices/nullconn.md)

## Gopherbot Development
- [Working on Gopherbot](GopherDev.md)
    - [Development Robot](botdev/DevelRobot.md) <!--TODO: write me! -->
    - [Integration Tests](botdev/IntegrationTests.md)
    - [Coding with Gitpod](botdev/Gitpod.md) <!--TODO: write me! -->
    - [Important Structs and Interfaces](botdev/StructsInterfaces.md)
    - [Protocols](botdev/protocols.md)


text:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import UserCreationForm, UserChangeForm
from .models import User

class UserAdmin(UserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm
    model = User
    list_display = ['email', 'username', 'is_superuser', 'is_staff', 'is_active',]

admin.site.register(User, UserAdmin)


text:
<component name="libraryTable">
  <library name="exposed-instrumentation-api-publish-0.5">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/03a3dfd3b4a8b15fb332ff03a8735dec45fa8c10/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/03a3dfd3b4a8b15fb332ff03a8735dec45fa8c10/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://D:/2016-5-14-1-19AndroidSDK/extras/android/m2repository/com/android/support/test/exposed-instrumentation-api-publish/0.5/exposed-instrumentation-api-publish-0.5-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
#ifndef __LAGER_H
#define __LAGER_H

#undef DEBUG
#define CONFIG_ARMV7
#define CONFIG_R8A7790
#define CONFIG_RMOBILE
#define CONFIG_RMOBILE_BOARD_STRING "Lager"
#define CONFIG_SH_GPIO_PFC
#define MACH_TYPE_LAGER		4538
#define CONFIG_MACH_TYPE	MACH_TYPE_LAGER

#include <asm/arch/rmobile.h>

#define	CONFIG_CMD_EDITENV
#define	CONFIG_CMD_SAVEENV
#define CONFIG_CMD_MEMORY
#define CONFIG_CMD_DFL
#define CONFIG_CMD_SDRAM
#define CONFIG_CMD_RUN
#define CONFIG_CMD_LOADS
#define CONFIG_CMD_NET
#define CONFIG_CMD_MII
#define CONFIG_CMD_PING
#define CONFIG_CMD_DHCP
#define CONFIG_CMD_NFS
#define CONFIG_CMD_BOOTZ

#if defined(CONFIG_SYS_USE_BOOT_NORFLASH)
#define CONFIG_CMD_FLASH
#define CONFIG_SYS_TEXT_BASE	0x00000000
#else
#define CONFIG_CMD_SF
#define CONFIG_CMD_SPI
#define CONFIG_SYS_TEXT_BASE	0xE8080000
#endif

#define	CONFIG_CMDLINE_TAG
#define	CONFIG_SETUP_MEMORY_TAGS
#define	CONFIG_INITRD_TAG
#define	CONFIG_CMDLINE_EDITING
#define	CONFIG_OF_LIBFDT

/* #define CONFIG_OF_LIBFDT */
#define BOARD_LATE_INIT

#define CONFIG_BAUDRATE		38400
#define CONFIG_BOOTDELAY	3
#define CONFIG_BOOTARGS		""

#define CONFIG_VERSION_VARIABLE
#undef	CONFIG_SHOW_BOOT_PROGRESS

#define CONFIG_ARCH_CPU_INIT
#define CONFIG_DISPLAY_CPUINFO
#define CONFIG_DISPLAY_BOARDINFO
#define CONFIG_BOARD_EARLY_INIT_F
#define CONFIG_USE_ARCH_MEMSET
#define CONFIG_USE_ARCH_MEMCPY
#define CONFIG_TMU_TIMER

/* STACK */
#define CONFIG_SYS_INIT_SP_ADDR		0xE827fffc
#define STACK_AREA_SIZE				0xC000
#define LOW_LEVEL_MERAM_STACK	\
		(CONFIG_SYS_INIT_SP_ADDR + STACK_AREA_SIZE - 4)

/* MEMORY */
#define LAGER_SDRAM_BASE	0x40000000
#define LAGER_SDRAM_SIZE	(2048u * 1024 * 1024)
#define LAGER_UBOOT_SDRAM_SIZE	(512 * 1024 * 1024)

#define CONFIG_SYS_LONGHELP
#define CONFIG_SYS_CBSIZE		256
#define CONFIG_SYS_PBSIZE		256
#define CONFIG_SYS_MAXARGS		16
#define CONFIG_SYS_BARGSIZE		512
#define CONFIG_SYS_BAUDRATE_TABLE	{ 38400, 115200 }

/* SCIF */
#define CONFIG_SCIF_CONSOLE
#define CONFIG_CONS_SCIF0
#define SCIF0_BASE		0xe6e60000
#undef	CONFIG_SYS_CONSOLE_INFO_QUIET
#undef	CONFIG_SYS_CONSOLE_OVERWRITE_ROUTINE
#undef	CONFIG_SYS_CONSOLE_ENV_OVERWRITE

#define CONFIG_SYS_MEMTEST_START	(LAGER_SDRAM_BASE)
#define CONFIG_SYS_MEMTEST_END		(CONFIG_SYS_MEMTEST_START + \
					 504 * 1024 * 1024)
#undef	CONFIG_SYS_ALT_MEMTEST
#undef	CONFIG_SYS_MEMTEST_SCRATCH
#undef	CONFIG_SYS_LOADS_BAUD_CHANGE

#define CONFIG_SYS_SDRAM_BASE		(LAGER_SDRAM_BASE)
#define CONFIG_SYS_SDRAM_SIZE		(LAGER_UBOOT_SDRAM_SIZE)
#define CONFIG_SYS_LOAD_ADDR		(CONFIG_SYS_SDRAM_BASE + 0x7fc0)
#define CONFIG_NR_DRAM_BANKS		1

#define CONFIG_SYS_MONITOR_BASE		0x00000000
#define CONFIG_SYS_MONITOR_LEN		(256 * 1024)
#define CONFIG_SYS_MALLOC_LEN		(1 * 1024 * 1024)
#define CONFIG_SYS_BOOTMAPSZ		(8 * 1024 * 1024)

#if defined(CONFIG_SYS_USE_BOOT_NORFLASH)
/* USE NOR FLASH */
#define CONFIG_SYS_FLASH_CFI
#define CONFIG_SYS_FLASH_CFI_WIDTH	FLASH_CFI_16BIT
#define	CONFIG_FLASH_CFI_DRIVER
#define	CONFIG_CFI_FLASH_USE_WEAK_ACCESSORS
#define	CONFIG_FLASH_SHOW_PROGRESS	45
#define CONFIG_SYS_FLASH_BASE		0x00000000
#define	CONFIG_SYS_FLASH_SIZE		0x04000000	/* 64 MB */
#define CONFIG_SYS_MAX_FLASH_SECT	1024
#define CONFIG_SYS_MAX_FLASH_BANKS	1
#define CONFIG_SYS_FLASH_BANKS_LIST	{ (CONFIG_SYS_FLASH_BASE) }
#define	CONFIG_SYS_FLASH_BANKS_SIZES	{ (CONFIG_SYS_FLASH_SIZE) }
#define CONFIG_SYS_FLASH_ERASE_TOUT	3000
#define CONFIG_SYS_FLASH_WRITE_TOUT	3000
#define CONFIG_SYS_FLASH_LOCK_TOUT	3000
#define CONFIG_SYS_FLASH_UNLOCK_TOUT	3000

/* ENV setting */
#define CONFIG_ENV_IS_IN_FLASH
#define CONFIG_ENV_ADDR		(CONFIG_SYS_FLASH_BASE + \
				 CONFIG_SYS_MONITOR_LEN)

#else /* CONFIG_SYS_USE_BOOT_NORFLASH */

/* USE SPI */
#define CONFIG_SPI
#define CONFIG_SPI_FLASH_BAR
#define CONFIG_SH_QSPI
#define CONFIG_SPI_FLASH
#define CONFIG_SPI_FLASH_SPANSION
#define CONFIG_SYS_NO_FLASH

/* ENV setting */
#define CONFIG_ENV_IS_IN_SPI_FLASH
#define CONFIG_ENV_ADDR	0xC0000
#endif

/* Common ENV setting */
#define CONFIG_ENV_OVERWRITE
#define CONFIG_ENV_SECT_SIZE	(256 * 1024)
#define CONFIG_ENV_OFFSET	(CONFIG_ENV_ADDR)
#define CONFIG_ENV_SIZE		(CONFIG_ENV_SECT_SIZE)
#define CONFIG_ENV_SIZE_REDUND	(CONFIG_SYS_MONITOR_LEN)

/* SH Ether */
#define	CONFIG_NET_MULTI
#define CONFIG_SH_ETHER
#define CONFIG_SH_ETHER_USE_PORT	0
#define CONFIG_SH_ETHER_PHY_ADDR	0x1
#define CONFIG_SH_ETHER_PHY_MODE PHY_INTERFACE_MODE_RMII
#define CONFIG_SH_ETHER_ALIGNE_SIZE	64
#define CONFIG_SH_ETHER_CACHE_WRITEBACK
#define CONFIG_SH_ETHER_CACHE_INVALIDATE
#define CONFIG_PHYLIB
#define CONFIG_PHY_MICREL
#define CONFIG_BITBANGMII
#define CONFIG_BITBANGMII_MULTI

/* I2C */
#define CONFIG_SYS_I2C
#define CONFIG_SYS_I2C_RCAR
#define CONFIG_SYS_RCAR_I2C0_BASE	0xE6508000
#define CONFIG_SYS_RCAR_I2C0_SPEED	400000
#define CONFIG_SYS_RCAR_I2C1_BASE	0xE6518000
#define CONFIG_SYS_RCAR_I2C1_SPEED	400000
#define CONFIG_SYS_RCAR_I2C2_BASE	0xE6530000
#define CONFIG_SYS_RCAR_I2C2_SPEED	400000
#define CONFIG_SYS_RCAR_I2C3_BASE	0xE6540000
#define CONFIG_SYS_RCAR_I2C3_SPEED	400000
#define CONFIF_SYS_RCAR_I2C_NUM_CONTROLLERS	4

#define CONFIG_SYS_I2C_POWERIC_ADDR 0x58 /* da9063 */

/* Board Clock */
#define CONFIG_BASE_CLK_FREQ	20000000u
#define CONFIG_SH_TMU_CLK_FREQ	(CONFIG_BASE_CLK_FREQ / 2) /* EXT / 2 */
#define CONFIG_PLL1_CLK_FREQ	(CONFIG_BASE_CLK_FREQ * 156 / 2)
#define CONFIG_PLL1_DIV2_CLK_FREQ	(CONFIG_PLL1_CLK_FREQ / 2)
#define CONFIG_MP_CLK_FREQ	(CONFIG_PLL1_DIV2_CLK_FREQ / 15)
#define CONFIG_HP_CLK_FREQ	(CONFIG_PLL1_CLK_FREQ / 12)
#define CONFIG_SH_SCIF_CLK_FREQ	CONFIG_MP_CLK_FREQ

#define CONFIG_SYS_TMU_CLK_DIV	4

#endif	/* __LAGER_H */


text:
package loa.upload;

public class TimeoutException extends RuntimeException {

	public TimeoutException(String msg) {
		super(msg);
	}

	private static final long serialVersionUID = 1L;

}


text:
from __future__ import unicode_literals, division
import unittest
import six

from nibble import decorators

class TestOperatorSameClass(unittest.TestCase):

    # noinspection PyUnusedLocal
    @decorators.operator_same_class
    def wrapped(self, other):
        return True

    def test_same_class(self):
        self.assertTrue(self.wrapped(self))

    def test_different_class(self):
        with self.assertRaises(TypeError):
            self.wrapped('')

class TestOperatorNumericType(unittest.TestCase):

    # noinspection PyUnusedLocal
    @decorators.operator_numeric_type
    def wrapped(self, other):
        return True

    def test_int(self):
        self.assertTrue(self.wrapped(1))

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_long(self):
        # noinspection PyUnresolvedReferences
        self.assertTrue(self.wrapped(long(1)))

    def test_float(self):
        self.assertTrue(self.wrapped(1.0))

    def test_string(self):
        with self.assertRaises(TypeError):
            self.wrapped('')

class TestPython2FormatCompatible(unittest.TestCase):

    # noinspection PyUnusedLocal
    @decorators.python_2_format_compatible
    def __format__(self, format_spec):
        return ''

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_str(self):
        bytestring = 'abc'.encode('utf-8')
        self.assertIsInstance(format(self, bytestring), type(bytestring))

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_unicode(self):
        unicode_ = 'abc'
        self.assertIsInstance(format(self, unicode_), type(unicode_))

    @unittest.skipUnless(six.PY3, 'Only applies to Python 3')
    def test_py3_str(self):
        self.assertIsInstance(format(self, 'abc'), str)

class TestPython2NonzeroCompatible(unittest.TestCase):

    @decorators.python_2_nonzero_compatible
    class Inner(object):

        def __init__(self, val):
            self.val = val

        def __bool__(self):
            return self.val

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_true(self):
        self.assertTrue(self.Inner(True))

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_false(self):
        self.assertFalse(self.Inner(False))

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_no_bool_method(self):
        with self.assertRaises(ValueError):
            # noinspection PyUnusedLocal
            @decorators.python_2_nonzero_compatible
            class NoBool(object):
                pass

    @unittest.skipUnless(six.PY3, 'Only applies to Python 3')
    def test_py3(self):
        self.assertFalse(hasattr(self.Inner(True), '__nonzero__'))

class TestPython2DivCompatible(unittest.TestCase):

    @decorators.python_2_div_compatible
    class Inner(object):

        def __init__(self, val):
            self.val = val

        def __floordiv__(self, other):
            return self.val // other

        def __truediv__(self, other):
            return self.val / other

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_div(self):
        self.assertEqual(self.Inner(5).__div__(3), 1)

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_floordiv(self):
        self.assertEqual(self.Inner(5) // 3, 1)

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_py2_truediv(self):
        self.assertAlmostEqual(self.Inner(5) / 3, 1.66666666)

    @unittest.skipUnless(six.PY2, 'Only applies to Python 2')
    def test_no_floordiv_method(self):
        with self.assertRaises(ValueError):
            # noinspection PyUnusedLocal
            @decorators.python_2_div_compatible
            class NoFloordiv(object):
                pass

    @unittest.skipUnless(six.PY3, 'Only applies to Python 3')
    def test_py3(self):
        self.assertFalse(hasattr(self.Inner(None), '__div__'))


text:
from __future__ import annotations

import pytest

from cctbx import sgtbx
from cctbx.sgtbx.lattice_symmetry import metric_subgroups

from dials.algorithms.symmetry.cosym._generate_test_data import generate_intensities
from dials.algorithms.symmetry.laue_group import (
    ScoreCorrelationCoefficient,
    ScoreSubGroup,
    ScoreSymmetryElement,
)

def test_score_correlation_coefficient():
    cc = 1
    expected_cc = 1
    sigma_cc = 0.1
    score_cc = ScoreCorrelationCoefficient(cc, sigma_cc, expected_cc)
    assert score_cc.p_s_given_cc == pytest.approx(0.9492499653267421)

    cc = 0.5
    score_cc = ScoreCorrelationCoefficient(cc, sigma_cc, expected_cc)
    assert score_cc.p_s_given_cc == pytest.approx(0.19697339347266518)

    cc = 0.5
    expected_cc = 0.6
    sigma_cc = 0.2
    score_cc = ScoreCorrelationCoefficient(cc, sigma_cc, expected_cc)
    assert score_cc.p_s_given_cc == pytest.approx(0.6178439917879021)

    if 0:
        import numpy as np
        from matplotlib import pyplot as plt

        x = np.linspace(-1, 1)
        values = [(0.1, 1), (0.1, 0.8), (0.2, 1), (0.2, 0.8)]
        fig, axes = plt.subplots(nrows=2, ncols=2)
        for ax, (sigma_cc, expected_cc) in zip(axes.flatten(), values):
            ax.set_title(f"E(CC) = {expected_cc:.1f}, sigma(cc) = {sigma_cc:.1f}")
            p_cc_given_s = []
            p_cc_given_not_s = []
            p_s_given_cc = []
            for _ in x:
                score_cc = ScoreCorrelationCoefficient(_, sigma_cc, expected_cc)
                p_cc_given_s.append(score_cc.p_cc_given_s)
                p_cc_given_not_s.append(score_cc.p_cc_given_not_s)
                p_s_given_cc.append(score_cc.p_s_given_cc)
            ax.plot(x, p_cc_given_s, label="p(CC;S)")
            ax.plot(x, p_cc_given_not_s, label="p(CC;!S)")
            ax.plot(x, p_s_given_cc, label="p(S;CC)")
        ylim = max(ax.get_ylim()[1] for ax in axes.flatten())
        for ax in axes.flatten():
            ax.legend()
            ax.set_ylim(ax.get_ylim()[0], ylim)
        plt.show()

@pytest.mark.parametrize("space_group", ["P2", "P3", "P6", "R3:h", "I23"][:])
def test_score_symmetry_element_subgroup(space_group):
    sgi = sgtbx.space_group_info(symbol=space_group)
    cs = sgi.any_compatible_crystal_symmetry(volume=10000)
    cs = cs.best_cell()
    cs = cs.minimum_cell()
    intensities = (
        generate_intensities(cs, d_min=1.0)
        .generate_bijvoet_mates()
        .set_observation_type_xray_intensity()
    )
    intensities = intensities.expand_to_p1()

    subgroups = metric_subgroups(
        intensities.crystal_symmetry(), max_delta=2.0, bravais_types_only=False
    )
    intensities = intensities.change_basis(subgroups.cb_op_inp_minimum)
    cs = cs.change_basis(subgroups.cb_op_inp_minimum)

    cb_op_inp_best = subgroups.result_groups[0]["cb_op_inp_best"]
    lattice_group = subgroups.result_groups[0]["best_subsym"].space_group()
    lattice_group = lattice_group.change_basis(cb_op_inp_best.inverse())

    lattice_group = subgroups.result_groups[0]["subsym"].space_group()

    sym_op_scores = []
    for sym_op in lattice_group.smx():
        if sym_op.r().info().sense() < 0:
            continue
        score = ScoreSymmetryElement(intensities, sym_op, 1.0, 1.0)
        sym_op_scores.append(score)
        if sym_op in cs.space_group():
            assert score.likelihood > 0.9
            assert score.cc.coefficient() > 0.9
        else:
            assert score.likelihood < 0.2
            assert score.cc.coefficient() < 0.3

    subgroup_scores = [
        ScoreSubGroup(subgrp, sym_op_scores) for subgrp in subgroups.result_groups
    ]
    total_likelihood = sum(score.likelihood for score in subgroup_scores)
    for score in subgroup_scores:
        score.likelihood /= total_likelihood
    true_patterson_group = (
        cs.space_group_info()
        .as_reference_setting()
        .group()
        .build_derived_patterson_group()
    )
    for score in subgroup_scores:
        if score.subgroup["best_subsym"].space_group() == true_patterson_group:
            assert score.likelihood > 0.8
        else:
            assert score.likelihood < 0.1


text:
using System;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;

namespace DiscUtils
{
    public delegate DiscFileSystem NewFileSystemDelegate();

    public class FileSystemSource
    {
        public FileSystemSource()
        {
        }

        public IEnumerable<TestCaseData> ReadWriteFileSystems
        {
            get
            {
                yield return new TestCaseData(
                    new NewFileSystemDelegate(FatFileSystem)).SetName("FAT");

                // TODO: When format code complete, format a vanilla partition rather than relying on file on disk
                yield return new TestCaseData(
                    new NewFileSystemDelegate(DiagnosticNtfsFileSystem)).SetName("NTFS");
            }
        }

        public IEnumerable<TestCaseData> QuickReadWriteFileSystems
        {
            get
            {
                yield return new TestCaseData(
                    new NewFileSystemDelegate(FatFileSystem)).SetName("FAT");

                yield return new TestCaseData(
                    new NewFileSystemDelegate(NtfsFileSystem)).SetName("NTFS");
            }
        }

        private static DiscFileSystem FatFileSystem()
        {
            SparseMemoryBuffer buffer = new SparseMemoryBuffer(4096);
            SparseMemoryStream ms = new SparseMemoryStream();
            Geometry diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024);
            return Fat.FatFileSystem.FormatFloppy(ms, FloppyDiskType.Extended, null);
        }

        public static DiscFileSystem DiagnosticNtfsFileSystem()
        {
            SparseMemoryBuffer buffer = new SparseMemoryBuffer(4096);
            SparseMemoryStream ms = new SparseMemoryStream();
            Geometry diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024);
            Ntfs.NtfsFileSystem.Format(ms, "", diskGeometry, 0, diskGeometry.TotalSectorsLong);
            var discFs = new DiscUtils.Diagnostics.ValidatingFileSystem<Ntfs.NtfsFileSystem, Ntfs.NtfsFileSystemChecker>(ms);
            discFs.CheckpointInterval = 1;
            discFs.GlobalIOTraceCapturesStackTraces = false;
            return discFs;
        }

        public Ntfs.NtfsFileSystem NtfsFileSystem()
        {
            SparseMemoryBuffer buffer = new SparseMemoryBuffer(4096);
            SparseMemoryStream ms = new SparseMemoryStream();
            Geometry diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024);
            return Ntfs.NtfsFileSystem.Format(ms, "", diskGeometry, 0, diskGeometry.TotalSectorsLong);
        }

    }
}