text:
Q: Error after the installation of python-pip I have Ubuntu (version 18.04.4), installed on Windows, if it is important.
Python version is 2.7.17.
I'm installing pip with
sudo apt install python-pip

and the output looks ok, but when I'm trying even to check the version of pip by
pip --version

I got the following errors:
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
  File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 22, in <module>
    from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarning
  File "/usr/lib/python2.7/dist-packages/pip/_vendor/__init__.py", line 64, in <module>
    vendored("cachecontrol")
  File "/usr/lib/python2.7/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
    __import__(modulename, globals(), locals(), level=0)
  File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/__init__.py", line 9, in <module>
  File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/wrapper.py", line 1, in <module>
  File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/adapter.py", line 4, in <module>
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/__init__.py", line 84, in <module>
  File "/usr/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 46, in <module>
  File "/usr/local/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py", line 12, in <module>
    from cryptography import x509
  File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/__init__.py", line 8, in <module>
    from cryptography.x509.base import (
  File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/base.py", line 18, in <module>
    from cryptography.x509.extensions import Extension, ExtensionType
  File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/extensions.py", line 26, in <module>
    from cryptography.x509.general_name import GeneralName, IPAddress, OtherName
  File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/general_name.py", line 16, in <module>
    from cryptography.x509.name import Name
  File "/usr/local/lib/python2.7/dist-packages/cryptography/x509/name.py", line 28, in <module>
    _ASN1_TYPE_TO_ENUM = dict((i.value, i) for i in _ASN1Type)
TypeError: 'type' object is not iterable

Please help me to solve the problem


text:
Q: Plugin settings not saving and 404 is generated on submit I am creating a WordPress using https://github.com/nadeem-khan/WordPress-Plugin-Template as a starter template.
This is my settings class file named 'class-xyz.php':
<?php
if (!defined('ABSPATH'))
    exit;

class Xyz_Settings {

    /**
     * The single instance of Xyz_Settings.
     * @var     object
     * @access  private
     * @since   1.0.0
     */
    private static $_instance = null;

    /**
     * The main plugin object.
     * @var     object
     * @access  public
     * @since   1.0.0
     */
    public $parent = null;

    /**
     * Prefix for plugin settings.
     * @var     string
     * @access  public
     * @since   1.0.0
     */
    public $base = '';

    /**
     * Available settings for plugin.
     * @var     array
     * @access  public
     * @since   1.0.0
     */
    public $settings = array();

    public function __construct($parent) {
        $this->parent = $parent;

        $this->base = 'xyzsms_';

        // Initialise settings
        add_action('admin_init', array($this, 'init_settings'));

        // Register plugin settings
        add_action('admin_init', array($this, 'register_settings'));

        // Add settings page to menu
        add_action('admin_menu', array($this, 'add_menu_item'));

        // Add settings link to plugins page
        add_filter('plugin_action_links_' . plugin_basename($this->parent->file), array($this, 'add_settings_link'));
    }

    /**
     * Initialise settings
     * @return void
     */
    public function init_settings() {
        $this->settings = $this->settings_fields();
    }

    /**
     * Add settings page to admin menu
     * @return void
     */
    public function add_menu_item() {
        $page = add_options_page(__('XYZ Settings', 'xyz-template'), __('XYZ Settings', 'xyz-template'), 'manage_options', 'xyz_template_settings', array($this, 'settings_page'));
        add_action('admin_print_styles-' . $page, array($this, 'settings_assets'));
    }

    /**
     * Load settings JS & CSS
     * @return void
     */
    public function settings_assets() {

        // We're including the farbtastic script & styles here because they're needed for the colour picker
        // If you're not including a colour picker field then you can leave these calls out as well as the farbtastic dependency for the wpt-admin-js script below
        wp_enqueue_style('farbtastic');
        wp_enqueue_script('farbtastic');

        // We're including the WP media scripts here because they're needed for the image upload field
        // If you're not including an image upload then you can leave this function call out
        wp_enqueue_media();

        wp_register_script($this->parent->_token . '-settings-js', $this->parent->assets_url . 'js/settings' . $this->parent->script_suffix . '.js', array('farbtastic', 'jquery'), '1.0.0');
        wp_enqueue_script($this->parent->_token . '-settings-js');
    }

    /**
     * Add settings link to plugin list table
     * @param  array $links Existing links
     * @return array        Modified links
     */
    public function add_settings_link($links) {
        $settings_link = '' . __('Settings', 'xyz-template') . '';
        array_push($links, $settings_link);
        return $links;
    }

    /**
     * Build settings fields
     * @return array Fields to be displayed on settings page
     */
    private function settings_fields() {
        $settings['social-bar-position'] = array(
            'title' => __('Bar Position', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'xyz_position',
                    'label' => __('Position', 'xyz-plugin-bar'),
                    'description' => __('Select the position', 'xyz-plugin-bar'),
                    'type' => 'radio',
                    'options' => array('left' => 'Left', 'right' => 'Right'),
                    'default' => 'left'
                ),
                array(
                    'id' => 'xyz_margin_top',
                    'label' => __('Bar Margin Top', 'xyz-plugin-bar'),
                    'description' => __('Define the margin top', 'xyz-plugin-bar'),
                    'type' => 'text',
                    'placeholder' => __('Enter margin.', 'xyz-plugin-bar'),
                    'default' => '200px'
                )
            )
        );
        $settings['social-networks-bar'] = array(
            'title' => __('Social Networks', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'xyz_networks',
                    'label' => __('Social', 'xyz-plugin-bar'),
                    'description' => __('Select social.', 'xyz-plugin-bar'),
                    'type' => 'checkbox_multi',
                    'options' => array(
                        'facebook' => 'Facebook'
                    )
                )
            )
        );

        $settings['links-bar'] = array(
            'title' => __('Links', 'xyz-plugin-bar'),
            'description' => __('Enter the Urls for all the selected social networks:', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'facebook_url',
                    'label' => __('Facebook URL', 'xyz-plugin-bar'),
                    'description' => __('Enter the URL for Facebook.', 'xyz-plugin-bar'),
                    'type' => 'text',
                    'placeholder' => __('Enter Facebook URL', 'xyz-plugin-bar'),
                    'default' => ''
                )
            )
        );

        $settings['custom-classes-bar'] = array(
            'title' => __('Custom Classes', 'xyz-plugin-bar'),
            'description' => __('Add custom classes in the main parent container of the bar (will affect shortcodes as well):', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'xyz_custom_class',
                    'label' => __('Add Custom Classes in the Bar Parent Container'),
                    'description' => __('Add your own custom CSS class (like customclass1 customclass2). Leave empty if default styling is desired.', 'xyz-plugin-bar'),
                    'type' => 'textarea',
                    'default' => '',
                    'placeholder' => __('Add custom classes like .custom_class1 .custom_class2 .custom_class3 to the main container of the social bar.', 'xyz-plugin-bar')
                )
            )
        );

        $settings['social-bar-custom-colors'] = array(
            'title' => __('Bar Icons Colors', 'xyz-plugin-bar'),
            'description' => __('Select the colors', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'bar_facebook_icon_custom_color',
                    'label' => __('Facebook Icon Color', 'xyz-plugin-bar'),
                    'description' => __('Default color: #FEFEFE ', 'xyz-plugin-bar'),
                    'type' => 'color',
                    'default' => '#FEFEFE'
                )
            )
        );

        $settings['add-custom-css-bar'] = array(
            'title' => __('Add CSS', 'xyz-plugin-bar'),
            'label' => __('Add CSS', 'xyz-plugin-bar'),
            'description' => __('Paste your CSS', 'xyz-plugin-bar'),
            'fields' => array(
                array(
                    'id' => 'xyz_add_custom_css',
                    'label' => __('Custom CSS', 'wordpress'),
                    'description' => __('Do not style', 'xyz-plugin-bar'),
                    'type' => 'textarea',
                    'default' => '',
                    'placeholder' => __('Do not style .', 'xyz-plugin-bar')
                )
            )
        );

        $settings = apply_filters('xyz_fields', $settings);

        return $settings;
    }

    /**
     * Register plugin settings
     * @return void
     */
    public function register_settings() {
        if (is_array($this->settings)) {
            foreach ($this->settings as $section => $data) {

                // Add section to page
                add_settings_section($section, $data['title'], array($this, 'settings_section'), 'xyz_template_settings');

                foreach ($data['fields'] as $field) {

                    // Validation callback for field
                    $validation = '';
                    if (isset($field['callback'])) {
                        $validation = $field['callback'];
                    }

                    // Register field
                    $option_name = $this->base . $field['id'];
                    register_setting('xyz_template_settings', $option_name, $validation);

                    // Add field to page
                    add_settings_field($field['id'], $field['label'], array($this, 'display_field'), 'xyz_template_settings', $section, array('field' => $field));
                }
            }
        }
    }

    public function settings_section($section) {
        $html = '
 ' . $this->settings[$section['id']]['description'] . '
' . "\n";
        echo $html;
    }

    /**
     * Generate HTML for displaying fields
     * @param  array $args Field data
     * @return void
     */
    public function display_field($args) {

        $field = $args['field'];

        $html = '';

        $option_name = $this->base . $field['id'];
        $option = get_option($option_name);

        $data = '';
        if (isset($field['default'])) {
            $data = $field['default'];
            if ($option) {
                $data = $option;
            }
        }

        switch ($field['type']) {

            case 'text':
            case 'password':
            case 'number':
                $html .= '<input id="' . esc_attr($field['id']) . '" type="' . $field['type'] . '" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '" value="' . $data . '"/>' . "\n";
                break;

            case 'text_secret':
                $html .= '<input id="' . esc_attr($field['id']) . '" type="text" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '" value=""/>' . "\n";
                break;

            case 'textarea':
                $html .= '<textarea id="' . esc_attr($field['id']) . '" rows="5" cols="50" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '">' . $data . '</textarea>
' . "\n";
                break;

            case 'checkbox':
                $checked = '';
                if ($option && 'on' == $option) {
                    $checked = 'checked="checked"';
                }
                $html .= '<input id="' . esc_attr($field['id']) . '" type="' . $field['type'] . '" name="' . esc_attr($option_name) . '" ' . $checked . '/>' . "\n";
                break;

            case 'checkbox_multi':
                foreach ($field['options'] as $k => $v) {
                    $checked = false;
                    if (in_array($k, $data)) {
                        $checked = true;
                    }
                    $html .= '<input type="checkbox" ' . checked($checked, true, false) . ' name="' . esc_attr($option_name) . '[]" value="' . esc_attr($k) . '" id="' . esc_attr($field['id'] . '_' . $k) . '" /> ' . $v . ' ';
                }
                break;

            case 'radio':
                foreach ($field['options'] as $k => $v) {
                    $checked = false;
                    if ($k == $data) {
                        $checked = true;
                    }
                    $html .= '<input type="radio" ' . checked($checked, true, false) . ' name="' . esc_attr($option_name) . '" value="' . esc_attr($k) . '" id="' . esc_attr($field['id'] . '_' . $k) . '" /> ' . $v . ' ';
                }
                break;

            case 'select':
                $html .= '<select name="' . esc_attr($option_name) . '" id="' . esc_attr($field['id']) . '">';
                foreach ($field['options'] as $k => $v) {
                    $selected = false;
                    if ($k == $data) {
                        $selected = true;
                    }
                    $html .= '<option ' . selected($selected, true, false) . ' value="' . esc_attr($k) . '">' . $v . '</option>';
                }
                $html .= '</select> ';
                break;

            case 'select_multi':
                $html .= '<select name="' . esc_attr($option_name) . '[]" id="' . esc_attr($field['id']) . '" multiple="multiple">';
                foreach ($field['options'] as $k => $v) {
                    $selected = false;
                    if (in_array($k, $data)) {
                        $selected = true;
                    }
                    $html .= '<option ' . selected($selected, true, false) . ' value="' . esc_attr($k) . '" />' . $v . ' ';
                }
                $html .= '</select> ';
                break;

            case 'image':
                $image_thumb = '';
                if ($data) {
                    $image_thumb = wp_get_attachment_thumb_url($data);
                }
                $html .= '
' . "\n";
                $html .= '<input id="' . $option_name . '_button" type="button" data-uploader_title="' . __('Upload an image', 'xyz-template') . '" data-uploader_button_text="' . __('Use image', 'xyz-template') . '" class="image_upload_button button" value="' . __('Upload new image', 'xyz-template') . '" />' . "\n";
                $html .= '<input id="' . $option_name . '_delete" type="button" class="image_delete_button button" value="' . __('Remove image', 'xyz-template') . '" />' . "\n";
                $html .= '<input id="' . $option_name . '" class="image_data_field" type="hidden" name="' . $option_name . '" value="' . $data . '"/>
' . "\n";
                break;

            case 'color':
                ?>

                    <input type="text" name="<?php esc_attr_e($option_name); ?>" class="color" value="<?php esc_attr_e($data); ?>" />

                <?php
                break;
        }

        switch ($field['type']) {

            case 'checkbox_multi':
            case 'radio':
            case 'select_multi':
                $html .= '
' . $field['description'] . '';
                break;

            default:
                $html .= '' . $field['description'] . '' . "\n";
                break;
        }

        echo $html;
    }

    /**
     * Validate individual settings field
     * @param  string $data Inputted value
     * @return string       Validated value
     */
    public function validate_field($data) {
        if ($data && strlen($data) > 0 && $data != '') {
            $data = urlencode(strtolower(str_replace(' ', '-', $data)));
        }
        return $data;
    }

    /**
     * Load settings page content
     * @return void
     */
    public function settings_page() {

        // Build page HTML
        $html = '
' . "\n";
        $html .= '
' . __('XYZ Settings', 'xyz-template') . '
' . "\n";
        $html .= '<form method="post" action="options.php" enctype="multipart/form-data">' . "\n";

        // Setup navigation
        $html .= '
' . "\n";
        $html .= '
' . __('All', 'xyz-template') . '
' . "\n";

        foreach ($this->settings as $section => $data) {
            $html .= '
| ' . $data['title'] . '
' . "\n";
        }

        $html .= '
' . "\n";

        $html .= '

' . "\n";

        // Get settings fields
        ob_start();
        settings_fields('xyz_template_settings');
        do_settings_sections('xyz_template_settings');
        $html .= ob_get_clean();

        $html .= '
' . "\n";
        $html .= '<input name="Submit" type="submit" class="button-primary" value="' . esc_attr(__('Save Settings', 'xyz-template')) . '" />' . "\n";
        $html .= '
' . "\n";
        $html .= '</form>' . "\n";
        $html .= '
' . "\n";

        echo $html;
    }

    /**
     * Main Xyz_Settings Instance
     *
     * Ensures only one instance of Xyz_Settings is loaded or can be loaded.
     *
     * @since 1.0.0
     * @static
     * @see Xyz()
     * @return Main Xyz_Settings instance
     */
    public static function instance($parent) {
        if (is_null(self::$_instance)) {
            self::$_instance = new self($parent);
        }
        return self::$_instance;
    }

