text:
Q: Margin-right from column I have written this code but I have some issues and questions.
First of all, as you can see in the Pen, the second menu item is "active". For some reason in the Pen only and not when I run the code in my browser there is a gray background.
Why is that and how can I be sure that there will be no background in any browser?
Secondly, as you can see in the html I have set the columns to col-md-2 and col-md-10 and as I understand, the content in the col-md-2 has less space than the one in col-md-10 but in total they should add up to the whole browser's window size.
The content of the col-md-10 though acts as if there is less space than actually exists as can be seen here.
(in the Pen there also is a margin left that is not displayed in my browser)
The HTML

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-navbar-collapse">
                          Toggle navigation

                        </button>
                        Menu

Menu Item 1

Menu Item 2

Menu Item 3

Menu Item 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet rhoncus dui, vel tempor purus. Proin eu gravida elit. Donec nisi sapien, ultricies elementum justo in, ultricies semper nisi.

The CSS
/* make sidebar nav vertical */
    @media (min-width: 768px)
    {
      .sidebar-nav .navbar .navbar-collapse {
        padding: 0;
        max-height: none;
      }
      .sidebar-nav .navbar ul {
        float: none;
      }
      .sidebar-nav .navbar ul:not {
        display: block;
      }
      .sidebar-nav .navbar li {
        float: none;
        display: block;
      }
      .sidebar-nav .navbar li a {
        padding-top: 12px;
        padding-bottom: 12px;
      }
    }

    .container
    {
        margin: 0px;
    }

    #myContent
    {
        margin-top: 25%;
    }

    #verticalMenu
    {
        margin-top: 50%;
        background-color: transparent;
        border: none;
    }

    #menuItems a
    {
        color: black;
    }

    #menuItems a:hover
    {
        color: red;
        background-color: white;
    }

    .navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:focus, .navbar-default .navbar-nav>.active>a:hover
    {
        background-color: transparent;
        border-right: 3px solid black;
    }

    .navbar-default .navbar-nav>li>a
    {
        border-right: 3px solid red;
        background-color: white;
        text-align: right;
    }

    .navbar-default .navbar-toggle
    {
        border: 2px solid red;
        border-color: red;
    }

    .navbar-default .navbar-toggle:focus, .navbar-default .navbar-toggle:hover
    {
        background-color: transparent;
    }

A: *

*The reason why the background of the active menu item is gray is because the CSS in the codepen is loaded before the bootstrap CSS and therefore the CSS where you try to set the   background-color: transparent; won't be prioritized over the bootstrap CSS. Same reason for the margin-left probably.

*the col-md-10 sets the width of the div to 83.33333% (10/12). As in 83.333% of its parent div, which is a container with a set pixel width. If you changed the class .container to .container-fluid it will instead go all the way out because the .container-fluid has a width of 100%.


text:
Q: Low latency R submits I have created some R codes, which accept a csv and produces and output, now I call these by:
Rscript code.R input.csv

Here code.R is the the code to be executed and input.csv is the file which it uses as input
Problem:
The script takes 5 seconds or more to produce results, that is because R is called from shell, the libraries need time to be loaded.
Question:
Is it possible to run R in background or as a service with all libraries loaded that I can just do submit my job and it just takes time to compute?
Full disclosure:
The script is a ML model which loads an .RDA object and the scripts calls predict function

A: *

*Open your R console and run/load all the libraries that are required.

*Use source() to now run your R scripts

Test.R file has the following code
#This file has no library declarations
c <- ggplot(mtcars, aes(factor(cyl)))
c <- c + geom_bar()
print(c)

Now I run from my console like this
> library(ggplot2)
> source("<Path>/test.R")

Output:

Edit: To pass Params along with source() command
You can do this by overriding commandArgs()
New test.R file code:
c <- ggplot(mtcars, aes(factor(cyl)))
c <- c + geom_bar()
print(c)
print(commandArgs())

Now from console:
> commandArgs <- function() c('a','b')
> source("<Path>/test.R")
[1] "a" "b"
(Along with the graph)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restriction on domain when using socket.io? I am using socket.io to establish 2 way communication between the server and the client.
Everything works fine, but it seems that if random person copies all my client side codes (including establishing connection) and make a separate new webpage, it seems that users who are connected to that new page can still communicate with my server. Which I think it can be used in bad ways.
Is there anyway that I can check where the socket messages are coming from? 'where' means the domain that user has used to send message to the server?
Is there a way to restrict or control list of domains to send and receive socket message?

A: I am answering my own question.
According to socket.io wiki, it is possible to specify 'origins' or clients' domain.

origins defaults to *:*
The origins that are allowed to connect to the Socket.IO server.


text:
Q: Send information to main class My program has network functionality so to avoid messagebox spam in case of network problem i display errors from a collection.
internal class VM_Main
    {   ...
        public ObservableCollection<string> Errors { get; } = new observableCollection<string>();
        ...
    }

This collection is displayed in my XAML window.
public MainWindow()
    {    ...
        vm_Main = new VM_Main();
        dgdErrors.ItemsSource = vm_Main.Errors;
        ...
    }

This is OK.
My problem is when i use objects from other classes in variables. How can I send information to the errors collection to report an error?
internal class VM_Main
{   ...
    public ObservableCollection<string> Errors { get; } = new observableCollection<string>();
    ...
    List <Customers> allCustomers = new List<Customer>()
}

public class Customer
{   ...
    public string Name { get; set; }
    ...
    public Customer()
    {
        try{ // Network work }
        catch (Exception ex) {   ????? Errors.Add(ex.Message) ????  }
    }
    ...
}

"Errors doesn't exist in the current context."
Of course, but how am I supposed to do ?

A: Here is a fully OOP implementation design using singleton pattern (lazy approach). Further info Singleton pattern
1- Define the singleton class.
using System;
using System.Collections.ObjectModel;

namespace ErrorToConsole
{
    public sealed class Singleton
    {
        private ObservableCollection<String> Errors = new ObservableCollection<string>();

        private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

        public static Singleton Instance { get { return lazy.Value; } }

        private Singleton()
        {

        }

        public string AddError(string strError)
        {
            Errors.Add(strError);
            return strError;
        }

        public ObservableCollection<string> GetErrors()
        {
            return Errors;
        }

    }

}

2- Calling the singleton class to add and retrieve errors.
using System;

namespace ErrorToConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var singleton = Singleton.Instance;

            try
            {

                //Adding some errors here
                singleton.AddError("aaa");
                singleton.AddError("bbb");
                singleton.AddError("ccc");
                singleton.AddError("ddd");

                throw new Exception("Throwing exception");
            }

            catch (Exception ex)
            {
                //Adding exception message here
                singleton.AddError(ex.Message);

                //this is just to show that all the errors where added to the singleton collection.
                foreach (var val in singleton.GetErrors())
                {
                    Console.WriteLine(val);
                }
                Console.ReadLine();
            }
        }
    }
}

A: You make an interface:
public interface IErrorReport
{
    void AddError(string message);
}

You then let your main window implement that interface:
internal class VM_Main : IErrorReport
{
    ...
    public void AddError(string)
    {
        Errors.Add(string);
    }
}

In your Customer constructor you add a parameter:
public Customer(IErrorReport report)
{
    try
    {
        // Network work
    }
    catch (Exception ex)
    {
        Report.AddError(ex.Message);
    }
}

Then all you need is to pass a reference to the main window when you create the customer:
internal class VM_Main
{   ...
    public ObservableCollection<string> Errors { get; } = new observableCollection<string>();
    ...
    List <Customers> allCustomers = new List<Customer>(this);
}


text:
Q: How to hide the process of data writing into worksheet in c# I am using worksheet object to write data to excel sheet.Creaating columns and writing my data from datatable to sheet.this is showing the data writing process on screen and then generating Pivot table.I dont want to display the writing process.Plz help me to hide that process.

A: I'm sure whether you are talking about Microsoft.Office.Interop.Excel.Application (but "worksheet object" suggests that), then it would be:
Microsoft.Office.Interop.Excel.Application excelApp = null;
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;

A: You can use Application.ScreenUpdating = false, but this stops all screen updates. If the window is dragged during this time, a ghost image will be left behind. You must be very careful with this -- you have to set it back to true.
A better option would be to activate a worksheet other than the one(s) being updated. You can show Sheet 1, for example, while updating Sheet 2, Sheet 3, and so on.


text:
Q: BoneCP - Add ShutdownHook to shutdown the connection pool I'm using the BoneCP connection pool library and basically everything works fine. But there is one thing that I am not 100 percent sure about:
I have a connection pool that is open during the whole runtime.
Do I have to add a shutdown hook that closes the connection pool? Or could I just do nothing when the application exists?
The shutdown hook would look like this:
Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public final void run() {
        connectionPool.shutdown(); //shutdown the connection pool
    }
});

But it gives me a not very good looking log message that mixes up with my logging system because the shutdown hooks run cuncurrent. So I would not want to call this. Do I have to?


text:
Q: Как определить высоту клика? Есть див с определенной высотой. Есть ли возможность на jQuery определить, на какой высоте в диве был сделан клик?
A: $("someSelector").on('click', function( e ) {
  var clickHeight = e.offsetY;
  // +, как можно было догадаться
  var clickWidth = e.offsetX;
})

A: $("someSelector").click(function(e){
var h=e.currentTarget.offsetHeight + e.currentTarget.offsetTop-e.clientY;
alert(h);
});

здесь offsetHeight - высота блока, offsetTop - верхняя точка блока на странице, clientY - координаты мышки на момент клика.


text:
Q: Getting an Aggregate Value from a Many-to-Many Field inside a Serializer We have an API endpoint that generates a response. However, we would like to aggregate some of the data and add an additional field to the serializer.
  {
        "id": 61,
        "not_owned_value": # This is what we're trying to get (Aggregate best_buy_price from not_owned_inventory PlayerProfiles)
        "not_owned_inventory": [ # PlayerProfile objects
            "29666196ed6900f07fc4f4af4738bffe",
            "0ff73ca20cd787c5b817aff62e7890da",
            "99d4eaef9991695d7ad94b83ad5c5223",
            "6fcabe9f9c8a95980923530e7d7353a7",
            "80b34c84a6e5ed25df112c11de676adc",
            "0a4c5b96474f0584519d1abc4364d5a2",
            "9ed1f55ac4f3b402b1d08b26870c34a6",
         ]
  }

Here is the models.py
class PlayerProfile(models.Model):
    card_id = models.CharField(max_length=120, unique=True, primary_key=True)
    name = models.CharField(max_length=120, null=True)

class PlayerListing(models.Model):
    player_profile = models.OneToOneField(
        PlayerProfile,
        on_delete=models.CASCADE,
        null=True)
    best_buy_price = models.IntegerField(null=True)

class InventoryLiveCollection(models.Model):
    not_owned_inventory = models.ManyToManyField(PlayerProfile, related_name="not_owned_inventory")

Here is the serializer.py
class InventoryLiveCollectionSerializer(serializers.ModelSerializer):
    not_owned_inventory = PlayerProfileAndListingForNesting(read_only=True, many=True)

    class Meta:
        model = InventoryLiveCollection
        fields = (
            'id',
            'date',
            'not_owned_value', # Trying to get this
            'not_owned_inventory',
        )

How can I aggregate the best_buy_price of the player_profile objects that belong to a specific InventoryLiveCollection__not_owned_inventory?

A: You can try this.
 from django.db.models import Sum

 not_owned_value = serializers.SerializerMethodField()

 def get_not_owned_value(self, obj):
     value = obj.not_owned_inventory.all().aggregate(total=Sum('playerlisting__best_buy_price'))
     return value['total']


text:
Q: Drag JSTree Node into an external div I am using Jquery jsTree where i load my data into jstree with json. Below is my code to populate my jsTree
  $.ajax({
           async: true,
           type: "POST",
           url: "MasterPageDataService.asmx/GetAllSites",
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           success: function (jsonData) {
           $("#divSitesTree").jstree({
                'core': {
                'data': jsonData
                 },
                "plugins": ['dnd', "themes", "json_data", "ui"]
               });},
           });

I get the data populated perfectly.
Now i want to drag a node and drop it onto div element. I have made my div drop able to serve the purpose like this
  $(".droppable").droppable({
            drop: function (event, ui) {
                alert('dropped');
                // here i want the id of dropped node
            }
        });

I don't want to move the node from tree to anywhere , i just want to get the id of the node being dragged and dropped into div. But my problem is that m not even getting the drop event getting fired. e.g i don't get any alert at all.
I have googled the different solutions and tried this so far.

But what it does, it simply appends the node(icon+text) in my div. But that is not what i want. I just want to get the Id of the node inside an event where i can perform further operation based over the id of the node.
How do I accomplish this task with jsTree? Please Help.

A: Luckily I have found the solution. Below is the script to get the id of the    node being dragged and the id of the target where the node is being dropped
 $(document)
   .on('dnd_stop.vakata', function (e, data) {
    var t = $(data.event.target);
      if (!t.closest('.jstree').length) {
        if (t.closest('.drop').length) {
           alert(data.data.origin.get_node(data.element).id);//node id
           alert(data.event.target.id) //target id
      }}});});