// End instance()

    /**
     * Cloning is forbidden.
     *
     * @since 1.0.0
     */
    public function __clone() {
        _doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->parent->_version);
    }

// End __clone()

    /**
     * Unserializing instances of this class is forbidden.
     *
     * @since 1.0.0
     */
    public function __wakeup() {
        _doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->parent->_version);
    }

// End __wakeup()
}

All the settings fields are displayed properly but as soon as the submit button is pressed 404 is generated and no settings get saved. What am I missing here?

A: The problem was with the huge number of settings I was trying to save and the max_input_vars limit was getting saturated.
I have now solved the issue by using jQuery to hide all the unused settings based on user input before submitting the settings form.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Javascript codes only work on a single Tabcontrol tab I made a tabbed browser using Cefsharp and Tabcontrol, but the java processes only work on the first tab.
This is how I activated Cefsharp.
 private void Form1_Load(object sender, EventArgs e)
    {

        CefSettings settings = new CefSettings();
        Cef.Initialize(settings);
        ChromiumWebBrowser chrome = new ChromiumWebBrowser(txtURL1.Text);
        chrome.Parent = tabControl.SelectedTab;
        chrome.Dock = DockStyle.Fill;
        chrome.AddressChanged += Chrome_AddressChanged;
        chrome.TitleChanged += Chrome_TitleChanged;
        chrome.LoadingStateChanged += Chrome_LoadingStateChanged;
        FormSizer();
        LoadGrid();
    }

This is how I opened the new tab via tabcontrol
 private void btnNewTab_Click(object sender, EventArgs e)
    {
        TabPage tab = new TabPage();
        tab.Text = txtName2.Text + "- NewTab";
        tabControl.Controls.Add(tab);
        tabControl.SelectTab(tabControl.TabCount - 1);
        ChromiumWebBrowser chrome = new ChromiumWebBrowser(txtURL2.Text);
        chrome.Parent = tab;
        chrome.Dock = DockStyle.Fill;
        chrome.TitleChanged += Chrome_TitleChanged;
    }

This is how I ran the java codes after the page was loaded.(TLoader)
 private void Chrome_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
    {
        this.Invoke(new MethodInvoker(() =>
        {
            bool CheckLoad = e.IsLoading;
            if (CheckLoad == false)
                if (OpenSetValue <= 2)
                {
                    TLoader();
                    OpenSetValue++;
                }

        }));
    }

Java content is exactly like this
 private void TLoader()
    {
        ChromiumWebBrowser chrome = tabControl.SelectedTab.Controls[0] as ChromiumWebBrowser;

        if (chrome != null)
        {
        string ClickName = "document.querySelector('input[type=text]').value ='" + SelectName + "'";
        string ClickPass = "document.querySelector('input[type=password]').value ='" + SelectPass + "'";
        string ClickButton = "document.querySelector('button[type=submit]').click();";
        //    MessageBox.Show(ClickPass);
        Thread.Sleep(348);
        chrome.ExecuteScriptAsync(ClickName); //id
        chrome.ExecuteScriptAsync(ClickPass); //pass
        Thread.Sleep(541);
        chrome.ExecuteScriptAsync(ClickButton); //click

        }
    }

Opening a new tab via tabcontrol and loading the cefsharp browser works fine, but "TLoader" does not work except in the first tab. It doesn't work on other tabs.
What do I need to do so that I can run TLoader on the selected or visible tab?
Thanks.


text:
Q: GKE metric server How to re-apply GKE metric server that comes installed by default? Also will it return TOP command stats?
I tried to install and then deleted the GITHUB version of metric server and now it might have deleted some roles related to default GKE metric server. I even tried reinstalling the GitHub version but I still get error..
kubectl top pods --all-namespaces
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)
kubectl top pods --all-namespaces
Error from server (InternalError): an error on the server ("Internal Server Error: \"/apis/metrics.k8s.io/v1beta1/pods\": Unauthorized") has prevented the request from succeeding (get pods.metrics.k8s.io)

GKE has the following pods running..
metrics-server-v0.3.6-7c5cb99b6f-npgzv
gke-metrics-agent-wkg5b

A: How to re-apply GKE metric server that comes installed by default?
First get name of metric server pod:
kubectl get pods --all-namespaces

Delete pod:
kubectl delete pod metrics-server-v0.3.6-547dc87f5f-sctcp -n kube-system

Since metric server is managed by Google, a new one will be reinstalled with a different pod name after deletion.
Also will it return TOP command stats?
It should, for example,
kubectl top pod metrics-server-v0.3.6-547dc87f5f-sctcp --containers -n kube-system


text:
Q: Set view controller as the first controller in UITabBarController I have this code in my appDelegate.m that implements a UINavigationController with a UITabBarController:
FristViewController *primeiro = [[FristViewController alloc] init];
    UINavigationController *nav1 = [[UINavigationController alloc] init];
    [nav1 pushViewController:primeiro animated:YES];

    FilesViewController *segundo = [[FilesViewController alloc] init];
    UINavigationController *nav2 = [[UINavigationController alloc] init];
    [nav2 pushViewController:segundo animated:YES];

    InfoViewController *terceiro = [[InfoViewController alloc] init];
    UINavigationController *nav3 = [[UINavigationController alloc] init];
    [nav3 pushViewController:terceiro animated:YES];

    UITabBarController *tabbar = [[UITabBarController alloc] init];
    tabbar.viewControllers = [NSArray arrayWithObjects:nav2, nav1, nav3, nil];
    nav1.tabBarItem.image = [UIImage imageNamed:@"tab1.png"];
    nav2.tabBarItem.image = [UIImage imageNamed:@"tab2.png"];
    nav3.tabBarItem.image = [UIImage imageNamed:@"tab3.png"];

    self.window.rootViewController = tab bar;

It's all right with this code, in my case when I beginning my app appearing on the first controller is FilesViewController because it is the first in the order of Tab Bar, but in my case I would like the first controller was the FristViewController without changing the order of items in the tab bar, how can I do this?

A: Go to your storyboard or xib where you created your TabBar. Drag the First controller to 1st position. Or programmatically you could set tabBar.selectedIndex = 0;


text:
Q: How can I change the section numbering for a single chapter with titlesec? I want my introduction to appear in the table of contents without the chapter number, but because I've used the \chapter* command to achieve this all the sections in the introduction are numbered as:

0.1  Title of Section

And I don't want the zero there (i.e. I want the first section of the introduction to be numbered 1). But for all the other chapters I do want the chapter number to be included in the section number (e.g. I want the 2nd section of chapter 1 to be numbered 1.2). Is there a way to get the section numbering of a single chapter to ignore the chapter number? Thanks!
Here's a MWE:
\documentclass[12pt, twoside]{report}

\usepackage[explicit]{titlesec} %adjust titles
\usepackage{lipsum}

\titleformat{\chapter}[display]{\LARGE\bfseries\centering}{\thechapter}{10pt}{#1}
\titleformat{\section}{\normalfont\fontsize{20}{20}\centering}{\thesection}{1em}{\MakeUppercase{#1}}
\titleformat{\subsection}{\normalfont\centering}{\thesubsection}{1em}{\textit{{#1}}}

\setcounter{tocdepth}{1} %removes subsubsections from toc

%%%%%%%%%removes dots from toc
\makeatletter
\renewcommand{\@dotsep}{10000}
\makeatother
%%%%%%%%%

\begin{document}

\tableofcontents

\chapter*{Introduction}
\addcontentsline{toc}{chapter}{Introduction}

\section{Here's a Section}

I want this section just to be numbered `1' rather than `0.1'. I would also like it to be numbered `1' instead of `0.1' in the table of contents.

\section{And Here's Another One}

This one should be numbered `2' rather than `0.2'.

\chapter{The First Chapter}

\section{Here's Another Section}

This section is numbered correctly.

\section{And Here's Another One}

And so is this one.

\end{document}

A: Change the section numbering style at appropriate places.
% secnumprob.tex  SE 561571
\documentclass[12pt, twoside]{report}

\usepackage[explicit]{titlesec} %adjust titles
\usepackage{lipsum}

\titleformat{\chapter}[display]{\LARGE\bfseries\centering}{\thechapter}{10pt}{#1}
\titleformat{\section}{\normalfont\fontsize{20}{20}\centering}{\thesection}{1em}{\MakeUppercase{#1}}
\titleformat{\subsection}{\normalfont\centering}{\thesubsection}{1em}{\textit{{#1}}}

\setcounter{tocdepth}{1} %removes subsubsections from toc

%%%%%%%%%removes dots from toc
\makeatletter
\renewcommand{\@dotsep}{10000}
\makeatother
%%%%%%%%%

\begin{document}

\tableofcontents

\chapter*{Introduction}
\addcontentsline{toc}{chapter}{Introduction}
\renewcommand{\thesection}{\arabic{section}}  % PW ADDED

\section{Here's a Section}

I want this section just to be numbered `1' rather than `0.1'. I would also like it to be numbered `1' instead of `0.1' in the table of contents.

\section{And Here's Another One}

This one should be numbered `2' rather than `0.2'.

\chapter{The First Chapter}
\renewcommand{\thesection}{\thechapter.\arabic{section}} % PW ADDED

\section{Here's Another Section}

This section is numbered correctly.

\section{And Here's Another One}

And so is this one.

\end{document}


text:
Q: GNU/Linux thread implementation Recently, I've read in the "Advanced Linux Programming" book (http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf, Chapter 4.5) that on GNU/Linux POSIX threads are implemented as processes and that there is some kind of "manager thread" which does some control work.
When I run the following example from this book:
#include <stdio.h>
#include <pthread.h>

void* thread_func(void *arg)
{
  fprintf(stderr, "thread: %d\n", (int)getpid());
  while(1);
  return NULL;
}

int main()
{
  fprintf(stderr, "main: %d\n", (int)getpid());

  pthread_t thread;
  pthread_create(&thread, NULL, thread_func, NULL);

  while(1);
  return 0;
}

I've received the same PID for the main thread and child thread, while the book says that it can be different & that there is another PID, which corresponds to the so-called "manager thread." I've tried to find some information about this "manager thread", but it's proving difficult.
UPD. I have no doubts about behaivour of my program, but there is some confusion about behaivour, explained on the book - in particular, under which circumstances it can be true?

A:
i've received the same PID both for main thread and child thread

That is normal and expected behavior. These threads you created co-exist in the same process, so getpid() returns ID for that process. If you want to distinguish threads, use pthread_self() (POSIX-compatible, but not system-wide unique) or gettid() (Linux specific).
Internally, all processes and threads in Linux are managed by universal object called task (and defined by task_struct), and each task has it's own ID. However, first task is a handle process thus called task group leader. And getpid() returns PID of that task group leader.
So in your case, thread_func() thread prints PID of its leader, main() task, and main() thread print PID of itself.
I suggest you to dive into kernel internals. It provides cleaner view of such things - try for example Robert Love book "Linux Kernel Development". Some information on threads/processes/etc. may be found here: http://www.win.tue.nl/~aeb/linux/lk/lk-10.html

A: Just reading the relevant lines from book and the example shared by you, it is clear that it is related to specific implementation of POSIX threads on GNU/Linux
In GNU/Linux, threads are implemented as processes.

Hence, Whenever you call pthread_create to create a
new thread, Linux creates a new process that runs that thread.
So in example code, when you do pthread_create(&thread, NULL, thread_func, NULL); the implementation creates a new process to run this newly created thread. This process will have a different PID (which is what getpid()call displays).
So, now you already have 2 process, one main process which is launched when you run the program and this new process created by system to support thread execution.
And the same implementation is also creating another process (which is internal to its implementation), which is termed as manager thread. And this is created when you invoke pthread_create


text:
Q: Programmatically load images in Flex I need to load several images as Bitmap or BitmapData objects. The images are hosted outside the Flex project, and they're referenced by an external configuration file, so I can't embed them. Because the images won't be displayed directly to the user (they're being added to a PDF that is generated for download), creating a grouping of Image objects, attaching them to the application, and waiting for their LoadComplete handler to fire seems inefficient.
What is the best way to load these images into an application?

A: Have you considered using Loader class?
var ldr:Loader = new Loader();
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
ldr.load(new URLRequest("image.png"));

function onLoad(e:Event):void
{
    var image:Bitmap = Bitmap(LoaderInfo(e.target).content);
    var bmpData:BitmapData = image.bitmapData;
    //use bmpdata the way you want
    trace(bmpdata.width);
    trace(bmpdata.height);
}


text:
Q: Compact Framework reset internet connection I'm uploading files from a Windows CE 6.0 using Compact Framework 2.0 and OpenNETCF. WiFi is not available, so I'm using a HSDPA connection. Before uploading I check for an internet connection by sending a ping to the upload server.
If the server is not reachable I want to try to reset the device's internet connection and then try again. Do you have any suggestions on how I can do that?

A: I assume there is no ConnectionManager available on CE6 as on Windows Mobile devices. So you need to use RAPI to handle the connection. You may use RasHangUp and the other API functions to enum connections etc: https://msdn.microsoft.com/en-us/library/aa450851.aspx


text:
Q: Divide values in data frame according to date range in another data frame I have two dataframes. Dataframe data one has two columns: one contains ymd dates, and the other values:
        date value
1 2009-10-23  1100
2 2009-05-01  5000
3 2010-01-13  3050
4 2010-07-24  2700
5 2009-06-16  2600

My second dataframe (named factors) also has two columns: another ymd date, and a coefficient. Here, for each month of each year, I always have two specific dates: the 1st and 15th of each month. This is how the data frame looks (I only added some dates on this minimal example, but there shouldn't be any 'jumps': I have continued data in a 10-year period):
         date coeff
1  2009-05-01  2.00
2  2009-05-15  3.00
3  2009-06-01  2.50
4  2009-06-15  4.00
5  2009-10-01  3.65
6  2009-10-15  4.80
7  2010-01-01  2.40
8  2010-01-15  1.90
9  2010-07-01  5.20
10 2010-07-15  4.30

The dataframes are ready to use on this fiddle: http://rextester.com/MOIY96065
My problem
I need to create a new column in dataframe 1 (named data) where this column is data$value / factors$coeff following a condition: it must use the coeff with the previous closest date value.
For example: date$value[1] should be divided by factors$coeff[6] (the value on October 15th), but date$value[2] should be divided by factors$coeff[1] (the value on May 1st).
My factors dataframe is ordered by date. I've been using lubridate to parse the dates from string type, but I don't know how can I make this work.

A: You can use findInterval() to get the indices for selecting the correct rows
from factors:
(i <- findInterval(date$date, factors$date))
#> [1]  6  1  7 10  4

date$value / factors$coeff[i]
#> [1]  229.1667 2500.0000 1270.8333  627.9070  650.0000

Created on 2018-08-09 by the reprex package (v0.2.0.9000).
Data:
date <- structure(list(date = structure(c(14540, 14365, 14622, 14814,
14411), class = "Date"), value = c(1100, 5000, 3050, 2700, 2600
)), row.names = c(NA, -5L), class = "data.frame")

factors <- structure(list(date = structure(c(14365, 14379, 14396, 14410,
14518, 14532, 14610, 14624, 14791, 14805), class = "Date"), coeff = c(2,
3, 2.5, 4, 3.65, 4.8, 2.4, 1.9, 5.2, 4.3)), row.names = c(NA,
-10L), class = "data.frame")

A: Adapted form @Frank answer's here
d <- function(x,y) {
      diff <- as.numeric(x-y)
      diff <- which.min(diff[diff>=0])
}

indx <- sapply(df$date, function(x) d(x,df1$date))

df_final <- cbind(df,df1[indx,,drop=FALSE])

df_final$result <- df_final$value/df_final$coeff

date value       date coeff    result
1 2009-10-23  1100 2009-10-15   4.8  229.1667
2 2009-05-01  5000 2009-05-01   2.0 2500.0000
3 2010-01-13  3050 2010-01-01   2.4 1270.8333
4 2010-07-24  2700 2010-07-15   4.3  627.9070
5 2009-06-16  2600 2009-06-15   4.0  650.0000

data
df<-read.table(text="        date value
           1 2009-10-23  1100
           2 2009-05-01  5000
           3 2010-01-13  3050
           4 2010-07-24  2700
           5 2009-06-16  2600
           ",header=TRUE)

df1<-read.table(text="         date coeff
           1  2009-05-01  2.00
           2  2009-05-15  3.00
           3  2009-06-01  2.50
           4  2009-06-15  4.00
           5  2009-10-01  3.65
           6  2009-10-15  4.80
           7  2010-01-01  2.40
           8  2010-01-15  1.90
           9  2010-07-01  5.20
           10 2010-07-15  4.30
           ",header=TRUE)


text:
Q: How to use fortran module subroutine in c I'm trying to use a fortran module subroutine in c and cannot get through, here is a simplified version of my problem:
I have one fortran module that contains a subroutine, and the second subroutine uses the module.
!md.f90
module myadd
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer a
a=a+1

end subroutine add1
end module myadd

!sb.f90
subroutine sq(a) bind(c)
use myadd
implicit none
integer a
call add1(a)
a=a*a
end subroutine sq

Now I want to call the sb function in c:
//main.cpp
extern "C"{ void sb(int * a); }
int main(){
  int a=2;
  sb(&a);
}

how should I link them together?
I tried something like
ifort -c md.f90 sb.f90
icc sb.o main.cpp

but it gives error

sb.o: In function sq': sb.f90:(.text+0x6): undefined reference to
  add1' /tmp/icc40D9n7.o: In function main': main.cpp:(.text+0x2e):
  undefined reference tosb'

Does anyone know how to solve the problem?

A: int main(void){
  int a=2;
  sb(&a);
  return 0;
}

and
module myadd
use iso_c_binding
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer (c_int),intent (inout) :: a
a=a+1

end subroutine add1
end module myadd

!sb.f90
subroutine sq(a) bind(c, name="sb")
use iso_c_binding
use myadd
implicit none
integer (c_int), intent(inout) :: a
call add1(a)
a=a*a
end subroutine sq

with
gcc -c main.c
gfortran-debug fort_subs.f90 main.o

It is easier to link with the Fortran compiler because it brings in the Fortran libraries.

A: The reason for your link error is twofold:

*

*you omitted the object file for the source file that holds the module from the final command line (md.o).

*you've called sq in the fortran sb in the C++ code.
Fix those and you'll be right to go.


text:
Q: Using getSimpleName() vs getName() for acquiring logger I've seen code that uses log4j, which acquires logger for a given Logger using
static public Logger getLogger(String name)

and
static public Logger getLogger(Class clazz)

with the former api passed explicitly with getSimpleName(), while the latter uses getName() on the passed Class. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?

A: Using of this.getClass().getName();
Returns :   alin.iwin.flickrbrowser.GetRawData
Meanwhile
private String LOG_TAG = this.getClass().getSimpleName();
Return only : GetRawData.

A: I prefer using the full name (Class.getName()). When packages are organized correctly, this allows tuning log4j to handle differently log messages originating from different parts of the java packages tree.
For example, you can easily configure all classes in packages starting with "com.mycompany.infra" to use a specific appender, and log only messages of level WARN or above.

A: Yes there is a huge difference.
I never use simpleName for Logger instance as it strips down the package name.
Apart from having problems when same class name exists in two different packages (leading to both classes getting the same logger instance), you lose the ability to control logger inheritance.
e.g. for two loggers:
com.foo.A
com.foo.B

in properties, i can just have:
log4j.logger.com.foo=DEBUG,CONSOLE

A: E.g. My class ShapeDemo.java resides in com.test package, and I have written code like below.
System.out.println("Name-->"+ShapeDemo.class.getName());
System.out.println("SimpleName-->"+ShapeDemo.class.getSimpleName());

This will output following
Name-->com.test.ShapeDemo
SimpleName-->ShapeDemo

A: You might get confused if you have many classes with the same simpleName in different packages.  Having many loggers with the same name should not be a problem otherwise - just could be confusing.


text:
Q: How to Show Http Header manager in request in jmeter I want to display HTTP Header manager which are used for API, I have added JSR223 PostProcessor for displaying request parameter which is working fine, now same I want to display Http Header manager used for API.

A: The Header Manager lets you add or override HTTP request headers. You can view the headers sent with the requests through the view result tree.
Select the request from the view result tree--> Request--> Request Headers

If you wish to see the headers in a table format select the HTTP button at the bottom of the window.

A: You can use the same JSR223 PostProcessor for displaying request and response headers, for example hers is how you can print them to the jmeter.log file:
log.info('Request headers: ' + System.getProperty('line.separator') + prev.getRequestHeaders())

log.info('Response headers: ' + System.getProperty('line.separator') + prev.getResponseHeaders())

in the above code prev stands for SampleResult class instance, see JavaDoc for more information on all methods and fields and Top 8 JMeter Java Classes You Should Be Using with Groovy article for more details on this and other JMeter API shorthands avaiable for hte JSR223 Test Elements.
Also View Results Tree listener does already have headers information stored, just click Request -> Request Headers and/or Response data -> Response Headers
Demo:


text:
Q: How to Dynamic create and remove a tabs in foundation 6? I want to make user to click for example add button in the tab section to dynamically create the content of the second tab base on what is in the first tab.
I achieve this in Bootstrap but i'm really stuck with this one in foundation.
Can someone please help here.
Thank you in advance

 Add Participant

+

Codepen: http://codepen.io/anon/pen/dMOGyO
How to achieve this in foundation.

A: Your current code is only adding the tab heading. In your .add-form click event you need to add a corresponding div for the tab content.
The line below uses the html content from the first tab and appends it to a new div, which is added to .tabs-content. It uses tabId to ensure it's associated with the correct tab heading:
$(".tabs-content").append('
' + $("#info1").html() + '
');

I'm also calling $(document).foundation(); after adding the new content to ensure any event listeners are rebound.
The Foundation 6 docs don't provide nearly enough information when it comes to programmatically selecting tabs, but I've come up with a solution after a bit of trial and error.
I had to remove the tabs-title class from the "+" button as it interferes with the tab selection. You'll have to re-style it using a different class name.
//Find the parent "ul" that contains the tabs
var target = document.getElementById("shop-main-tabs");
var options = {
    "linkClass": "tabs-title"
};

//Use the target "ul" to initialize the "Tabs" object.
var elem = new Foundation.Tabs($(target), options);

//Find the tab that will be selected
var tab = document.getElementById(tabId);
elem.selectTab($(tab));

Updated Pen


text:
Q: How to have multiple GitHub accounts on one computer? (Note not a copy of 80 Multiple github accounts on the same computer? )
In our lab we are using Git+Github to store the software controlling the measurement setup.
Most of the time we are working on the actual setup to live test the code we made.
Because different users are using the same computer it would be nice to quickly change the github account so that commits are attributed to the correct user.
As the guides listed on the GitHub site of the question above are no longer valid I was wondering what the best workflow would be to do this.
The main criterium is that once it is set up it should be easy to switch between accounts.

A: One option is to use the --author attribute as detailed in
https://stackoverflow.com/a/3696994/631619
Another option is to consider removing any [user] section from the ~/.git_config file (or just remove the entire file) for any individual (note that the file is in an individuals home - ~ - directory) who may be submitting from multiple accounts so it is never defaulted for them and is always prompted for.
At the command line this can be done with:
git config --global user.email ""


text:
Q: Помогите оптимизировать программу по времени работы (600мс)
Гоблины Мглистых гор очень любях ходить к своим шаманам. Так как гоблинов много, к шаманам часто образуются очень длинные очереди. А поскольку много гоблинов в одном месте быстро
образуют шумную толку, которая мешает шаманам проводить сложные медицинские манипуляции,
последние решили установить некоторые правила касательно порядка в очереди.
Обычные гоблины при посещении шаманов должны вставать в конец очереди. Привилегированные же гоблины, знающие особый пароль, встают ровно в ее середину, причем при нечетной длине
очереди они встают сразу за центром.
Так как гоблины также широко известны своим непочтительным отношением ко всяческим правилам и законам, шаманы попросили вас написать программу, которая бы отслеживала порядок
гоблинов в очереди.
Формат входных данных
В первой строке входных данный записано число N (1 <N <10**5
) − количество запросов.
Следующие N строк содержат описание запросов в формате:
• + i − гоблин с номером i (1 <i <N) встаёт в конец очереди.
• * i − привилегированный гоблин с номером i встает в середину очереди.
• - − первый гоблин из очереди уходит к шаманам. Гарантируется, что на момент такого запроса
очередь не пуста.
Формат выходных данных
Для каждого запроса типа - программа должна вывести номер гоблина, который должен зайти
к шаманам

import collections

num = int(input())

newList = collections.deque()

el = ''

mun = []

while (num):
    var = str(input())
    if var[0] == '+':

        newList.append(int(var[1:10000]))
    elif var[0] == '-':
        print(newList.popleft())
    else:
        flag = len(newList) // 2
        if len(newList) % 2 == 0:
            newList.insert((flag), int(var[1:]))
        else:
            newList.insert(((flag) + 1), int(var[1:]))
num -= 1

A: Ваша программа работает медленно потому что вставка элемента в середину очереди требует линейного времени - надо скопировать половину элементов очереди чтобы освободить место в середине для нового элемента.
Подсказка: если будете хранить две очереди примерно равного размера, вставка в середину будет занимать константу. Остальные операции тоже можно доработать так чтобы они остались константными.
Например:
import collections

q1 = collections.deque()
q2 = collections.deque()
for _ in range(int(input())):

    c = input().split()

    if c[0] == '+':
        q2.append(c[1])
    elif c[0] == '*':
        q2.appendleft(c[1])
    else:
        print(q1.popleft())

    if len(q1) < len(q2):
        q1.append(q2.popleft())


text:
Q: Before Insert Lookups are Null I am working on a before insert class that searches for a custom object record and populates it on the OpportunityLineItem. For a while this morning, it was not working. However, I found this post from Jeff Douglas that solved why my class was not working: http://blog.jeffdouglas.com/2010/02/23/relationship-lookup-objects-in-triggers-are-null/ The post describes that lookups are null on isnew triggers and that you must query the object to get the values.
I did this in my method and my debug statements shows that it works. The problem is I think I need to do the same thing it again in a later method. It doesn't make sense to me that I would need to make two queries again to get record info that I already have queried earlier in the process.
I have two questions:
* What am I doing wrong in my updateOLI method because as it's written it's not finding a match against my concatenation.
* Is there a way to reuse maps from one method to another?
Example:
public static void filterInsert(List<OpportunityLineItem> newlist)
{
    Set<String> olikeys = new Set<String>();
    List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
    Set<Id> oppIds = new Set<Id>();
    Set<Id> prodIds = new Set<Id>();

    // Create a set of all the unique Opp Ids that we need to query for
    for(OpportunityLineItem oliO : newList)
        oppIds.add(oliO.OpportunityId);

    // Create a map so that Opportunity is locatable by its Id (key)
    Map<Id, Opportunity> oppsMap = new Map<Id, Opportunity>(
        [SELECT Id, Account.OwnerId FROM Opportunity WHERE Id IN :oppIds]);

    // Create a set of all the unique Product Ids that we need to query for
    for(OpportunityLineItem oliP : newList)
        prodIds.add(oliP.Product2Id);

    // Create a map so that the Product is locatable by its Id (key)
    Map<Id, Product2> prodsMap = new Map<Id, Product2>(
        [SELECT Id, Practice__c FROM Product2 WHERE Id IN :prodIds]);

    // On Insert we add to all products
    for(OpportunityLineItem oppyLine : newList)
    {
        olikeys.add(oppsMap.get(oppyLine.OpportunityId).Account.OwnerId + '-' + prodsMap.get(oppyLine.Product2Id).Practice__c);
        olis.add(oppyLine);
    }

    Map<String, Responsible_Party__c> rmap = getResParty(olikeys);
    updateOLI(rmap, olis);
}

public static Map<String, Responsible_Party__c> getResParty(Set<String> olikeys)
{
    Map<String, Responsible_Party__c> rmap = new Map<String, Responsible_Party__c>();

    for(Responsible_Party__c r : [SELECT    Id,
                                            Name,
                                            User__c,
                                            Sector__c,
                                            Key__c
                                  FROM      Responsible_Party__c
                                  WHERE     Key__c IN : olikeys])
    {
        rmap.put(r.Key__c, r);
    }
    return rmap;

}

public static void updateOLI(Map<String, Responsible_Party__c> rmap, List<OpportunityLineItem> olis)
{
    for(OpportunityLineItem o : olis)
    {
        Responsible_Party__c r = rmap.get(o.Opportunity.Account.OwnerId + '-' + o.Product2.Practice__c);

        If(r != null)
        {
            o.Responsible_Party__c = r.Id;
        }
        //else{
        //  o.Responsible_Party__c = null;
        //}
    }
}

A: You can pass parameters from one method to the next. So, in filterInsert, you can take out olis (the OpportunityLineItem list):
for(OpportunityLineItem oppyLine : newList)
{
    olikeys.add(oppsMap.get(oppyLine.OpportunityId).Account.OwnerId + '-' + prodsMap.get(oppyLine.Product2Id).Practice__c);
}

Then, just pass the maps:
updateOLI(rmap, newList, oppsMap, prodsMap);

...
public static void updateOLI(Map<String, Responsible_Party__c> rmap, List<OpportunityLineItem> olis, Map<Id, Opportunity> oppsMap, Map<Id, Product2> prodsMap)

...
rmap.get(oppsMap.get(o.OpportunityId).Account.OwnerId + '-' + prodsMap.get(o.Product2Id).Practice__c);


text:
Q: How to use regular expressions to extract patterns above a certain value I have a string. I would like to generate a regex pattern that would only print the string with a value over 0.5
import re

text = 'xxxx || yyy || 0.7819662242 || zzz'

pattern = " " #regex here

if re.search(pattern, text):
    print("Yes!")
else:
    print("No!")

A: Generic Regex
(.* \|\| (1\.\d+|0\.[789]\d+) \|\| .*)
Specific Regex
(?P<username>[\w\d]*)(\s\|\|\s.*\s\|\|\s.*\s\|\|\s)(?P<botprob>(1\.\d+|0\.[789]\d+))(\s\|\|\s)(\w+)
Description
/ (.* \|\| (1\.\d|0\.[789]\d+) \|\| .*) /gm

1st Capturing Group (.* \|\| (1\.\d|0\.[789]\d+) \|\| .*)
  .* matches any character (except for line terminators)
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    matches the character   literally (case sensitive)
  \| matches the character | literally (case sensitive)
  \| matches the character | literally (case sensitive)
    matches the character   literally (case sensitive)

  2nd Capturing Group (1\.\d|0\.[789]\d+)
    1st Alternative 1\.\d
      1 matches the character 1 literally (case sensitive)
      \. matches the character . literally (case sensitive)
      \d matches a digit (equal to [0-9])
    2nd Alternative 0\.[789]\d+
      0 matches the character 0 literally (case sensitive)
      \. matches the character . literally (case sensitive)
      Match a single character present in the list below [789]
        789 matches a single character in the list 789 (case sensitive)
      \d+ matches a digit (equal to [0-9])
        + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    matches the character   literally (case sensitive)
    \| matches the character | literally (case sensitive)
    \| matches the character | literally (case sensitive)
        matches the character   literally (case sensitive)
    .* matches any character (except for line terminators)
  Global pattern flags
    g modifier: global. All matches (don't return after first match)
    m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Regex101

A: You can do:
>>> [e.rstrip() for e in tweets if re.search(r' 0\.[789]\d+ \|\|[^|]+$', e)]

Alternatively:
>>> [e.rstrip() for e in tweets if float(re.split(r'\|\|', e)[-2])>.7]

Either produces (\n added...):
['fasteddiekc || Wed Mar 18 07:16:32 +0000 2020 || #coronavirus shows that racists have absolutely 2 much time on their hands Firstly, those racists who hate POC & Râ\x80¦ || 0.8441984525 || irrelevant',
 'Georgia_VOL || Sun Mar 22 23:40:18 +0000 2020 || If your mountain of toilet paper falls on you and kills you, did you die from the coronavirus? || 0.8548931203 || irrelevant',
 "saintevenlive || Thu Mar 26 23:16:29 +0000 2020 || Things have been shitty enough (even before covid) that you don't have to waste time to watch shallow heavy handedâ\x80¦ || 0.8002252668000001 || irrelevant",
 'ioncorruption || Fri Jun 19 02:23:31 +0000 2020 || I hope your father recovers from the virus as soonas possible and the family does not get infected from Covid as thâ\x80¦ || 0.7434430488 || politics']

A: try this, just minor regex alteration
pattern = "(?P<username>[\w\d]*)(\s\|\|\s.*\s\|\|\s.*\s\|\|\s)(?P<botprob>0\.[7-9][0-9]+)(\s\|\|\s)(\w+)"


text:
Q: SetWindowsHookEx to block 64-bit WM_HOTKEY from 32-bit Our application requires running in a "secure kiosk mode" on Windows. We have a variety of ways we block various actions. One thing that we do is listen for the use of hotkeys using SetWindowsHookEx to register a WH_GETMESSAGE hook, then when a WM_HOTKEY message comes through we change it to WM_NULL (see code below). This works great in most cases but we recently uncovered an issue. On a 64-bit machine, if the application listening and responding to the hotkey is a 64-bit application we cannot block it with our 32-bit application.
We're trying to find ways to solve this and the only option I can think of is spawning a background 64-bit process to handle this hook for 64-bit applications. Are there other (more simple) alternatives?
Setting up the hook:
HHOOK getMessageHook = SetWindowsHookEx(WH_GETMESSAGE, GetMessageProc, hInst, 0);

GetMsgProc:
LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    switch (nCode)
    {
        case HC_ACTION:
        {
            MSG *msg = (MSG *) lParam;
            if (msg->message == WM_HOTKEY)
            {
                // A hotkey was pressed, changed the message to WM_NULL
                msg->message = WM_NULL;
            }
            break;
        }

        default:
            break;
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}


text:
Q: How to trigger keyboard interrupt I'm trying to use Twitter API to stream tweets, but I don't know how to stop the streaming automatically, unless using keyboard interrupt ( control+c).
import tweepy
import time
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
class listener(StreamListener):
    def on_data(self, data):
        #print data
        tweet = data.split(',"text":"')[1].split('","source')[0]
        print tweet
        saveThis = str(time.time()) + '::' + tweet
        saveFile = open('twitDB.csv','a')
        saveFile.write(saveThis)
        saveFile.write('\n')
        saveFile.close
        return True
    def on_error(self, status):
        print status

twitterStream = Stream(auth, listener())
twitterStream.filter(track=["car"])

so, how can I stop the data streaming automatically?

A: You can maintain a counter which you increment and check in on_status().
Once you reach your limit returning False should stop the stream. Try it like.
def on_status(self, status):
    print status.text
    self.n += 1
    if self.n < 20:
        return True
    else:
        print 'maxnum = '+str(self.n)
        return False


text:
Q: cannot git add.gitignore I  inputted the following:
mkdir project_name
cd project_name
git init
touch .gitignore
git add .gitignore

I got the following response:
The following paths are ignored by one of your .gitignore files:
.gitignore
Use -f if you really want to add them.
fatal: no files added

I couldn't find any gitignore files that could cause this.  Is there a recommended way to find out what is causing the issue?

A: It seems the file is ignored in the global ignore definition.
Search for the ~/.gitignore_global file and remove the line with .gitignore.


text:
Q: save path in database / or \ I want to save the path of an image in my database. I'm developing on a Windows system.
I'm using
setDestination( APPLICATION_PATH . "/userfiles/")

In my database I have a path like the following:
C:\wamp\www\cheyenne\application/userfiles\test...

If I try to use a relative path like \public\covers I get an error like "path or directory does not exist".
I'd prefer the 2nd possibility because the former webserver will be an Apache on a Linux.

A: It's not a good idea to store in a database the complete path of your picture. You really should consider to use a relative path and build the complete path on render, with a database view... My point of view is that you can or not know where your application will be and how your application will be deploy.
For example, today, you store your image on the same server, tomorow, because of traffic issues, you move all your pictures on a second server dedicated for pictures... if you store the complete path of your pictures, you have to execute a SQL request to change partial path and update your code. If you have juste a relative path, you just have to change your application configuration. This can be done in a config.local file that override your default configuration.
For the backslash... it's normal, you are on Windows. Use on your code the default php global variable DIRECTORY_SEPARATOR instead of "/".


text:
Q: Converting integer from 0 to 255 ( 1 byte ) into NSDATA I need exactly 1 byte for some kind of socket based application and i cant find a way to create it.

A: unsigned char mydata = 3;
[NSMutableData dataWithBytes:&mydata length:sizeof(mydata)];

NSData reference, unsigned char is used to save 1 byte.


text:
Q: Replace id by name in the comment without replace wrong case I have a comment contain mentioned userId like this:
$subject = "@1 likes @12 and @123";

Now I want to replace these ids with the real name inside an array:
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];

I got stuck in the situation Henry user can replace all the id contain @1 like this:
$subjectReplaced = "@Henry likes @Henry2 and @Henry23"

// What I want is:
$subjectReplaced = "@Henry likes @Tony and @Pizza";

Anyone help me, please?
Full code here:
<?php

$subject = "@1 likes @12 and @123";
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];

foreach ($users as $id => $user) {
  $subject = str_replace('@' . $id, '@' . $user, $subject);
}

echo $subject;

A: You can explode your subject based on spaces and do a preg_match on each token you receive. If the token  matches your @some_text format, we do a replacement in the subject_data array below. In the end, we just do an implode() to get the replaced string.
<?php

$users = ['1' => "Henry", '12' => "Tony", '123' => "Pizza"];

$subject = "@1 likes @12 and @123";

$subject_data = explode(" ",$subject);

foreach($subject_data as $key => $each_data){
    if(preg_match('/@.+/',$each_data) === 1){
        $subject_data[$key] = "@" . $users[substr($each_data,1)];
    }
}

echo implode(" ",$subject_data);

Note that this also takes care of overlapping or you can say prefix string issues, like @1 and @12. One of the reasons why I did not use str_replace().

A: Another approach using the preg_split to break the string, then looping through the parts of the breaking string and replacing the ids with the associated user id and finally using implode to join the string parts.
$subject = "@1 likes @12 and @123";

$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];

$parts = preg_split("/(\@\d*)/", $subject, 0, PREG_SPLIT_DELIM_CAPTURE);

foreach ($parts as &$part) {
    if (strpos($part, '@') !== 0) {
        continue;
    }

    $part = $users[substr($part, 1, strlen($part) - 1)] ?? '';
}

$result = implode($parts);

echo $result;

Result:
Henry likes Tony and Pizza
Test it here

A: You can use array_walk with str_replace
$subject = "@1 likes @12 and @123";
$patterns = ['1' => 'Henry','12' => 'Tony' ,'123' => 'Pizza'];
$previousKey ='';
array_walk($patterns, function($v, $k) use (&$subject, &$previousKey, $patterns){
    if(!empty($previousKey))
      $subject = str_replace(str_replace($previousKey, $patterns[$previousKey], $k), $v, $subject);
 else
      $subject = str_replace($k, $v, $subject);
$previousKey = $k;
    $previousKey = $k;
});
echo $subject;

Working example

A: You can just use strtr to do the replacements. strtr is good for this job because it replaces longer strings first and then won't look at them again so it avoids possible double replacement issues.
$subject = "@1 likes @12 and @123";
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];
echo strtr($subject, $users);

Output:
@Henry likes @Tony and @Pizza

Demo on 3v4l.org


text:
Q: Android Adding a button with multiline text inside MaterialButtonToggleGroup doesn't work I am trying to show a multiline button inside a MaterialButtonToggleGroup but it always shows me ... at the newline
but it works fine outside the MaterialButtonToggleGroup  I have tried

*

*using \n and

*using <br/> HTML tag with Html.form method
As shown in the image below the first button is outside the MaterialButtonToggleGroup but the second is inside it.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".conversation.ui.conversations.AddNewConversationFragment">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_margin="20dp"
            android:background="@drawable/register_field_background"
            android:orientation="vertical"
            android:padding="10dp">

            <ImageView
                android:id="@+id/img_close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_baseline_close_24"
                android:tint="@android:color/darker_gray"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="ContentDescription" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/add_anyone"
                android:singleLine="false"
                android:maxLines="2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/gray100"
                android:text="This is Multi Line Text
Line2"
                android:textAllCaps="false"
                android:textColor="@color/gray700"
                app:iconTint="@color/gray700"
                />
            <com.google.android.material.button.MaterialButtonToggleGroup
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:layout_marginBottom="10dp"
                android:orientation="vertical"
                app:checkedButton="@+id/button_add_native"
                app:layout_constraintBottom_toTopOf="@+id/tv_select_address"
                app:layout_constraintTop_toBottomOf="@+id/textView"
                app:selectionRequired="true"
                app:singleSelection="true">

                <com.google.android.material.button.MaterialButton
                    android:id="@+id/add_anyone"
                    android:singleLine="false"
                    android:maxLines="2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:backgroundTint="@color/gray100"
                    android:text="This is Multi Line Text
Line2"
                    android:textAllCaps="false"
                    android:textColor="@color/gray700"
                    app:iconTint="@color/gray700"
                    />

            </com.google.android.material.button.MaterialButtonToggleGroup>

            <TextView
                android:id="@+id/textView"
                style="@style/bottomSheetDialogHeader"
                android:layout_marginStart="16dp"
                android:letterSpacing="0.1"
                android:text="@string/add_conversation_dialog_title"
                android:textAllCaps="true"
                app:layout_constraintBottom_toBottomOf="@+id/img_close"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/img_close" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/tv_select_address"
                style="@style/LinguisticMainLayoutOrangeButton"
                android:paddingBottom="10dp"
                android:text="@string/start_chatting"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </RelativeLayout>
</layout>

A: It is an expected result.You can check the source code below where the multiline is overridden.
You can set it programmatically. Something like:
    val button : MaterialButton = findViewById(R.id.add_anyone)
    button.maxLines = 2

Source code:
https://github.com/material-components/material-components-android/blob/e944d1b2a6ee5d9d5a338de0c0061f7b02790f77/lib/java/com/google/android/material/button/MaterialButtonToggleGroup.java#L751-L754
  private void setupButtonChild(@NonNull MaterialButton buttonChild) {
    buttonChild.setMaxLines(1);
    buttonChild.setEllipsize(TruncateAt.END);
    buttonChild.setCheckable(true);

A: An alternative trick for future reference:

*

*Provide your own custom class, let's name it CustomMaterialButtonToggleGroup, which extends MaterialButtonToogleGroup

example:
public class CustomMaterialButtonToggleGroup extends MaterialButtonToggleGroup {
    public CustomMaterialButtonToggleGroup(@NonNull Context context) {
        super(context);
    }

    public CustomMaterialButtonToggleGroup(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomMaterialButtonToggleGroup(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        if(child instanceof MaterialButton)
        {
            ((MaterialButton) child).setMaxLines(2);
        }
    }

This way we enforce via code the child views of the MaterialToggleGroup to implement maxLines!
Final the 2nd weird part is:

*Go to your Activity/Fragment in which you define your button...and set it via code!

example:
SampleButton.setText("Hey\nI'm multiline"); // notice the escape character of newline-> \n

Afterwards extract it in the strings.xml as you would do normally!


text:
Q: malloc in assembly 8086 I need to receive input from user and I am required to use malloc to init the buffer first. I can't find any example online.
This is the buffer:
 section .bss
        buffer:
                resb 80                     ;store my input

How is it done? Is this ok? (it compiles but I don't think it works...)
    push 80
    push buffer
    call malloc
    add esp, 8

or maybe this? (this doesn't compile)
push 80
push buffer
call malloc
add esp, 8
mov buffer, [eax]

The thing is that when I give the buffer the input 0, it prints 2608
instead of 48 as the ASCII value should print.
Input 1 -> gives 2609 accordingly. So my guess is that somehow the buffer has values it's not supposed to have.
This is the fgets part (it works ok)
 push dword [stdin]             ;fgets need 3 param
    push dword 80                   ;max lenght
    push dword buffer               ;input buffer
    call fgets
    add esp, 12                     ;remove 3 push from stuck

and this is the print part:
push dword [buffer]             ;push string to stuck
push INT_FORMAT                     ; its INT_FORMAT:DB "%d", 10, 0
call printf
add esp, 8              ;remove pushed argument

A: malloc has one DWORD parameter, which is the size in bytes to allocate, so it should be called:
push <size>
call malloc
add esp, 4
; now eax points to an allocated buffer of the requested size
mov [eax], ebx ; will set the first 4 bytes of the buffer to ebx (etc...)


text:
Q: Prevent attachment of Certain type while sending email I have been trying to prevent an attachment of type pdf while sending emails within Cases. I create an email, attach a pdf document. The process builder fires on Email creation which in turn calls a flow. The HasAttachment on email returns true. However when i check for attachement ids, it returns null. The reason being, during the process of sending the email. the attachment is temporarily created with the following prefix 0F0 which stands for EmailTempAttachmentMap, but i cannot access this object in a flow. So cannot prevent this type of attachment. Once the email is sent, the attachment object changes prefix to 00P which is the standard prefix for attachments and I can go and delete these using a flow. But i want to prevent attachement of a certain type being added during the send and not after.
Has anybody faced this issue. Salesforce support has not been able to solve it either.

A: Since this is on Case, that would mean you're using the EmailMessage object. In order to send/save the outbound message, it would seem the record would need to pass any validation rules you created for it. With the being the situation, I don't see why creating a validation rule for EmailMessage records sent where ParentId = CaseId, couldn't be required not to have an attachment with mime type="text/PDF". That's how I would recommend approaching solving this issue.


text:
Q: Model associations I have two models Library and Book. In my Library model, I have an array - book_ids. The primary key of Book model is ID.
How do I create a has_many :books relation in my library model?
This is a legacy database we are using with rails.
Thanks.

A: Your database schema doesn't really conform with the prescribed Rails conventions so you will probably have a hard time making the default has_many association work. Have you tried fiddling with the custom SQL options with it thought?
If you can't get the built in has_many association to work, you'll have to roll your own. I would define the books and books= methods on your Library model, and inside them set a virtual attribute, which you then save as an array in the database. Perhaps something like this:
class Book > ActiveRecord::Base; end

class Library > ActiveRecord::Base

  before_save :serialize_books

  def books
    @books || nil
  end

  def books=(new_books)
    @books = new_books
  end

  private
  def serialize_books
    @attributes['books'] = "[" + @books.collect {|b| b.id }.join(',') + "]"
  end
end

That up there wouldn't pull out the dataIf you wanted to go even more gung ho and support single query find operations, you could use some custom SQL in a scope or override find and add it to the default options. Comment if you want help with any of this!

A: If you want to use has_many you could use the options :counter_sql and :finder_sql using the MySQL LIKE or REGEX syntax. But its probably better to first load the Libary model, then parse the book_ids column and load the books, or directly build a query with that string.

A: Consider using :serialize method with ActiveRecord:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002284
it might do what you want


text:
Q: Incorrect valid coins value. Error in code logic I am assigned with the task of giving coins to the user on successful delivery of an order. The coins come with an expiration date of 45 days.
I am using MongoDB and have 2 collections: User and Ledger.
User collection has a key currentCoins which holds the current available coins of the user.
Ledger stores the both positive and negative entry for coin transaction.
Ledger Schema
credit   userId   usedAmount   matched   createdAt   expirationDate  isExpired
positive credit value defines addition of coins and vice-versa.
Problem occurs when I try to calculate spendable coins for a user and it should match with currentCoins value but it's always coming less than it.
Query I am running on ledger collection to get documents through which I am calculating the spendable coins
{
 credit: { $gt: 0 }, //get positive entries only
 matched: false, // when usedAmount is less than the credit amount which means some coins can still be used
 expirationDate: { $lte: new Date() },
 userId: "userId",
 isExpired: false
}

Then I run a loop over the resulted documents and calculate required coins
let coins = 0;
coins += (doc.credit - doc.usedAmount);

Ideally currentCoins should equal to coins but it's not the case.
Also, whenever a user spends coins, I get the oldest documents with usable coins and deduct coins in that order.

I cannot seem to find what's wrong with my logic


text:
Q: Defining Schema for Neo4J Using Neo4JClient in C# How to correctly/standardly define schema for neo4j database in my C# application?
In my application, I have nodes with properties and relations with properties. I want to define templates/Classes of these nodes and relations that can then be created and related at run time and retrieved as objects of a class with queries.
After a lot of search and research, I found something that was nearly related to my question:
http://blog.micic.ch/net/using-neo4j-graph-db-with-c-net
But according to the Neo4j Documentation these are legacy methods.
https://github.com/Readify/Neo4jClient/wiki
So What is the Current standard way in Neo4J 2.0? As we also have labels now.
I hope I am clear enough in my question. If not, Please let me know.

A: The basic idea is that now you use the Cypher querying capabilities to do everything, so where as Darko uses the REST API to Create / CreateRelationship the client has moved to use Cypher instead.
This means you no-longer need the Relationship based classes, and can stick to POCO (Plain Old CLR Objects) for storing and querying - which makes your code simpler to use...
The standard ways can all be found on the 'Cypher Examples' page on the Neo4jClient wiki, and I've put a gist up with an updated version of Darko's code.
All the addition of labels etc comes from the way you write the Cypher, and as Neo4jClient is as near as can be to being direct Cypher (but with C# niceness added in) the translation should be pretty simple.


text:
Q: how to use google material icons as class instead of  tag According to the guideline in the Google Material website we have to use material icons in  _i _   tag.
the question is how to add the icons as font-awesome. something like :
Class="material-icons face"

instead of
 face

A: Yes,you can add the material icons as classes using the after pseudo elements.check out the fiddle

.face {
    position:relative;
    display:inline-block;
}

.face:after {
    content: "face";
}

A: There's an easier way than the accepted answer. I got inspiration for this from the plugin css-toolip, which utilises the attr() css function (surprisingly has high browser adoption).

While attr() is supported for effectively all browsers for the content property...
  https://caniuse.com/#search=css%20attr

.material-icons:after {
    content: attr(data-icon);
}

This means that you don't have to add css for each icon that you want to use.

A: You can use IcoMoon (an outstanding free tool to generate fonts). Set class, prefix/suffix etc to adjust then you can easily add icons by

A: It's also possible to create the selectors with Sass, if someone don't want to use data selectors.
$icons: "content_paste_search", "format-size", "search";

@each $icon in $icons {
  .material-icons-#{$icon}:after {
    content: $icon;
  }
}


text:
Q: Backbone and Coffeescript "this" reference issue I have a problem with the "this" reference on Backbone with Coffeescript, this is a method which shows information of an artist:
show: (id) ->
    self = @
    if @collection
        artist = @collection.get(id)
        @renderArtist(artist)
    else
        artist = new DemoBackbone.Models.Artist({id: id})
        artist.fetch
            success: ->
                self.renderArtist(artist)

renderArtist: (artist) ->
    view = new DemoBackbone.Views.ArtistsShow(model: artist)
    $('#content_artists').html(view.render().el)

This works perfectly, but I'm using the "self = @" statement so I can use the Class function "renderArtist", but is there a more "elegant" way to do this on "success: -> self.renderArtist(artist)", so I can avoid using the "self = @" line??
Something like
success: @->
    @renderArtist(artist)

I'm not pretty sure but I think there should be a way to do this.
Thanks

A: This is exactly what the double-arrow function in CoffeeScript does. It will generate code like you have shown for you automatically so you don't have to write it yourself.
success: =>
    @renderArtist(artist)


text:
Q: How to set up DAGGER dependency injection from scratch in Android project? How to use Dagger? How to configure Dagger to work in my Android project?
I'd like to use Dagger in my Android project, but I find it confusing.
EDIT: Dagger2 is also out since 2015 04 15, and it's even more confusing!
[This question is a "stub" on which I am adding to my answer as I learned more about Dagger1, and learn more about Dagger2. This question is more of a guide rather than a "question".]

A: Guide for Dagger 2.x (Revised Edition 6):
The steps are the following:
1.) add Dagger to your build.gradle files:

*

*top level build.gradle:

.
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' //added apt for source code generation
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

*

*app level build.gradle:

.
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' //needed for source code generation

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "your.app.id"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    apt 'com.google.dagger:dagger-compiler:2.7' //needed for source code generation
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.dagger:dagger:2.7' //dagger itself
    provided 'org.glassfish:javax.annotation:10.0-b28' //needed to resolve compilation errors, thanks to tutplus.org for finding the dependency
}

2.) Create your AppContextModule class that provides the dependencies.
@Module //a module could also include other modules
public class AppContextModule {
    private final CustomApplication application;

    public AppContextModule(CustomApplication application) {
        this.application = application;
    }

    @Provides
    public CustomApplication application() {
        return this.application;
    }

    @Provides
    public Context applicationContext() {
        return this.application;
    }

    @Provides
    public LocationManager locationService(Context context) {
        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }
}

3.) create the AppContextComponent class that provides the interface to get the classes that are injectable.
public interface AppContextComponent {
    CustomApplication application(); //provision method
    Context applicationContext(); //provision method
    LocationManager locationManager(); //provision method
}

3.1.) This is how you would create a module with an implementation:
@Module //this is to show that you can include modules to one another
public class AnotherModule {
    @Provides
    @Singleton
    public AnotherClass anotherClass() {
        return new AnotherClassImpl();
    }
}

@Module(includes=AnotherModule.class) //this is to show that you can include modules to one another
public class OtherModule {
    @Provides
    @Singleton
    public OtherClass otherClass(AnotherClass anotherClass) {
        return new OtherClassImpl(anotherClass);
    }
}

public interface AnotherComponent {
    AnotherClass anotherClass();
}

public interface OtherComponent extends AnotherComponent {
    OtherClass otherClass();
}

@Component(modules={OtherModule.class})
@Singleton
public interface ApplicationComponent extends OtherComponent {
    void inject(MainActivity mainActivity);
}

Beware:: You need to provide the @Scope annotation (like @Singleton or @ActivityScope) on the module's @Provides annotated method to get a scoped provider within your generated component, otherwise it will be unscoped, and you'll get a new instance each time you inject.
3.2.) Create an Application-scoped component that specifies what you can inject (this is the same as the injects={MainActivity.class} in Dagger 1.x):
@Singleton
@Component(module={AppContextModule.class}) //this is where you would add additional modules, and a dependency if you want to subscope
public interface ApplicationComponent extends AppContextComponent { //extend to have the provision methods
    void inject(MainActivity mainActivity);
}

3.3.) For dependencies that you can create via a constructor yourself and won't want to redefine using a @Module (for example, you use build flavors instead to change the type of implementation), you can use @Inject annotated constructor.
public class Something {
    OtherThing otherThing;

    @Inject
    public Something(OtherThing otherThing) {
        this.otherThing = otherThing;
    }
}

Also, if you use @Inject constructor, you can use field injection without having to explicitly call component.inject(this):
public class Something {
    @Inject
    OtherThing otherThing;

    @Inject
    public Something() {
    }
}

These @Inject constructor classes are automatically added to the component of the same scope without having to explicitly specify them in a module.
A @Singleton scoped @Inject constructor class will be seen in @Singleton scoped components.
@Singleton // scoping
public class Something {
    OtherThing otherThing;

    @Inject
    public Something(OtherThing otherThing) {
        this.otherThing = otherThing;
    }
}

3.4.) After you've defined a specific implementation for a given interface, like so:
public interface Something {
    void doSomething();
}

@Singleton
public class SomethingImpl {
    @Inject
    AnotherThing anotherThing;

    @Inject
    public SomethingImpl() {
    }
}

You'll need to "bind" the specific implementation to the interface with a @Module.
@Module
public class SomethingModule {
    @Provides
    Something something(SomethingImpl something) {
        return something;
    }
}

A short-hand for this since Dagger 2.4 is the following:
@Module
public abstract class SomethingModule {
    @Binds
    abstract Something something(SomethingImpl something);
}

4.) create an Injector class to handle your application-level component (it replaces the monolithic ObjectGraph)
(note: Rebuild Project to create the DaggerApplicationComponent builder class using APT)
public enum Injector {
    INSTANCE;

    ApplicationComponent applicationComponent;

    private Injector(){
    }

    static void initialize(CustomApplication customApplication) {
        ApplicationComponent applicationComponent = DaggerApplicationComponent.builder()
           .appContextModule(new AppContextModule(customApplication))
           .build();
        INSTANCE.applicationComponent = applicationComponent;
    }

    public static ApplicationComponent get() {
        return INSTANCE.applicationComponent;
    }
}

5.) create your CustomApplication class
public class CustomApplication
        extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Injector.initialize(this);
    }
}

6.) add CustomApplication to your AndroidManifest.xml.
<application
    android:name=".CustomApplication"
    ...

7.) Inject your classes in MainActivity
public class MainActivity
        extends AppCompatActivity {
    @Inject
    CustomApplication customApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Injector.get().inject(this);
        //customApplication is injected from component
    }
}

8.) Enjoy!
+1.) You can specify Scope for your components with which you can create Activity-level scoped components. Subscopes allow you to provide dependencies that you only need only for a given subscope, rather than throughout the whole application. Typically, each Activity gets its own module with this setup. Please note that a scoped provider exists per component, meaning in order to retain the instance for that activity, the component itself must survive configuration change. For example, it could survive through onRetainCustomNonConfigurationInstance(), or a Mortar scope.
For more info on subscoping, check out the guide by Google. Also please see this site about provision methods and also the component dependencies section) and here.
To create a custom scope, you must specify the scope qualifier annotation:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface YourCustomScope {
}

To create a subscope, you need to specify the scope on your component, and specify ApplicationComponent as its dependency. Obviously you need to specify the subscope on the module provider methods too.
@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
        extends ApplicationComponent {
    CustomScopeClass customScopeClass();

    void inject(YourScopedClass scopedClass);
}

And
@Module
public class CustomScopeModule {
    @Provides
    @YourCustomScope
    public CustomScopeClass customScopeClass() {
        return new CustomScopeClassImpl();
    }
}

Please note that only one scoped component can be specified as a dependency. Think of it exactly like how multiple inheritance is not supported in Java.
+2.) About @Subcomponent: essentially, a scoped @Subcomponent can replace a component dependency; but rather than using a builder provided by the annotation processor, you would need to use a component factory method.
So this:
@Singleton
@Component
public interface ApplicationComponent {
}

@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
        extends ApplicationComponent {
    CustomScopeClass customScopeClass();

    void inject(YourScopedClass scopedClass);
}

Becomes this:
@Singleton
@Component
public interface ApplicationComponent {
    YourCustomScopedComponent newYourCustomScopedComponent(CustomScopeModule customScopeModule);
}

@Subcomponent(modules={CustomScopeModule.class})
@YourCustomScope
public interface YourCustomScopedComponent {
    CustomScopeClass customScopeClass();
}

And this:
DaggerYourCustomScopedComponent.builder()
      .applicationComponent(Injector.get())
      .customScopeModule(new CustomScopeModule())
      .build();

Becomes this:
Injector.INSTANCE.newYourCustomScopedComponent(new CustomScopeModule());

+3.): Please check other Stack Overflow questions regarding Dagger2 as well, they provide a lot of info. For example, my current Dagger2 structure is specified in this answer.
Thanks
Thank you for the guides at Github, TutsPlus, Joe Steele, Froger MCS and Google.
Also for this step by step migration guide I found after writing this post.
And for scope explanation by Kirill.
Even more information in the official documentation.

A: Guide for Dagger 1.x:
The steps are the following:
1.) add Dagger to the build.gradle file for the dependencies
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    ...
    compile 'com.squareup.dagger:dagger:1.2.2'
    provided 'com.squareup.dagger:dagger-compiler:1.2.2'

Also, add packaging-option to prevent an error about duplicate APKs.
android {
    ...
    packagingOptions {
        // Exclude file to avoid
        // Error: Duplicate files during packaging of APK
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
}

2.) create an Injector class to handle the ObjectGraph.
public enum Injector
{
    INSTANCE;

    private ObjectGraph objectGraph = null;

    public void init(final Object rootModule)
    {

        if(objectGraph == null)
        {
            objectGraph = ObjectGraph.create(rootModule);
        }
        else
        {
            objectGraph = objectGraph.plus(rootModule);
        }

        // Inject statics
        objectGraph.injectStatics();

    }

    public void init(final Object rootModule, final Object target)
    {
        init(rootModule);
        inject(target);
    }

    public void inject(final Object target)
    {
        objectGraph.inject(target);
    }

    public <T> T resolve(Class<T> type)
    {
        return objectGraph.get(type);
    }
}

3.) Create a RootModule to link your future modules together. Please note that you must include injects to specify every class in which you will use @Inject annotation, because otherwise Dagger throws RuntimeException.
@Module(
    includes = {
        UtilsModule.class,
        NetworkingModule.class
    },
    injects = {
        MainActivity.class
    }
)
public class RootModule
{
}

4.) In case you have other sub-modules within your modules specified in your Root, create modules for those:
@Module(
    includes = {
        SerializerModule.class,
        CertUtilModule.class
    }
)
public class UtilsModule
{
}