text:
Q: What is the best way to insert a snippet of code in spacemacs I have a function which basically inserts function () {}; but properly indented and the cursor positioned appropriately:
(defun insert-function-js ()
  (insert "function () {
};"))

(define-key evil-normal-state-map (kbd "SPC dg")
  (lambda ()
    (interactive)
    (call-interactively 'evil-insert)
    (insert-function-js)
    (evil-force-normal-state)
    (call-interactively 'evil-visual-char)
    (call-interactively 'evil-previous-line)
    (call-interactively 'indent-region)
    (call-interactively 'evil-open-below)))

This seems very cumbersome. I would guess there is a better way to write this functionality! One that  better leverages elisp's capabilities.
Thanks for the help!

A: As an answer to your first question, you could use yasnippet and a snippet based on the function-snippet provided with Spacemacs [1] to do this for you:
# -*- mode: snippet; require-final-newline: nil -*-
# name: my-function
# key: fn
# --
function () {
         $0
};

If you put this snippet in a new file in ~/.emacs.d/private/snippets/, you can expand it by typing fn and then pressing M-/ [2]. If yas-indent-line is set to 'auto (which it is by default in Spacemacs), then the function should be indented correctly, and the $0 in the snippet puts your cursor in that position after insertion.
The yasnippet-expansion forms a single undo-action.

[1] The default function-snippet can be found in ~/.emacs.d/elpa/yasnippet-<VERSION>/snippets/js-mode
[2] using the default Spacemacs bindings, this calls hippie-expand, which in turn calls yas-expand.


text:
Q: Trying to understand the statement of Nakayama's lemma for coherent modules in Mumford' red book Here is the statement of a version of Nakayama's lemma in Mumford's red book. Let $X$ be a noetherian scheme, $F$ a coherent $O_X$-module and $x \in X$. If $U$ is a neighbourhood of $x$ and $a_1, \ldots a_n \in \Gamma(U,F)$ have the property:
the images $\overline{a_1}, ..., \overline{a_1}$ generate $F_x \otimes_{O_{X,x}} k(x)$
then there exists a neighbourhood $U_0 \subset U$ of $x$ such that $a_1, ..., a_n $ generate $F |_{U_0}$.
There are two things I don't understand in this statement, which I haven't been able to deduce looking at the proof.
-"$\overline{a_1}, ..., \overline{a_1}$ generate $F_x \otimes_{O_{X,x}} k(x)$" over $O_{X,x}$ or $k(x)$?
-what does it mean by $a_1, ..., a_n $ generate $F |_{U_0}$?
thank you.

A: The map $O_{X,x} \to k(x)$ is surjective, so generated over $O_{X,x}$ or $k(x)$ is the same thing.
For the second question, it means that the images of $a_1, ..., a_n $ in $F_y$ are generators for this $O_{X,y}$-module for each $y\in U_0$.


text:
Q: Why are there space in if commands in python language ? Are there needed ? Is it a convention? I'm a beginner : sorry the answer is found nowhere on the web.
Why people in python typically write :
if __name__ == "__main__":
    main()

instead of (without space) :
if __name__=="__main__":
    main()

Is there a better convention to use ?

A: This is a convention is part of the Python Enhancement Proposals, namely, PEP8.
You can check for mor information in:

*

*https://www.python.org/dev/peps/pep-0008/

*https://pep8.org/


text:
Q: Count online user, daily and total visitors with firebase real-time database ( react typescript ) I'm trying to create an app which can count online, daily and total visitors to web page with real-time database of firebase but don't know how to start, any suggestion is appreciate, thank you

A: You can use Google Analytics for firebase Which has a real-time dashboard for total visitor and much more interesting details, and it is free
If you are going to report it manually in the database it will be really expensive to do it for every single request and hackers can exploit it to incur your firebase billing.
Related Links:
https://firebase.google.com/products/analytics
https://firebase.google.com/pricing#realtime-database


text:
Q: How does a motherboard convert the input voltage to the 12V of the PCI? Has it a DC/DC converter inside? Are the 12V guaranteed to be 12.0V sharp?

A: No, it won't be exactly 12V, because PCIe specs allow for 8% tolerance in the 12V supply at any load current that is within limits of the specs.
As computer ATX supplies have requirement of 5% tolerance for 12V output, it is highly unlikely that a motherboard would provide a separate DC-DC converter for the PCIe slots. The PCIe slots would simply be powered directly from the 12V coming from ATX power supply.


text:
Q: Combining name columns LIKE another I have 2 name columns from table1.name and table2.name. I have names in table1.name like "Alex Testing" and in table2.name it's "Alexander Testing". I have the table do some other tricky stuff but it doesn't recognize that Alex and Alexander are the same people so it will not include the name in my report. I was wondering if there was a way I could get these 2 to inner join by first name or even by last name, like if another table had the same first name but different last name?
I've tried:
SELECT
   Table1.[Name], Table2.[Time],
   CASE WHEN myvariables here then 0 ELSE 1 END AS columnB
INTO NewTable
FROM
   Table1 INNER JOIN Table2
      ON Table1.[Name] LIKE ('%' + Table2.Name + '%')

however it still does not work, it wont recognize Alex's name.
I've also tried:
SELECT
   Table1.[Name], Table2.[Time],
   CASE WHEN myvariables here THEN 0 ELSE 1 END as columnB
INTO NewTable
FROM
   Table1 INNER JOIN Table2
      ON Table1.[Name] LIKE CONCAT('%',"Table2.Name", '%')

A: Try:
 SELECT
       Table1.[Name], Table2.[Time],
       CASE WHEN myvariables here then 0 ELSE 1 END AS columnB
    INTO NewTable
    FROM
       Table1 INNER JOIN Table2
          ON  SUBSTRING(Table1.[Name], CHARINDEX(' ', Table1.[Name]) + 1, LEN(Table1.[Name])) = SUBSTRING(Table2.[Name], CHARINDEX(' ', Table2.[Name]) + 1, LEN(Table2.[Name]))

If you have large volume tables you may want to use subqueries and select directly lastnames, and then use a join on lastnames.


text:
Q: unable to iterate over json object using jquery I am new to AJAX/JQuery/JSON, I am using Struts 2 to get a JSON object using AJAX, I can see the object returned but I am unable to iterate over it. The returned object is a list that has just one object(may contain more objects), also every object contains a list of some other object.
This is how the js file looks like:
$.getJSON('GetAllSaleItemsAction', {
        customerName : debtorSelection
    }, function(jsonResponse){
        //alert(jsonResponse);

        //populate table
        var trHtml = '';
        //$("tr:has(td)").remove();
        jsonResponse = jsonResponse.saleItemsList;

        var responseString = JSON.stringify(jsonResponse);
        console.log(responseString);

        $.each(jsonResponse, function(i, item) {
            var saleEntries = $.parseJSON(item.singleSaleEntries);

            var saleEntriesString = JSON.stringify(saleEntries);
            console.log(saleEntriesString);

            var sseString = '';
            $.each(saleEntries, function(n, sse){
                sseString += sse.item + ' ' + sse.quantity + ' x ' + sse.price + ' = ' + sse.amount;
            });

            trHtml+= '
' + item.date + '	' + sseString + '	' + item.saleAmount  + '	' + item.interest  + '	' + item.totalAmount + '
';
        });
        if(trHtml != ''){
            $('#saleRecordTable').append(trHtml);
        }
    });

Here the first console.log is executed but not the second console.log as javascript inside the each-function is not executed:
[{"customerName":"Tester","date":"2015-02-16T17:36:19","debtorId":1,"interest":0,"saleAmount":14000,"saleId":3,"singleSaleEntries":[{"amount":9000,"item":"DAP_50KG","price":900,"quantity":10,"saleEntry":null,"singleSaleId":4},{"amount":5000,"item":"UREA_50KG","price":500,"quantity":10,"saleEntry":null,"singleSaleId":5}],"totalAmount":14000}]

Please guide me.

A: The issue was with var saleEntries = $.parseJSON(item.singleSaleEntries);
After changing this statement to var saleEntries = item.singleSaleEntries;
everything works fine, the problem was that the debug point was set to next statement and because of error in this line, the control was never reaching there.


text:
Q: Secondary DHCP server won't start on Centos 6.2 I'm trying to create a backup DHCP server.  Server times are in sync.  Primary server starts fine.  Secondary server won't start.  Error from /var/log/messages is:
Sep 15 14:47:45 stream dhcpd: Copyright 2004-2010 Internet Systems Consortium.
Sep 15 14:47:45 stream dhcpd: All rights reserved.
Sep 15 14:47:45 stream dhcpd: For info, please visit https://www.isc.org/software/dhcp/
Sep 15 14:47:45 stream dhcpd: /etc/dhcp/dhcpd.conf line 25: invalid statement in peer declaration
Sep 15 14:47:45 stream dhcpd: #011max-response-default
Sep 15 14:47:45 stream dhcpd:          ^
Sep 15 14:47:45 stream dhcpd: /etc/dhcp/dhcpd.conf line 41: failover peer dhcp-failover: not found
Sep 15 14:47:45 stream dhcpd:     failover peer "dhcp-failover"
Sep 15 14:47:45 stream dhcpd:                    ^
Sep 15 14:47:45 stream dhcpd: /etc/dhcp/dhcpd.conf line 49: failover peer dhcp-failover: not found
Sep 15 14:47:45 stream dhcpd:     failover peer "dhcp-failover"
Sep 15 14:47:45 stream dhcpd:                    ^
Sep 15 14:47:45 stream dhcpd: WARNING: Host declarations are global.  They are not limited to the scope you declared them in.
Sep 15 14:47:45 stream dhcpd: /etc/dhcp/dhcpd.conf line 70: failover peer dhcp-failover: not found
Sep 15 14:47:45 stream dhcpd:     failover peer "dhcp-failover"
Sep 15 14:47:45 stream dhcpd:                    ^
Sep 15 14:47:45 stream dhcpd: /etc/dhcp/dhcpd.conf line 78: failover peer dhcp-failover: not found
Sep 15 14:47:45 stream dhcpd:     failover peer "dhcp-failover"
Sep 15 14:47:45 stream dhcpd:                    ^
Sep 15 14:47:45 stream dhcpd: Configuration file errors encountered -- exiting
Sep 15 14:47:45 stream dhcpd:
Sep 15 14:47:45 stream dhcpd: This version of ISC DHCP is based on the release available
Sep 15 14:47:45 stream dhcpd: on ftp.isc.org.  Features have been added and other changes
Sep 15 14:47:45 stream dhcpd: have been made to the base software release in order to make
Sep 15 14:47:45 stream dhcpd: it work better with this distribution.
Sep 15 14:47:45 stream dhcpd:
Sep 15 14:47:45 stream dhcpd: Please report for this software via the CentOS Bugs Database:
Sep 15 14:47:45 stream dhcpd:     http://bugs.centos.org/
Sep 15 14:47:45 stream dhcpd:
Sep 15 14:47:45 stream dhcpd: exiting.

Config file contents:
# DHCP Server Configuration file.
#   see /usr/share/doc/dhcp*/dhcpd.conf.sample
#   see 'man 5 dhcpd.conf'
#

option domain-name "eng.foo.com";
option domain-name-servers ns0.eng.foo.com, ns1.eng.foo.com;
option ntp-servers ntp.eng.foo.com;
#option time-servers ntp.eng.foo.com;

default-lease-time 3600;
max-lease-time 7200;

authoritative;

log-facility local7;

failover peer "dhcp-failover" {
        secondary;
        address 10.0.1.70;
        port 647;
        peer address 10.0.1.11;
        peer port 647;
        max-response-default 30;
        max-unacked-updates 10;
        load balance max seconds 3;
}

#
# Management subnet
#
subnet 10.0.0.0 netmask 255.255.255.0 {
  option subnet-mask 255.255.255.0;
  option broadcast-address 10.0.0.255;
  option routers 10.0.0.1;
  option domain-search "eng.foo.com", "foo.com";

  # Unknown clients get this pool
  pool {
    failover peer "dhcp-failover";
    max-lease-time 300;
    range 10.0.0.240 10.0.0.249;
    allow unknown-clients;
  }

  # Known clients get this pool
  pool {
    failover peer "dhcp-failover";
    max-lease-time 28800;
    range 10.0.0.150 10.0.0.199;
    deny unknown-clients;
  }

  include "/etc/dhcp/dhcpd.conf-engmgmt";

}

#
# Data subnet
#
subnet 10.0.1.0 netmask 255.255.255.0 {
  option subnet-mask 255.255.255.0;
  option broadcast-address 10.0.1.255;
  option routers 10.0.1.1;
  option domain-search "eng.foo.com", "foo.com";

  # Unknown clients get this pool
  pool {
    failover peer "dhcp-failover";
    max-lease-time 300;
    range 10.0.1.240 10.0.1.249;
    allow unknown-clients;
  }

  # Known clients get this pool
  pool {
    failover peer "dhcp-failover";
    max-lease-time 28800;
    range 10.0.1.150 10.0.1.199;
    deny unknown-clients;
  }

  # For centos network installs
  if substring (option vendor-class-identifier, 0, 8) = "anaconda" {
    filename "/autohome/distro/ks/";
    next-server eng-data.eng.foo.com;
  }

  # For PXE network installs
  if substring (option vendor-class-identifier, 0, 9) = "PXEClient" {
    filename "pxelinux.0";
    next-server eng-data.eng.foo.com;
  }

  # For KVM PXE network installs
  if substring (option vendor-class-identifier, 0, 9) = "Etherboot" {
    filename "pxelinux.0";
    next-server eng-data.eng.foo.com;
  }

  include "/etc/dhcp/dhcpd.conf-engdata";

}

A: This answer is specific to those who are experiencing this same type of error after copying this example configuration from ISC's website. There is a subtle error caused by the encoding of the dashes on that page.
In vim, if you place your cursor over the first dash of max-response-default and press ga while in command mode, you will see a unicode value of 8208. Now if you delete the dash, replace it with your own, and check again, it will have an ASCII/unicode value of 45.
Replace all the Unicode-dashes inside your failover configuration with ASCII-dashes and the configuration should successfully load.

A: There sems to be a configuration problem around line 25, quite possibly max-response-default. Shouldn't that be max-response-delay?

A: Most obvious culprit seems to be the secondaries inability to communicate with the primary over the specified port.

*

*Can you ping the primary from the secondary?

*Is iptables configured to allow communication on port 647?

Beyond that, according to ISC the DHCP service doesn't do a lot of checking to ensure the config is correct, and will fail in odd ways if something isn't set right. So if its not a network issue then it must be the config. For example, one omission in your config file seems to be disabling bootp on segments that have failover enabled. You'd be better off making a master dhcp config used on both servers and then primary/secondary peer declarations that includes the master config, it would preclude the possibility of the configs not matching up.
For quick overview of the main requirements for setting up a dhcp failover scenario see: http://webcache.googleusercontent.com/search?q=cache:tbaPhUwlbdsJ:consultancy.edvoncken.net/index.php/HOWTO_Configure_DHCP_failover+&cd=1&hl=en&ct=clnk&gl=us
Edit: Ah woops, missed the line gertvdijk points out below. It seems it should be max-response-delay, not max-response-default.


text:
Q: Proving that distinct edge atoms of a graph are vertex-disjoint. The Question
In Godsil and Royle's Algebraic Graph Theory, they prove that any two distinct edge atoms of a graph $X$ are vertex-disjoint, making the following argument, where $A$ and $B$ are such edge atoms:

So we may assume that $A\cup B$ is a proper subset of $V(X)$. Now, the previous lemma yields
$$|\partial(A\cup B)| + |\partial(A\cap B)|\le 2\kappa_1(X),$$
and, since $A\cup B\ne V(X)$ and $A\cap B\ne\emptyset$, this implies that
$$|\partial(A\cup B)| = |\partial(A\cap B)| = \kappa_1(X).$$

I don't understand why the second assertion is true, nor why it follows from  $A\cup B\ne V(X)$ and $A\cap B\ne\emptyset$.
Background
I'm unsure how common their notation/definitions are, so I've included some below.

*

*We let $\kappa_1(X)$ denote edge-connectivity;

*For $S\subseteq V(X)$, we define $\partial S$ to be $\{xy\in E(X):x\in S, y\notin S\}$. That is, it is the set of edges with one end in $S$ and one end not in $S$;

*An edge atom of $X$ is a subset $S\subseteq V(X)$ such that $|\partial S|=\kappa_1(X)$, and $|S|$ is minimal.

*The lemma referenced states that $|\partial(A\cup B)|+|\partial(A\cap B)|\le |\partial A| + |\partial B|$ for $A,B\subseteq V(X)$.

A: The second assertion follows from the first because, by Menger's Theorem, for any nonempty $S \subsetneq V(X)$, $|\partial S| \geq \kappa_1(X)$.
Here's another way to think about it. If either of $\partial (A \cup B)$ or $\partial (A \cap B)$ had size different from $\kappa_1 (X)$, then one of the two would have to be less than $\kappa_1 (X)$, which contradicts $\kappa_1 (X)$ being the edge connectivity, since neither $A \cap B$ or $A \cup B$ is $V(X)$ or empty.

A: In Godsill & Royle's book :
"So we may assume that A∪B is a proper subset of V(X)."
This is proved immediately above the statement on page 38. So A∪B≠V(X) since it is a proper subset (and is also not the empty set since neither A nor B are empty).
"A∩B≠∅" should be stated in the proof as an assumption because the object of corollary 3.3.2 is to prove A and B are disjoint.
The final line:
" |∂(A∪B)|=|∂(A∩B)|=κ1(X)."
follows the expression from the previous lemma because neither |∂(A∪B)| nor |∂(A∩B)| can be less than κ1 (and both are non-zero from the previous working) since the edge connectivity is κ1 so the only option is  that both equal κ1
So the corollary is proved by contradiction.


text:
Q: Countdown Timer not working in Magento 2 I tried to display the Festive offer banner in Top of the page, but it's not working. For these, I tried below code.
countdownTimer.phtml file
  <?php /** @var $block ABCSolutions\OfferBanner\Block\OfferBanner */?>

<?php $from_Date = $this->helper('ABCSolutions\OfferBanner\Helper\Data')->getFromDate(); ?>
<?php $to_Date = $this->helper('ABCSolutions\OfferBanner\Helper\Data')->getToDate(); ?>
<?php $title = $this->helper('ABCSolutions\OfferBanner\Helper\Data')->getTitle(); ?>
<?php $Days = $this->helper('ABCSolutions\OfferBanner\Helper\Data')->getDays(); ?>

        <?php echo $title; ?>
        Days
        Hours
        Minutes
        Seconds

<?php
$f = $from_Date . " 00:00:00";
$fromDate = date("M/d/y h:i:s A", strtotime($f));
$t = $to_Date . " 23:59:59";
$toDate = date("M/d/y h:i:s A", strtotime($t));

$jScriptFunction = "";

echo $jScriptFunction;
?>

After printing these it looks like below image.

Well formatted in Javascript. but it's not working.
Suggest us where I went wrong?
Results are showing below image.

It's showing above image, but not countdown the time. I mean timer is not running.


text:
Q: Intuition for Smooth Manifolds Consider the graphs of the functions $f_1(x) = |x|$, and $f_2(x) = x$ under the subspace topology of $\mathbb{R}^2$.
Both of these graphs are smooth manifolds, just pick coordinate charts to be $(x, f_i(x)) \leftrightarrow x$.
Moreover, they are diffeomorphic via the map $(x, f_1(x)) \rightarrow (x, f_2(x))$.
This seems to clash with my intuition. For example, the graph of $f_1$ has a corner, so it "shouldn't" be smooth, much less diffeomorphic to $f_2$, which is just a straight line.
Can someone explain what's going on here?
In light of these examples, how should I visualize smooth manifolds and diffeomorphisms?

A: You could do the same thing with the set $T=\{(x,g(x))\}$ for any continuous $g$.  The reason this seems non-intuitive is that you haven't used the smooth structure of $\mathbb{R}^2$ at all in defining the smooth structure of $T$; you've just taken the smooth structure on $\mathbb{R}$ and "transported" it onto $T$.  Another way to say it: The intuitive non-smoothness of $T$ (for, say, $g(x)=|x|$) comes from looking at the way that $T$ is sitting in $\mathbb{R}^2$.
Abstractly, it's very much the same as the following situation, which may be clearer. The integers $\mathbb{Z}$ form a group under addition.  The set $T = \{17,59\} \subset \mathbb{Z}$ is not a subgroup of $\mathbb{Z}$ under addition.  It is true that $T$ can be made into group by transporting the structure of a 2-element group onto $T$, but you don't expect that this group will have anything to do with $\mathbb{Z}$ as a group anymore since you didn't use the group structure on $\mathbb{Z}$ to define the group structure on $T$.

A: Your intuition is broken because the inclusion of the graph of $f_1$ (with the smooth structure you describe) into $\mathbb{R}^2$ isn't smooth. The graph of $f_1$, as a subset of $\mathbb{R}^2$ with its usual smooth structure, is not a smooth manifold for exactly the intuitive reason.


text:
Q: TS doesn't see default props in React function component My code
interface ButtonProps {
  onClick?: () => void
}

const Button: FC<ButtonProps> = ({ onClick }) => {
  const wrapClick = () => {
    onClick() // TS2722: Cannot invoke an object which is possibly 'undefined'.
  }

  return <button onClick={wrapClick}>button</button>
}

Button.defaultProps = {
  onClick: () => {},
}

In this case, everything works
const Button: FC<ButtonProps> = ({ onClick }) => {
  const wrapClick = () => {
    onClick && onClick()
  }

  return <button onClick={wrapClick}>button</button>
}

and in this
const Button: FC<ButtonProps> = ({ onClick = () => {} }) => {
  const wrapClick = () => {
    onClick()
  }

  return <button onClick={wrapClick}>button</button>
}

Is there a way to use default props to solve this problem ? Since I have large components with a lot of properties.

A: The onClick property in the props object is marked as optional by using a question mark, so we can't directly invoke the function.
To solve the error, use the optional chaining (?.) operator when calling the function.
import { FC } from "react";

interface ButtonProps {
  onClick?: () => void;
}

const Button: FC<ButtonProps> = ({ onClick }) => {
  const wrapClick = () => {
    onClick?.();
  };

  return <button onClick={wrapClick}>button</button>;
};

Button.defaultProps = {
  onClick: () => {}
};

export default Button;

Code Sandbox : DEMO

A: Use the Non-null assertion operator (postfix !) to let TypeScript know your default onClick(): void is not null/undefined (which it thinks it is because of IButtonProps.onClick: () => void | undefined, which is used by Button (FC<IButtonProps>, FC<T>.defaultProps is of type T & { children?: Node } if I remember correctly)).
interface IButtonProps {
  onClick?: () => void;  // No event args?
}

const Button: FC<IButtonProps> = (props) => {
  const {
    onClick = Button.defaultProps.onClick!,
  } = props;

  const wrapClick = (/* No event args? */) => {
    onClick();
  };

  return <button onClick={wrapClick}>button</button>;
};

Button.defaultProps = {
  onClick: () => {},
};


text:
Q: Macbook Air will not connect to Wifi even though other Macs work fine with same Wifi I'm having some issues and I feel as though I have literally tried everything. I am at a complete loss on what to do.
Situation:
I had multiple Mac computers including this one for a while. All working fine with router.
Then I replaced my router because it was getting slow and dated, the new one I got worked fine at first, but then started to drop connection every other day and even sometimes every day. I replaced the replacement router, then my macbook air had ridiculously slow connection speed. It would take google 5-10 minutes to load. But my iMac computer worked fine. I didn't change anything, nor do anything different to either computer except get this new router. The router even managed to corrupt my time machine. So I called up the ISP and they worked me through the issues, so now everything is working fine EXCEPT my Macbook Air.
I have tried starting from scratch with the router, with the Time Machine, I have rebooted all devices. But the internet remains the same. It's good on my iMac, my phone, my TV, but not the macbook air. I wanted to call Apple, but it costs $60 to talk to a someone which is not affordable for me. I am really frustrated with this.
I went through all the changes with my Airport Utility. I even reset my Macbook Air to factory default settings. Still I have the same issue.
What can I do to troubleshoot this problem?

A: Have you tried going to the Network preference pane in System Preferences, clicking on Advanced, then Wi-Fi, and deleting all the Preferred Networks? I seem to recall having the same problem a few years ago, and deleting the networks fixed it.

A: Deleting all networks in Mac, System Preferences, Network fixed the identical problem for me.

A: The following are all suggestions I've tried from different sources:

*

*moving preferred network to top

*clearing all WiFi passwords (including those from the keychain) and reconnecting only to the preferred network

*disabling bluetooth

*forcefully removing network configuration files

*adding a fixed DNS server
What actually helped was to reset the SMC and reset the PRAM. Now the Mac connects instantly to the WiFi. And it fixed the ping delays as well I had (ping times were up to 4 times higher than from another Macbook).

A: With seven years of experience in the technical industry I troubleshooted this error for a very long time and was very frustrated! The only thing that fixed it was this

*

*Login to your router and reset all settings

*connect to your router with no wifi security

*once you confirm that the wireless connected fine, then

*setup your wifi router with WPA and reconfigure your passphrase/wifi password again

*re-connect to your secured wifi

After doing this I now have internet. I hope this helps. I know this solution makes no sense, but I tried everything on the internet and nothing else did it.


text:
Q: Code Security for .net other than using obfuscation Is there any way to prevent the code from being dissembled other then obfuscation.

A: There is no way to prevent your code from being disassembled!
The runtime needs to be able to execute the instructions that you have created with your code otherwise your software won't run. If the computer that the software is running on can read the instructions then a user who has control of that computer can get access to the instructions and by way of decompilation recreate a version of the code - it may not look exactly like the original code but will compile to an equivalent program.
There are however several approaches for hiding the instructions and the structure of your code from prying eyes - one of them being obfuscation. Ultimately they are only speed bumps as a competent hacker could copy your instructions out from the machine's memory as the software is executed...


text:
Q: Fastlane Tests Failing with libXCTestSwiftSupport.dylib requires version 1.0.0 or later, but libswiftCore.dylib provides version 0.0.0 Any help would be greatly appreciated. I've been fighting for a few weeks on and off to get my unit tests running as part of my build pipeline with Jenkins and Fastlane.
When I run them through Fastlane locally, everything is fine. I run fastlane unit_tests and everything compiles, simulator launches, and tests run.
When I run them on the build pipeline, after the simulator launches and the first test should execute, I see an error.
I don't understand what is missing here. I would have thought the development build that fastlane creates with the scan option would be enough include what is necessary for running the tests. The lane definition is:
desc "Run Unit Tests"
lane :unit_tests do
    scan(
        scheme: "myAppTests",
        devices: ["iPhone 11"]
    )
end

The error I'm receiving is:
[16:20:32]: ▸ Linking myAppTests
[16:20:33]: ▸ Copying provisioning.plist
[16:20:33]: ▸ Copying GoogleService-Info.plist
[16:20:33]: ▸ Compiling SynchronizationViewController.xib
[16:20:33]: ▸ Processing Info.plist
[16:20:33]: ▸ Running script '[CP] Embed Pods Frameworks'
[16:20:33]: Running Tests: ▸ Touching myAppTests.xctest (in target 'myAppTests' from project 'myApp')
[16:20:33]: ▸ Build Succeeded
[16:20:34]: ▸ Linking MYAPP
[16:20:34]: ▸ Running script 'SwiftLint'
[16:20:35]: ▸ Linking myAppTests
[16:20:35]: ▸ 2020-02-20 16:20:35.801 xcodebuild[42315:2308394]  IDETestOperationsObserverDebug: Writing diagnostic log for test session to:
[16:20:35]: ▸ /Users/Jenkins.SVN/Library/Developer/Xcode/DerivedData/MYAPP-gjylxkutiwwowsdxuadsovduecib/Logs/Test/Run-myAppTests-2020.02.20_16-19-59-+0000.xcresult/Staging/2_Test/Diagnostics/myAppTests-35F843CE-22FC-427A-B385-A9EF0F61E4B1/myAppTests-D3C6D752-F909-4965-BAB5-26194C7BB5D0/Session-myAppTests-2020-02-20_162035-s3sDH8.log
[16:20:35]: ▸ 2020-02-20 16:20:35.801 xcodebuild[42315:2306273] [MT] IDETestOperationsObserverDebug: (5D31D2AA-6061-40B3-943F-858AE0181E65) Beginning test session myAppTests-5D31D2AA-6061-40B3-943F-858AE0181E65 at 2020-02-20 16:20:35.801 with Xcode 11C505 on target <DVTiPhoneSimulator: 0x7fa3f1a8e220> {
[16:20:35]: ▸       SimDevice: iPhone 11 (703948B3-684D-4E84-AFD4-34FFB522203D, iOS 13.3, Shutdown)
[16:20:35]: ▸ } (13.3 (17C45))
[16:20:37]: ▸ 2020-02-20 16:20:37.747 xcodebuild[42315:2306273] [MT] IDETestOperationsObserverDebug: (5D31D2AA-6061-40B3-943F-858AE0181E65) Finished requesting crash reports. Continuing with testing.
[16:20:40]: ▸ 2020-02-20 16:20:40.907 xcodebuild[42315:2306273] [MT] IDETestOperationsObserverDebug: 5.110 elapsed -- Testing started completed.
[16:20:40]: ▸ 2020-02-20 16:20:40.907 xcodebuild[42315:2306273] [MT] IDETestOperationsObserverDebug: 0.000 sec, +0.000 sec -- start
[16:20:40]: ▸ 2020-02-20 16:20:40.907 xcodebuild[42315:2306273] [MT] IDETestOperationsObserverDebug: 5.110 sec, +5.110 sec -- end
[16:20:41]: ▸ Testing failed:
[16:20:41]: ▸   myAppTests:
[16:20:41]: ▸       xctest (43228) encountered an error (Failed to load the test bundle. (Underlying error: The bundle "myAppTests" couldn't be loaded because it is damaged or missing necessary resources. The bundle is damaged or missing necessary resources. dlopen_preflight(/Users/Jenkins.SVN/Library/Developer/Xcode/DerivedData/MYAPP-gjylxkutiwwowsdxuadsovduecib/Build/Products/Debug-iphonesimulator/myAppTests.xctest/myAppTests): Library not loaded: @rpath/libswiftCore.dylib
[16:20:41]: ▸   Referenced from: /Applications/Xcode-11.3.1.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/lib/libXCTestSwiftSupport.dylib
[16:20:41]: ▸   Reason: Incompatible library version: libXCTestSwiftSupport.dylib requires version 1.0.0 or later, but libswiftCore.dylib provides version 0.0.0))
[16:20:41]: ▸ ** TEST FAILED **

Podfile:
# define a global platform for your project
platform :ios, '13.2'

# ignore all warnings from all pods
inhibit_all_warnings!

def default_pods
  pod 'MyAwesomePod'
end

target 'myApp' do
  use_frameworks!
  default_pods
end

target 'myAppTests' do
  inherit! :search_paths
  use_frameworks!
  default_pods
end

target 'myAppUITests' do
  inherit! :search_paths
  use_frameworks!
  default_pods
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['CLANG_ENABLE_CODE_COVERAGE'] = 'NO'
      config.build_settings['SWIFT_EXEC'] = '$(SRCROOT)/SWIFT_EXEC-no-coverage'
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '10.0'
      config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf-with-dsym'
      config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = 'YES'
    end
  end
end

Always Embed Swift Standard Libraries has been set to YES across the test target and the application target.

A: This seemed to be caused by using an incorrect version of the swift toolchain. Along with the latest toolchain installed via Xcode, we also had 4.2.4 and 5.1.2 installed. I believe the app was being published with 5.1.2, which satisfied the built target.
I resolved it by removing the unused swift toolchains. I could have also probably specified the toolchain to use in fastlane's scan and gym commands.


text:
Q: how to find element with its name in jquery How to find checkbox with name checkbox[]
$("#a_tag_id").parent('tr.section_quick_edit').find('input:checkbox[name=checkbox[]]').val();

A: $("#a_tag_id").parent('tr.section_quick_edit').find("input:checkbox[name='checkbox[]']").val();

Notice the extra quotes.
Bob

A: I think what you are looking for is
$("#a_tag_id").parent('tr.section_quick_edit').find('input:checkbox[name=checkbox[]]').attr('name');


text:
Q: What all things the startapp done in Django? When we use :
django-admin startapp app_one

whats the things the django done for us?
Because I want to know whether we can delete the app directory directly.

I am not sure whether all the app related data are deleted (Because I don't know the all the django-admin startapp things).

A: you can read in the docs startapp

Creates a Django app directory structure for the given app name in the current directory or the given destination.

and also you can look on the templates
so if you never use the code, you can feel free to delete it.


text:
Q: HTML Canvas: update globalAlpha property I'm trying to update the globalAlpha of a canvas element after its painted. The canvas contains an image, and two texts. I show the code at the bottom.
I want to change the globalAlpha property from 0.6 to 1 afterwards. How can i do this most elegantly with performance in mind?
        var ctx = canvasElement.getContext("2d");
        ctx.globalAlpha = 0.6;

        //background gradient
        var gradient = ctx.createLinearGradient(0, 0, 0, options["height"]);
        gradient.addColorStop(0, options["colorStop0"]);
        gradient.addColorStop(1, options["colorStop1"]);
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, options["width"], options["height"]);

        //program
        ctx.font = options.programText["font"];
        ctx.fillStyle = options.programText["color"];
        ctx.fillText(prog.title, options.programText["x"], options.programText["y"]);

        //channel number
        ctx.font = options.channelNumber["font"];
        ctx.fillStyle = options.channelNumber["color"];
        ctx.fillText(item_index + 1, options.channelNumber["x"], options.channelNumber["y"]);

        //channel logo
        var channelLogo = new Image();
        channelLogo.onload = function () {
            var clX = options.channelLogo["x"];
            var clY = options.channelLogo["y"];
            ctx.drawImage(channelLogo, clX, clY, channelLogo.width, channelLogo.height);
        };
        channelLogo.src = this.getChannelLogo(channel);

A: You cannot update the globalAlpha of a shape after it is painted.
More to the point, you cannot "update" anything after it is painted. There is no updating in Canvas. You must instead redraw the thing(s) with the attributes changed.
So in your case you will simply want to clear your canvas and redraw everything with globalAlpha set back to 1.

A: You can update canvas after painting by just doing pixel manipulation.
Using the getImageData & putImageData method of context of canvas.
But there is not any method like "changeAlpha(x,y,width,height,alphaValue)" of context of canvas.
Same kind of problem i am also facing in my app.

A: If your alpha is going up to 100%, you can probably just repaint it without redrawing the whole scene (overwriting what was there previously).  The only risk is some antialiasing artifacts if you're doing curves.
If you alpha is going down, however, you have to do as Simon says - repaint the whole scene.


text:
Q: Should we ignore misc.xml and .iml in Pycharm .idea/ folder? My google search give me this thread which leads us to Pycharm official site here saying that we should KEEP all except workspace.xml, tasks.xml
Though I see that files misc.xml and <projectFolderName>.iml also contains local/physical path pointing to a sub folder in my user home in Ubuntu.
So I confused and brought it up here - should we git ignore those two files too?

A: You need to use your own judgment based on circumstances.
misc.xml contains local environment specific information, for example project interpreter name, like this
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (myvirtenvname)" project-jdk-type="Python SDK" />

Unless there is a strict shared virtual environments naming policy in the team, I would recommend ignoring it. I myself prefer no-one dictating me how I name my virtual environments on my dev machine. I might have many other projects and potential conflicting names.
The .iml and .name are addressed by the other answer. I do not like the fact though that the project interpreter name is here also bundled with all the project settings in the projecname.iml xml file. I wish it was more granular and in a separate file in the .idea folder so I can decide to share it or not. It is environment dependent and what interpreter to use might be better left to be decided by the individual. If jetbrains are reading this please consider.

A: 1) <projectFolderName>.iml - By default Idea editors produce <projectFolderName>.iml files which are place specific. To deal with it:
Rename a project:

Now you have two files in .idea dir: .name and YOUR_RENAMED_PROJECT.iml both of them are directory and platform independent and could be added to git.
2) misc.xml - TL;DR; ignore it
For PyCharm  misc.xml may contain platform specific paths and even could ship more sensitive data.
3) Finally one has to rename a toolchain and use the same name across the team:

The best way to share your project files among a group of developers is to rename your project interpreter into something not dependent on your file system paths (e.g. "Python 2.7" or "My Project: Python 2.7 virtualenv") and then use that name consistently for all the developers.
You can rename your interpreters in "File | Settings | Project | Project Interpreter |  | More... | Edit".

Source from PyCharm tracker


text:
Q: Cannot find crontab entry for a scheduled shell script My predecessor set up a basic installation of CrunchBang in a VirtualBox VM - The Windows host runs a scheduled task to boot the VM, then CrunchBang runs a shell script some 10-15 minutes later to rsync some files to a local drive. Windows is booting the VM just fine, and CrunchBang's script appears to be functioning correctly and running according to its schedule. But I would like to tweak CrunchBang's schedule a bit, and I can't figure out how/where the script is being scheduled. crontab -l returns no crontab for xxx for both the default user and root, and crontab -e likewise results in empty files.
Is there another location where the schedule entry could be saved? An alternative to cron that may be running it instead?
Thanks.

A: Check under /etc/cron.d/ for scripts.

A: If it's starting a consistent 15 minutes after boot, it might be a startup script that has a built-in delay/sleep before running.  You might also look at /etc/rc.local, or in /etc/init.d, in case it's not cron.


text:
Q: all invariant subspaces Let $A$ be a linear operator such that $A \begin{bmatrix}x\\y\\z \end{bmatrix}=\begin {bmatrix}x+y\\y-x\\0 \end{bmatrix}$. Find all invariant subspaces of $A$.
I know how to find subspaces of dimensions $0$, $1$ and $3$, but how can I find all subspaces of dimension $2$ (I know that $\mathrm{Im}A$ is a subspace and $\mathrm{dim}\; \mathrm{Im} A=2$ )

A: Hint: a two-dimensional subspace must intersect any other two-dimensional subspace nontrivially. Apply this to $A$ and the space generated by two basis vectors.

A: A two-dimensional subspace is the null space of a nonzero linear functional.  The subspace is invariant if and only if the linear functional is an eigenvector of $A^*$.


text:
Q: Gem install error (sass compass) When I want to install sass and compass, I get this message. Can someone help me?
Microsoft Windows [version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Tous droits réservés.

C:\Users\Bk>gem install sass

ERROR:  While executing gem (Encoding::UndefinedConversionError)
    U+2019 to CP850 in conversion from UTF-16LE to UTF-8 to CP850

A: Open up a command prompt and type:
chcp 1252

Then run the installer again:
gem install sass
Unfortunately there's a known issue in some versions of Ruby regarding this.  See here

A: Here is what worked for me:
modified line 70 of registry.rb (in your ruby installation folder).
Change this line:
LOCALE = Encoding.find(Encoding.locale_charmap)

to this one:
LOCALE = Encoding::UTF_8

A: to resolve this problem you have to install an old version of ruby and delete the latest versions on your pc i think there is an error on the latest version,look for this version and download it  1.8.7


text:
Q: Getting the component selector 'epimss-personnel'Given the following...
@Component(
    {
      selector: 'epimss-personnel',
      templateUrl: './personnel.component.html',
      styleUrls: [ './personnel.component.css' ]
    } )
export class PersonnelComponent implements OnInit {
  personnel: IPersonnel = new Personnel();

  constructor( ) {
  }

  ngOnInit() {
  }
}

... how can I get the selector string 'epimss-personnel' in PersonnelComponent programmatically?
EDIT 1
When I add try the suggestion below I get the following:
compiler.es5.js:14582 Uncaught Error: Unexpected value 'AppRoutingModule' imported by the module 'AppModule'. Please add a @NgModule annotation.
    at syntaxError (compiler.es5.js:1503) [<root>]
    at :4200/vendor.bundle.js:117324:44 [<root>]
    at Array.forEach (<anonymous>) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (compiler.es5.js:13953) [<root>]
    at JitCompiler._loadModules (compiler.es5.js:25134) [<root>]
    at JitCompiler._compileModuleAndComponents (compiler.es5.js:25093) [<root>]
    at JitCompiler.compileModuleAsync (compiler.es5.js:25055) [<root>]
    at PlatformRef_._bootstrapModuleWithZone (core.es5.js:4786) [<root>]
    at PlatformRef_.bootstrapModule (core.es5.js:4772) [<root>]
    at Object.426 (main.ts:47) [<root>]
    at __webpack_require__ (bootstrap d227106…:52) [<root>]
    at Object.1132 (main.bundle.js:7) [<root>]
    at __webpack_require__ (bootstrap d227106…:52) [<root>]
    at webpackJsonpCallback (bootstrap d227106…:23) [<root>]

... the UI is not displayed either.

A: If you're not inside the component, you won't be able to use ElementRef, and the Reflect solution won't work with AOT.  Fortunately, there's an alternative when you know the target is a component:
const components = [ PersonnelComponent ];
/*
  ...
  Anything that can be injected into
*/
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  // For each component
  components.forEach(element => {
    // Get its resolved factory
    const factory = this.componentFactoryResolver.resolveComponentFactory(element);

    console.log('Factory:', factory);
    console.log('Selector:', factory.selector);
  });
}

A: constructor(elRef:ElementRef) {
  console.log(elRef.nativeElement.tagName);
}

A: With Angular 14, you have an option to get the metadata by reflectComponentType(Targetcomponent)
const mirror = reflectComponentType(StandaloneComponent)!;

expect(mirror.selector).toBe('standalone-component');

expect(mirror.type).toBe(StandaloneComponent);

expect(mirror.isStandalone).toEqual(true);

Source: https://netbasal.com/a-new-method-for-retrieving-metadata-about-angular-components-b494351dd130


text:
Q: Strange behavior of rails with link_to Issues:  when I clink on a link_to action, the app calls another controller causing a missing id error.
I have a menu that display buttons for creating new objects that convert into navigation links when the object is created by the user.
the behavior is using the object.exists? helper.

<%= link_to "Personal information", edit_user_registration_path %>

<%= link_to "Settings", notification_settings_path %>

<%= link_to "Payments", payment_method_path %>

   <% if Prequalification.exists? %>

<%= link_to "Edit prequalification",edit_prequalification_path(@user, @prequalification) %>

   <% end %>
   <% if Company.exists? %>

<%= link_to "Edit company data",edit_company_path(@user, @company) %>

   <% end %>

   <% if !Company.exists? %>
    Add a company
   <% end %>
   <% if !Prequalification.exists? %>
    Prequalify for loan or rents
    <% end %>

Thanks to this post:
https://stackoverflow.com/questions/13186722/what-is-the-difference-between-using-exists-and-present-in-ruby

I can create a new company and have access to the edit link, but when I try to create subsequently a prequalification file, then I get:
ActionController::UrlGenerationError in Prequalifications#new

No route matches {:action=>"edit", :controller=>"companies", :format=>nil, :id=>nil, :locale=>:en}, possible unmatched constraints: [:id]

The controllers for companies and prequalifications are separated.  I do not understand why the error happens.  Especially as if I delete the reference link_to the company model before actioning the prequalification then it seems to work as intented.
my routes are very straightforward:
resources :prequalifications
resources :companies

my controller is also quite simple:
def new
 @company = Company.new
end

def create
 @company = current_user.build_company(company_params
end

def edit
 @user = current_user
 @company = Company.find_by(id: [params[:id], params[:company_id]])
end

The controller for the other model look very similar.
Where could that behavior could come from ?

A: You want to test @company.exists? and @prequalification.exists instead of Company.exists and Prequalification.exists, otherwise your are testing if the Class exists (which is always the case) and not if the actual company and prequalifcation exist.
This is why you are getting an error on the edit company link, since Company.exists is true even when @company = nil, it tries to build a link for a nil object


text:
Q: PHPUnit - assertion failed but I want to continue testing ->assertTrue(false);
->assertTrue(true);

First assertion was failed and execution was stopped. But I want to continue the further snippet of code.
Is there possible in PHPUnit

A: that defeats the point of a unit test. you might want to break it into a few more test methods instead of having a monolithic test method.
Here is some pseudo-code, as a bad example.
MyBadTestMethod()
{
   someResult = MyMethod();
   assertIsCorrect(someResult);
   myResult2 = MyMethod2(someResult);
   assertIsCorrect(myResult2);
}

MyMethod2 and myResult2 will fail.
Here is a better example.
MyTestMethod1()
{
   someResult = MyMethod();
   assertIsCorrect(someResult);
}
MyTestMethod2()
{
   myResult2 = MyMethod2(someCorrectResult);
   assertIsCorrect(myResult2);
}

A: I'm late to the party, but I recommend using a configuration file for the test suites to achieve this easily.
You can create phpunit.xml file from where you are running the phpunit test. Hence phpunit will run the needed tests listed there.

PHPUnit 3.7.38 by Sebastian Bergmann.
Configuration read from /path/phpunit.xml

In that file you can specify that you don't want to stop on failure.
<phpunit bootstrap="vendor/autoload.php" stopOnFailure="false">
  <testsuites>
    <testsuite name="Test">
      <file>tests/ClassTest.php</file>
    </testsuite>
  </testsuites>
</phpunit>

Hope this helps.

A: The other answerers are correct - you really should separate out your assertions into separate tests, if you want to be able to do this. However, assuming you have a legitimate reason for wanting to do this... there is a way.
Phpunit assertion failures are actually exceptions, which means you can catch and throw them yourself. For example, try this test:
public function testDemo()
{
    $failures = [];
    try {
        $this->assertTrue(false);
    } catch(PHPUnit_Framework_ExpectationFailedException $e) {
        $failures[] = $e->getMessage();
    }
    try {
        $this->assertTrue(false);
    } catch(PHPUnit_Framework_ExpectationFailedException $e) {
        $failures[] = $e->getMessage();
    }
    if(!empty($failures))
    {
        throw new PHPUnit_Framework_ExpectationFailedException (
            count($failures)." assertions failed:\n\t".implode("\n\t", $failures)
        );
    }
}

As you can see, it tries two assertions, both of which fail, but it waits until the end to throw all of the failure output messages as a single exception.

A: You could just store up the failures for the end, say with a
$passing = true;
if (! false) { $passing = false; }
if (! true) { $passing = false; }
$this->assertTrue($passing);

but I highly discourage this form of testing. I have written tests like this, and they exponentially get out of hand, and worse, you start to get weird failures for hard-to-find reasons.
Additionally, smarter people than me agree, tests should not have any conditionals (if/else, try/catch), because each conditional adds significant complexity to the test. If a conditional is needed, perhaps both the test and the SUT, or System Under Test, should be looked at very carefully, for ways to make it simpler.
A much better way would be to change it to be two tests, and if they share a significant portion of the setup, then move those two tests into a new test class, with the shared setup performed in the Setup() method.


text:
Q: hide uncited bibitems in the bibliography I have a shared bibliography.tex file with a set of bibitems:
\begin{thebibliography}{99}
\bibitem{A} A
\bibitem{B} B
\end{thebibliography}

I have a series of tex files that include this file, each of which produces an output pdf. They are compiled with pdflatex. Their content:
\begin{document}
%...
\cite{A} %A or B is cited here
\end{document}

I'd like to exclude from the bibliography of the output pdf files those bibitems (in the example A or B) that were not cited in the specific source tex file.
Is there an easy way that does not require going through the pain of bash scripting or compiling with bibtex?

A: I had to chances but to use bibtex plus cite package and adding the references like this:
\nocite{}
\bibliographystyle{plain}
\bibliography{../../common/bibliography}

The nocite command discards all the bibliography not explicitly cited. No need for biblatex package metioned around and no use of theblibliography command which did not discard uncited stuff.


text:
Q: Need regular expression to remove one and only one s Need a regex to remove letter s
I want regex to remove s only if it is the last characte and only one instance is found
So word "boys" will become "boy"
and word "process" will remain the same since there are more than one "s" and should be case insensitive.
Please help
Thanks

Works only on a single word.
I tried this code below and does not work  in a sentence.
string str = "The boys in the student's class didn't understand  the process.";
str = System.Text.RegularExpressions.Regex.Replace(str, "([^s])s$", "$1");
Console.WriteLine(str);
Console.ReadLine();

A: I believe what you need is a zero-width negative look-behind assertion;  the Perl-style regular expression would be something like this:
$line =~ s/(?<!s)s\b//gi;

Which means "remove a single 's' character if it is the last character of a word (i.e. a whitespace character is the next character) and if the preceding character is not an 's', all case insensitive."
use strict;
use warnings;

my $line = "The boys in the student's class didn't understand the process.";

$line =~ s/(?<!s)s\b//gi;

print "$line\n";

yields:  "The boy in the student' class didn't understand the process."

A: This should work:
/([^s])s$/\1/

This in say C# is:
Regex.Replace(str, "([^s])s$", "$1")


text:
Q: Repeated measurements with missing values The data is measured in two biological replicates with two technical replicates, each.

*

*Each variable might be detected only in one or more replicates, in the others it is considered missing at random.

*Each variable is measured with zero (missing) to dozens of data points in each experiment.

*Each measurement comes with its own estimated variance

The question for each variable (which was detected at least once): Does its mean deviate from 0? We can assume that the data is normally distributed.
What would be an appropriate test to apply to this data with randomness on many levels?

A: Let me propose an answer - I am happy to hear constructive criticism:

*

*Merge measurements of technical replicates (taking the union)

*

*I assume that the between-replicates variation is about the same as the within-replicate variation (for any variable).

*Apply statistical tests of difference of mean for the combined data for each biological replicate and each variable. Apply multiplicity correction.

*For variables detected in both biological replicate sets:

*

*if direction of change is in both direction:

*

*calculate combined p-values using Fisher's method

*else, set p-value to 1

*For variables seen in only one biological replicate set, use its original p-value (just penalize but don't remove them)

Do I miss any assumptions such that you would deem this procedure unsound?


text:
Q: Why Are My Hinge Joints Being Pushed Away?(Unity 2D) Hey guys so I'm making a 2d Stickman ragdoll and I'm trying to get one of the arms to look at the mouse and the arm looks at the mouse but when the mouse gets to close the arms start glitching uncontrollably and the joints are now off set. How can I fix?
upper arm
lower arm
When I move the mouse, this happens
public GameObject LeftArm;
public GameObject LeftElbow;
 Vector2 mousepos = Input.mousePosition;
    mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = new Vector2(mousepos.x - LeftArm.transform.position.x, mousepos.y - LeftArm.transform.position.y);
    LeftArm.transform.right = direction;
    LeftElbow.transform.right = direction;


text:
Q: Unable to see application console logs in azure log stream, filesystem , blob storage We are using spring boot app deployed in azure app service , App is using Logback by default and logging in console. Even though i have configured the storageV2 account to retreive the logs in blob storage , enabled to store logs in filesystem still i am not able to see the logs at any place. Is there any further configuration needed to be added in java app to get the logs ? Though i am getting web server related logs (url getting hit) but
app logs are not showing up.


text:
Q: android - What is the 1:n relationship between view and viewModel I know view and viewmodel are 1:n.
However, in most examples there was one viewmodel per activity.
ex) mainActivity - mainViewModel , userListActivity - userListViewModel
Shouldn't it be like below if it's a 1:n relationship??
ex) mainActivity - viewModel , userListActivity - viewModel
What does 1:n mean?
Does it mean n activities in one viewmodel?
Does it mean n xml files in one viewmodel?

A: Yes the common use-case is 1:1. But theoretically you could have multiple ViewModels serving a view, so that's why the 1:n relation.
In practice this could be useful if you'd like to share a ViewModel between two views for example, or when you have a shared Flow ViewModel
So basically in that flow every View could communicate with two ViewModels: the shared one and one specific for that view:

*

*Imagine a SignUp flow, with two screens user credentials (email, password, etc...) and another one with some preferences (like membership, notification, address or other app specific settings)

*In this case the SharedFlowViewModel could hold all the user information, and at the last screen the Submit will send the request. All other screens with the individual ViewModels would just handle the individual screen logic: form validation, input enabling/desabling, etc...


text:
Q: Cocoa/objectiveC UI design issue I'm trying to build an app on MacOSX - ObjectiveC. I don't not find a good ressource to understand how I can create the view I need and the steps to made it.
I'm looking mostly to create 3 sections.
Section 1: Few buttons and one image
Section 2: TreeView to have a File browser/finder
Section 3: Progress bar to show the disk usage.
I'm creating an app to read android device and manage file transfer. Such as Android File Transfer.

A: First and foremost you need to look over the tutorial that Apple provides on creating your first Mac app.
Second you can use NSOutlineView to create your treeview, here's a tutorial on this.
Then you need NSProgressIndicator for your progress bar, here's a tutorial.
I also suggest you look over at ray's tutorials to get started with XCode and all the interface builder tools.


text:
Q: Does Xamarin offer a native number picker that I can use with Xamarin.Forms? I have used the standard picker which comes up with a box on the screen and allows me to select from a list.
But is there a native Xamarin picker that can be used just to pick numbers and populate a binder number?  Something like I see on applications where a telephone keypad type thing displays with the numbers 1,2,3,4,5,6,7,8,9,0 and a backspace. This seems like a common kind of control for when a user wants to enter a number or dollar amount.
I look in the sample apps but could not find any example of this. If there is not one then is the only way to implement a series of numbers in a list ?

A:
The kind of control I am interested in is one that when I click on an input field it opens up a box on the bottom of the screen with a number pad

Use an Entry with the Keyboard property set to Numeric
<Entry Keyboard="Numeric" />


text:
Q: Is there a proper algorithm for detecting the background color of a figure? For college, we have been given an assignment where, given an image, we have to identify the "figures", their color, and the amount of "pixel-groups" inside them. Let me explain:

The image above has one figure (in the image there can be multiple figures, but let us forget about that for now).

*

*The background color of the canvas is the pixel at 0,0 (in this case, yellow)

*The border color of the figure is black (it can be any color other than the canvas' background color).

*The figure's background color is white (it can also be the same as the canvas' background color).

*A figure can only have one background color.

*There are two pixel groups in the figure. One is a pool of blue pixels, and the other is a pool of red with some green inside. As you can see, it doesn't matter the color of the pixel group's pixels (it is just different than the figure's background color). What matters is the fact that they're in contact (even diagonally). So despite having two different colors, such group is considered as just one anyway.

*As you can see, the border can be as irregular as you wish. It only has, however, one color.

*It is known that a pixel group will not touch the border.

*I was told that a pixel group's colors can be any except the figure's background color. I assume that then it can be the same as the figure's border color (black).

We have been given a class capable of taking images and converting them to a matrix (each element being an integer representing the color of the pixel).
And that's it. I'm doing it with Java.
WHAT HAVE I DONE SO FAR

*

*Iterate through each pixel in the matrix

*If I find a pixel that is different from the background color, I will assume it belongs to the border of the figure. I will call this pixel initialPixel from now on.

*Note that the initialPixel in the image I provided is that black pixel in the top-left corner of the figure. I made a sharp cut there purposefully to illustrate it.

*My mission now is to find the background color of the figure (in this case white).

But I'm having quite a great deal of trouble to find such background color (white). This is the closest method I did, which worked for some cases - but not with this image:

*

*Since I know the color of the border, I could find the first different color that is to the south of the initialPixel. Did sound like a good idea - it did work sometimes, but it would not work with the image provided: it will return yellow in this case, since initialPixel is quite away from the figure's contents.

Assuming I did find the figure's background color (white), my next task would be to realize that there exist two pixel groups within the figure. This one seems easier:

*

*Since I now know the figure's background color (white), I can try iterating through each pixel within the figure and, if I find one that does not belong to the border and is not part of the figure's background, I can already tell there is one pixel group. I can begin a recursive function to find all pixels related to such group and "flag" them so that in the future iterations I can completely ignore such pixels.

WHAT I NEED
Yes, my problem is about how to find the figure's background color (keep in mind it can be the same as the whole image's background color - for now it is yellow, but it can be white as well) based on what I described before.
I don't need any code - I'm just having trouble thinking a proper algorithm for such. The fact that the border can have such weird irregular lines is killing me.
Or even better: have I been doing it wrong all along? Maybe I shouldn't have focused so much on that initialPixel at all. Maybe a different kind of initial method would have worked? Are there any documents/examples about topics like this? I realize there is a lot of research on "computer vision" and such, but I can't find much about this particular problem.
SOME CODE
My function to retrieve a vector with all the figures:
*Note: Figure is just a class that contains some values like the background color and the number of elements.
public Figure[] getFiguresFromImage(Image image) {
    Figure[] tempFigures = new Figure[100];
    int numberOfFigures = 0;
    matrixOfImage = image.getMatrix();
    int imageBackgroundColor = matrixOfImage[0][0];
    int pixel = 0;

    for (int y = 0; y < matrixOfImage.length; ++y) {
        for (int x = 0; x < matrixOfImage[0].length; ++x) {
            pixel = matrixOfImage[y][x];
            if (!exploredPixels[y][x]) {
                // This pixel has not been evaluated yet
                if (pixel != imageBackgroundColor ) {
                    // This pixel is different than the background color
                    // Since it is a new pixel, I assume it is the initial pixel of a new figure
                    // Get the figure based on the initial pixel found
                    tempFigures[numberOfFigures] = retrieveFigure(y,x);
                    ++numberOfFigures;
                }
            }
        }
    }

    // ** Do some work here after getting my figures **

    return null;
}

Then, clearly, the function retrieveFigure(y,x) is what I am being unable to do.
Notes:

*

*For learning purposes, I should not be using any external libraries.

A: A good way to solve this problem is to treat the image as a graph, where there is one node ('component' in this answer) for each color filled area.
Here is one way to implement this approach:

*

*Mark all pixels as unvisited.

*For each pixel, if the pixel is unvisited, perform the flood fill algorithm on it. During the flood fill mark each connected pixel as visited.
Now you should have a list of solid color areas in your image (or 'components'), so you just have to figure out how they are connected to each other:

*Find the component that has pixels adjacent to the background color component - this is your figure border. Note that you can find the background color component by finding the component with the 0,0 pixel.

*Now find the components with pixels adjacent to the newly found 'figure border' component. There will be two such components - pick the one that isn't the background (ie that doesn't have the 0,0 pixel). This is your figure background.

*To find the pixel groups, simply count the number of components with pixels adjacent to the figure background component (ignoring of course the figure border component)
Advantages of this approach:

*

*runs in O(# pixels) time.

*easy to understand and implement.

*doesn't assume the background color and figure background color are different.

To make sure you understand how iterating through the components and their neighbors might work, here's an example pseudocode implementation for step 5:
List<Component> allComponents; // created in step 2
Component background; // found in step 3 (this is the component with the 0,0 pixel)
Component figureBorder; // found in step 4
List<Component> pixelGroups = new List<Component>(); // list of pixel groups

for each Component c in allComponents:
    if c == background:
        continue;
    for each Pixel pixel in c.pixelList:
        for each Pixel neighbor in pixel.neighbors:
            if neighbor.getComponent() == figureBorder:
                c.isPixelGroup = true;

int numPixelGroups = 0;
for each Component c in allComponents:
    if (c.isPixelGroup)
        numPixelGroups++;

A: Try this code :
import java.util.Scanner;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;

class Analyzer{
    private int pixdata[][];
    private int rgbdata[][];
    private BufferedImage image;
    int background_color;
    int border_color;
    int imagebg_color;
    private void populateRGB(){
        rgbdata = new int[image.getWidth()][image.getHeight()];
        for(int i = 0; i < image.getWidth(); i++){
            for(int j = 0; j < image.getHeight(); j++){
                rgbdata[i][j] = image.getRGB(i, j);
            }
        }
        int howmanydone = 0;
        int prevcolor,newcolor;
        prevcolor = rgbdata[0][0];

        /*
        for(int i = 0; i < image.getWidth(); i++){
           for(int j = 0; j < image.getHeight(); j++){
              System.out.print(rgbdata[i][j]);
           }
           System.out.println("");
        }*/
        for(int i = 0; i < image.getWidth(); i++){
            for(int j = 0; j < image.getHeight(); j++){
                newcolor = rgbdata[i][j];
                if((howmanydone == 0) && (newcolor != prevcolor)){
                    background_color = prevcolor;
                    border_color = newcolor;
                    prevcolor = newcolor;
                    howmanydone = 1;
                }
                if((newcolor != prevcolor) && (howmanydone == 1)){
                    imagebg_color = newcolor;
                }
            }
        }
    }
    public Analyzer(){ background_color = 0; border_color = 0; imagebg_color = 0;}
    public int background(){ return background_color; }
    public int border() { return border_color;}
    public int imagebg() {return imagebg_color;}
    public int analyze(String filename,String what) throws IOException{
        image = ImageIO.read(new File(filename));
        pixdata = new int[image.getHeight()][image.getWidth()];
        populateRGB();
        if(what.equals("background"))return background();
        if(what.equals("border"))return border();
        if(what.equals("image-background"))return imagebg();
        else return 0;
    }
}
public class ImageAnalyze{
    public static void main(String[] args){
        Analyzer an = new Analyzer();
        String imageName;

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter image name:");
        imageName = scan.nextLine();
        try{
        int a = an.analyze(imageName,"border");//"border","image-background","background" will get you different colors
        System.out.printf("Color bg: %x",a);

        }catch(Exception e){
           System.out.println(e.getMessage());
        }
    }
}

the color returned is ARGB format. You will need to extract R,G and B from it.
There is a bug in this code. Working on implementation using Finite State machine. in the first state you're inside the image, hence 0,0 is the background color, then when there is a change, the change is the border color, then the third state is when inside the image + inside the border and the color changes.


text:
Q: Is there a way to get all registered meta fields in a post types? I'm creating a dynamic form that user can select a post type and show all meta fields registered on that selected post type, is there a way to get all meta fields in a post types?

A: You'll use custom sql query to get these meta keys/fields.
With this function you'll be able to exclude/include the empty meta_keys and the hidden ones.
function get_all_meta_keys($post_type = 'post', $exclude_empty = false,
    $exclude_hidden = false){
    global $wpdb;
    $query = "
        SELECT DISTINCT($wpdb->postmeta.meta_key)
        FROM $wpdb->posts
        LEFT JOIN $wpdb->postmeta
        ON $wpdb->posts.ID = $wpdb->postmeta.post_id
        WHERE $wpdb->posts.post_type = '%s'
    ";
    if($exclude_empty)
        $query .= " AND $wpdb->postmeta.meta_key != ''";
    if($exclude_hidden)
        $query .= " AND $wpdb->postmeta.meta_key NOT RegExp '(^[_0-9].+$)' ";

    $meta_keys = $wpdb->get_col($wpdb->prepare($query, $post_type));

    return $meta_keys;
}


text:
Q: Techniques to measure application performance I maintain an application which, during the course of two years, has constantly required new hardware to be even usable, due to the amount of new users / new data inserted. However, justifying the investiment is sometimes very hard to do.
I started to wonder - how can I establish the maximum number of users a web application currently suports?
I thought of using JMeter scripts but they can get really nasty to implement when having to simulate file transfers and decison trees. What do you guys use?

A: You can use this performance algorithm:
http://i.msdn.microsoft.com/cc500561.fig02_L(en-us).gif

R Response time. The total time from the user requesting a page
(by clicking a link, and so on) to when the full page is rendered on
the user's computer. Typically measured in seconds. Payload   Total
bytes sent to the browser, including markup and all resources (such as
CSS, JS, and image files).
Bandwidth Rate of transfer to and from the browser. This may be
asymmetrical and might represent multiple speeds if a given page is
generated from multiple sources. Usually, it is averaged together to
create a single bandwidth expressed in bytes per second.
AppTurns  The number of resource files a given page needs. These
resource files will include CSS, JS, images, and any other files
retrieved by the browser in the process of rendering the page. In the
equation, the HTML page is accounted for separately by adding in
round-trip time (RTT) before the AppTurns expression.
RTT   The time it takes to round-trip, regardless of bytes
transferred. Every request pays a minimum of one RTT for the page
itself. Typically measured in milliseconds.
Concurrent Requests   Number
of simultaneous requests a browser will make for resource files. By
default, Internet Explorer performs two concurrent requests. This
setting can be adjusted but rarely is.
Cs    Compute time on the server. This is the time it takes for code
to run, retrieve data from the database, and compose the response to
be sent to the browser. Measured in milliseconds.
Cc    Compute time on the client. This is the time it takes for a
browser to actually render the HTML on the screen, execute JavaScript,
implement CSS rules, and so on.

For more details:
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

A: We use HP's LoadRunner.  But it's not cheap, and you still have to create scripts, test cases.


text:
Q: Find the 2nd td of every table and push it into array I have this HTML table:

var code = [];
var pname = [];
var description = [];
var size = [];
var printarea = [];
var colours = [];
var comments = [];

var cell = document.getElementsByTagName("td");

for (var i = 1; i < cell.length; i += 14) {
  var c = cell[i].innerHTML;
  code.push(c);
}

console.log(code);
console.log(pname);

// code = VISA01, UMBR21
// name = Sun Viscor Clip, Compact Umbrella With Steel Shaft
// description = Stylish Sun Visor Clip which holds your sunglasses in place and within reachProtects your sunglasses away from being scratchedEasy to use, sturdy, clips well and does not block your vision while driving SIZE 8 (w) x 3 (h) cm,  Compact umbrella with steel shaft for a strong wind-resistant performancePush button and auto-open for a convenient and effortless openingDurable Logo printed on front and back panels; comes in several colors; can combine colors upon request

  <title>Table to Array</title>

          CODE
          VISA01

          NAME
          Sun Visor Clip

          DESCRIPTION
          Stylish Sun Visor Clip which holds your sunglasses in place and within reachProtects your sunglasses away from being scratchedEasy to use, sturdy, clips well and does not block your vision while driving

          SIZE
          8 (w) x 3 (h) cm

          PRINT AREA
          4 (w) x 1 (h) cm

          COLOURS
          navy, black, red, royal, white, orange, green

          COMMENTS

          CODE
          UMBR21

          NAME
          Compact Umbrella With Steel Shaft

          DESCRIPTION
          Compact umbrella with steel shaft for a strong wind-resistant performancePush button and auto-open for a convenient and effortless openingDurable Logo printed on front and back panels; comes in several colors; can combine colors upon request

          SIZE
          53 (h) cm

          PRINT AREA
          20 (w) x 20 (h) cm

          COLOURS
          black, white, red, blue.please call for more colour options

          COMMENTS

I want to extract the values from every second  and put it in to an array.
For example:
code array contains VISA01, UMBR21
name array contains Sun Viscor Clip, Compact Umbrella With Steel Shaft
Can anyone please help me out?

A: Give it a try

          CODE
          VISA01

          NAME
          Sun Visor Clip

          DESCRIPTION
          Stylish Sun Visor Clip which holds your sunglasses in place and within reachProtects your sunglasses away from being scratchedEasy to use, sturdy, clips well and does not block your vision while driving

          SIZE
          8 (w) x 3 (h) cm

          PRINT AREA
          4 (w) x 1 (h) cm

          COLOURS
          navy, black, red, royal, white, orange, green

          COMMENTS

          CODE
          UMBR21

          NAME
          Compact Umbrella With Steel Shaft

          DESCRIPTION
          Compact umbrella with steel shaft for a strong wind-resistant performancePush button and auto-open for a convenient and effortless openingDurable Logo printed on front and back panels; comes in several colors; can combine colors upon request

          SIZE
          53 (h) cm

          PRINT AREA
          20 (w) x 20 (h) cm

          COLOURS
          black, white, red, blue.please call for more colour options

          COMMENTS

A: You can use reduce to group the selection and ES6 destructuring assignment to access the required vars:
const {
  code,
  name: _name,
  description,
  size,
  printarea,
  colours,
  comments
} = [...document.querySelectorAll('.ty-table')].reduce((all, table) => {

  [...table.getElementsByTagName('tr')].forEach(tr => {

    const [key, val] = [...tr.getElementsByTagName('td')].map(n => n.innerText.trim());

    const keyLc = key.replace(/ /g,'').toLowerCase();

    if (!all.hasOwnProperty(keyLc)) {
      all[keyLc] = [];
    }

    all[keyLc].push(val);

  })

  return all;

}, {});;

console.log(code);
console.log(_name);
console.log(description);
console.log(size);
console.log(printarea);
console.log(colours);
console.log(comments);

Note that we have _name alias for name, as name is a reserved JS keyword and accessors with name convert all data structures to string:
var name = [1,2,3];
typeof name === 'string' // true

General practice is not to use name as your variable name.

A: I solved it by doing this.. not the best/elegant solution but at least it works.
var code = [];
var pname = [];
var description = [];
var size = [];
var printarea = [];
var colours = [];
var comments = [];

var cell = document.getElementsByTagName("td");

for (var i = 1; i < cell.length; i+=14) {
    var c = cell[i].innerHTML;
    code.push(c);
}

for (var i = 3; i < cell.length; i+=14) {
    var n = cell[i].innerHTML;
    pname.push(n);
}

for (var i = 5; i < cell.length; i+=14) {
    var d = cell[i].innerHTML;
    description.push(d);
}

for (var i = 7; i < cell.length; i+=14) {
    var s = cell[i].innerHTML;
    size.push(s);
}

for (var i = 9; i < cell.length; i+=14) {
    var p = cell[i].innerHTML;
    printarea.push(p);
}

for (var i = 11; i < cell.length; i+=14) {
    var col = cell[i].innerHTML;
    colours.push(col);
}

for (var i = 13; i < cell.length; i+=14) {
    var com = cell[i].innerHTML;
    comments.push(com);
}

console.log(code);
console.log(pname);
console.log(description);
console.log(size);
console.log(printarea);
console.log(colours);
console.log(comments);


text:
Q: How to pass kotlin FloatArray to flutter? I am trying to implement some kotlin native code so I have a FloatArray which I need to pass to flutter side.
Here is what it looks like,
kotlin code snippets
private var sampleData : FloatArray? = null

fun someFunction(){
// add data to sampleData
}

fun getData(result: MethodChannel.Result) {
        result.success(sampleData)
    }

dart code snippet
Future<void> getData() async {
    var result = await _methodChannel.invokeMethod('sampleData');
    print('type -> ${result.runtimeType}');
  }

When I print on both platforms it does print data on both platforms but on the flutter side when I check the runtimeType it always says List<Object?>.
So how can I pass FloatArray so that object is the relevant type?

A: I solved it by using List.from() like this,
Future<List<double>> getData() async {
    var result = await _methodChannel.invokeMethod('sampleData');
    return List<double>.from(result ?? []);
  }


text:
Q: How to nest a variable in another variable for parameter passing? say we have:
test() {
    echo $1
    echo $2
}

and two variables:
a="hello world"
b="$a blabla.."

test $b

it displays:
hello
world

what I want is:
hello world
blabla..

How can I achieve this?
Thanks

A: Use this:
a="hello world"
b="'$a' blabla"
eval "test $b"

The single-quotes are needed to keep hello world together as a single argument. Then you need to use eval because quotes are not normally processed after variable expansion.

A: You want b to be an array, otherwise there's no way with a single string containing whitespace to determine which space char is the separator:
mytest() {
    echo "$1"
    echo "$2"
}

a="hello world"
b=( "$a" "blah blah" )

mytest "${b[@]}"

hello world
blah blah


text:
Q: Can JPA persist data in JSON format? We have some fairly large Java POJO's that we serialize and save to the database as LOB's just cuz its easier than having 100 different tables to handle our Strings, Integer, Collection fields.  These seems icky if we ever need to change the Java objects themselves.
Would saving them as serialized JSON be a better approach?  Is there a best practice for this?  I'm wondering whether JPA can just automatically serialize/deserialize using something like Jackson.
EDIT: Since people seem to be asking about this, here is the justification:

*

*This is a Java class used to save form field information.  There are 100 fields.

*20 of the fields are Collections; therefore any queries on this data would require 20 different joins for each of the tables backing the collections

*99% of these fields are empty because the fields are all optional; therefore 21 different mostly empty tables is wasteful

*There will NEVER be queries against these individual tables.  The data is always retrieve all at once.

So we do have some kind of reason for doing it this way.


text:
Q: rewriting group by in subselect I have 2 queries and both the queries are showing different results when moving the where clause in inner select query.
select destination_number, count(*) as cnt from (
select caller_id_number as caller_id_number, destination_number as destination_number
from Final1  where start_stamp > '2013-01-01 00:00:00' and start_stamp < '2013-01-26 00:00:00'
group by caller_id_number, destination_number)
where destination_number = '1234'
group by  destination_number

count result: 294636
select destination_number, count(*) as cnt from (
select caller_id_number as caller_id_number, destination_number as destination_number
from Final1  where destination_number = '1234' and start_stamp > '2013-01-01 00:00:00' and start_stamp < '2013-01-26 00:00:00'
group by caller_id_number, destination_number)
group by  destination_number

count result: 310627
I will like to know why does the count change and which query is correct.


text:
Q: Did anybody have problems with migrating Xcode3.2x projects to Xcode4? At the moment I'm in a production cycle with submitting updates to my App every 2 weeks in average. I'm thinking of migrating to Xcode4 right now. Did anybody have problems with migrating projects or archiving or submitting to store? If so, best practises in solving such issues are very welcome.

A: I haven't experienced any problems and the transition guide claims:

Working on a Project in Xcode 4 Leaves
  Your Xcode 3 Preferences Untouched

I've also read somewhere else (but can't find it) that Xcode 4 uses the Xcode 3 project format unchanged. So far I can confirm this.


text:
Q: How to run CodeRAD 2 in netbeans I am learning CodeRAD but am using netbeans as my ide. I created a CodeRAD project from  https://start.codenameone.com but when i open it in my ide it has problems. I understand that from the tutorial they are using intellj. Can any one please help me on how i will start this using netbeans.
i downloaded all the required dependancies but still getting this error
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project coderad-common: Fatal error compiling: java.lang.NullPointerException: Cannot read field "kind" because "sym" is null -> [Help 1]

Am using apache netbeans IDE 14,
and java jdk 18, and the maven version downloaded in my netbeans is maven 4.47.
Yes in deed i did select netbeans as my ide before i download my template.