5.) create the leaf modules which receive the dependencies as constructor parameters. In my case, there was no circular dependency, so I don't know if Dagger can resolve that, but I find it unlikely. The constructor parameters must also be provided in a Module by Dagger, if you specify complete = false then it can be in other Modules too.
@Module(complete = false, library = true)
public class NetworkingModule
{
    @Provides
    public ClientAuthAuthenticator providesClientAuthAuthenticator()
    {
        return new ClientAuthAuthenticator();
    }

    @Provides
    public ClientCertWebRequestor providesClientCertWebRequestor(ClientAuthAuthenticator clientAuthAuthenticator)
    {
        return new ClientCertWebRequestor(clientAuthAuthenticator);
    }

    @Provides
    public ServerCommunicator providesServerCommunicator(ClientCertWebRequestor clientCertWebRequestor)
    {
        return new ServerCommunicator(clientCertWebRequestor);
    }
}

6.) Extend Application and initialize the Injector.
@Override
public void onCreate()
{
    super.onCreate();
    Injector.INSTANCE.init(new RootModule());
}

7.) In your MainActivity, call the Injector in the onCreate() method.
@Override
protected void onCreate(Bundle savedInstanceState)
{
    Injector.INSTANCE.inject(this);
    super.onCreate(savedInstanceState);
    ...

8.) Use @Inject in your MainActivity.
public class MainActivity extends ActionBarActivity
{
    @Inject
    public ServerCommunicator serverCommunicator;

...

If you get the error no injectable constructor found, make sure you did not forget the @Provides annotations.


text:
Q: Runaway Ladda button - won't stop I'm trying to use a Ladda progress indicator button. The spinner starts fine, but when I run a setTimeout to simulate another function, it never stops afterward.
Here's the code:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Ladda</title>
    <link rel="stylesheet" href="css/demo.css">
    <link rel="stylesheet" href="dist/ladda.min.css">
  </head>
  <body>

    <button id="btn" class="ladda-button" data-color="gray" data-style="expand-right">Fred!</button>

    <script src="dist/spin.min.js"></script>
    <script src="dist/ladda.min.js"></script>

    <script>

      document.getElementById('btn').onclick = function() {

        var l = Ladda.create(document.querySelector('.ladda-button'));
        l.start();
        var  endIt = setTimeout(stopIt, 5000);
      }

      function stopIt() {
        l.stop();    // Also tried Ladda.stopAll();
        alert("End it All!");
      }

    </script>
  </body>
</html>

Any thoughts on how to stop this? TIA

A: The variable l does not exist in the stopIt-function.
<script>

  // Ladda variable needs to be put outside of click event or
  // the stopId-function won't be able to use it.

  var l = Ladda.create(document.querySelector('.ladda-button'));

  document.getElementById('btn').onclick = function() {
    l.start();
    var endIt = setTimeout(stopIt, 5000);
  }

  function stopIt() {
    l.stop();    // Also tried Ladda.stopAll();
    alert("End it All!");
  }

</script>


text:
Q: How to register broadcast receiver from Manifest? I want to create a background app with no UI.
So, I have a broadcast receiver and I am trying to register it from the manifest. This is what I did inside my manifest:
<receiver
        android:name="background.broadcastReceivers.GPSStartedReceiver">

        <intent-filter android:priority="100">
            <action
                android:name="android.location.PROVIDERS_CHANGED"
                android:enabled="true"/>
        </intent-filter>
</receiver>

But when I run the app the broadcast receiver is never being registered.
When I register my receiver from a test activity, it works fine.
Why could this be happening?
This is what I am doing inside the test activity:
    private GPSStartedReceiver receiver = new GPSStartedReceiver();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Register a broadcast receiver which listens to GPS provider changes
        this.registerReceiver(receiver,
                new IntentFilter("android.location.PROVIDERS_CHANGED"));
    }

A:
I want to create a background app with no UI.

That is not practical.

But when I run the app the broadcast receiver is never being registered. When I register my receiver from a test activity, it works fine. Why could this be happening?

Manifest-registered receivers do not work upon installation. They only work after something uses an explicit Intent to start up one of the app's components. For 99.9% of apps, that is their home screen launcher activity.

A: I wrote a minimal app with the following manifest entry:
<receiver android:name="test.Receiver">
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED"/>
    </intent-filter>
</receiver>

And test.Receiver class:
package test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Receiver extends BroadcastReceiver {

    @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("@@@", "here");
        }
    }

My log message prints when I toggled the GPS on the device. Maybe your manifest XML has too much extra stuff in it?


text:
Q: How to set the background image for textview with Glide? How do I set background image for text with glide?
file[0] = "mnt/sdcard/sort_icon.png"

SimpleTarget target = new SimpleTarget<Drawable>(){
                    @Override
                    public void onResourceReady(Drawable resource, GlideAnimation<? super Drawable> glideAnimation) {
                        txtView.setBackground(resource);
                    }
                };
                Glide.with(getBaseContext())
                        .load(file[i-4])
                        .into(target);

A: Solution:
Try this:
Add the implementation in your gradle(app):
dependencies {
    .....
    .....

    def glide = "4.8.0"

    // Glide
    implementation "com.github.bumptech.glide:glide:$glide"
    annotationProcessor "com.github.bumptech.glide:compiler:$glide"
    .....
}

Then, in your Activity/Fragment:
File file = new File(file[i-4]);
Uri imageURI = Uri.fromFile(file);

Glide.with(MainActivity.this)
     .load(imageURI)
     .apply(RequestOptions.placeholderOf(R.drawable.ic_launcher))
     .into(new SimpleTarget<Drawable>() {
          @Override
          public void onResourceReady(@NonNull Drawable resource,
                      @Nullable Transition<? super Drawable> transition) {

                     txtView.setCompoundDrawablesWithIntrinsicBounds(resource, null, null, null);

                }
            });

See if it works.