text:
Q: Writing a new programming language - when and how to bootstrap datastructures? I'm in the process of writing my own programming language which, thus far, has been going great in terms of what I set out to accomplish. However, now, I'd like to bootstrap some pre-existing data structures and/or objects.  My problem is that I'm not really sure on how to begin.
When the compiler begins do I splice in these add-ins so their part of the scope of the application?
If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?
I get that there are probably a number of plausible ways to approach this, but I'm having trouble with the setting my direction.  If it helps, the language is on top of the .NET core (i.e it compiles to CLR code).
Any help or suggestions are very much appreciated!

A:
When the compiler begins do I splice in these add-ins so their part of the scope of the application?

That depends on how the language is designed. If there is special syntax to define a list for example, then you should include the list. If there's not, then it should be part of a (standard) library and follow the rules of other libraries.

If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?

Again, if the language syntax requires the structures to function then maybe just include them in the compiler. Otherwise make them a library and bundle the library with the compiler, or make it a simple install dependency.

A: In the core runtime library, which you will distribute with your compiler.
Your question is a bit abstract, which I think has misled others in how they've tried to answer. I shall assume your language has a domain of interest, and there are some core objects (base classes, perhaps) which are critical for the language. If your language was for writing games then perhaps you might have some special base classes for players, non-player characters, objects and terrain. This would allow you to have special keywords and language constructs for creating games.
While it is tempting to somehow 'emit' those classes from inside the compiler, in practice it makes more sense to write them as a separate library with known features and have the compiler assume that they will exist. On top of the 'core' library you then build one or more 'extension' or 'add-on' libraries as the language system grows. The compiler knows nothing about these.
In fact it turns out that you should put as little as possible inside the compiler and the core because it is far easier to extend the language system by add-ons than by extending the compiler and core itself.
If this is off the mark, please edit your question to provide some more concrete details.

A: The .NET Framework and all its tools form a two-part system: it has a compiler that compiles a language such as C# into an assembly with CIL code, and a just-in-time (JIT) compiler that compiles the CIL to machine code.
A big advantage of the CLR is that you can specify any type you want just by using its fully qualified name. In addition, the assembly specifies in which assemblies such types can be found. Then when later the JIT compiler comes along, it will look at the fully qualified type name, load the referenced assembly that contains the type, and use that. The type does not have to be known beforehand, and there is never an issue with circular references. So if you put some types in a core library, all you have to do is to make sure the CLR assemblies generated from your language reference your core library, and then the types in them are instantly available for use.
The JIT compiler includes only logic to handle some primitive types (32-bit integer, 64-bit integer, float, managed references and managed pointers) and knows about some very special object classes (Object, Enum, ValueType, Delegate, ...). Almost all other functionality is either simulated with the primitive types (e.g. boolean true is any integer with a non-zero value) or supported through (virtual or non-virtual) method calls (properties, methods, overloaded operators, coercions and conversions all use method calls internally). Only some core functionality that cannot be expressed (efficiently) in a managed language (such as adding integers, or allocating arrays) is integrated in the JIT compiler.

A: Since you are building a language on top of the .NET runtime I think what you want to do is distribute a DLL that will initialize the wanted structures/environment, then call an entry point in that DLL in your compiler-generated MSIL code, before you execute the main() function (or however your programming language finds its entry point) of the user's program.
This is analogous to how libc variables and runtime dependencies are initialized by assembly code that is executed before the user's main() function [or more precisely the assembly code generated for the prolog+body of main()] is actually called in C.


text:
Q: Imagine this scenario? Would the person feel anything or be injured? Imagine an individual touched a high voltage line (like a bird) without touching any ground. For sake of illustration, imagine that this high voltage line was at a 100 Exavolt potential.
Would the bird or person notice anything when they touched the line, since they were not also touching ground?
Now, imagine that the bird flies away from the line and lands on a ground line, after having touched the hot line (i.e. the bird is no longer touching the hot line and is far from it). Would the bird notice anything in this case?
Obviously, if the bird touched both at the same time it would be electrocuted.

A:
Imagine a bird touched a 100 Exavolt potential line without touching any ground.
  Would the bird ... notice anything when they touched the line ...

Lets make it a sparrow.
No, the sparrow would not notice a thing.
Nor would any observer within a radius of about 10, or 20 or maybe 40 or 50 km.
Outside that radius degree of noticing would be variable and duration of noticing would be varied and the lucky ones may not notice.
Somewhere from around a few 10's of km out an observer would notice, briefly.
Somewhere, beyond many tens of km the observer may live.
(The 1 microsparrow Tsar-Bomba had a total destruction radius of 15 miles.)
Because:
See references at end for formulae et al
An Exavolt = 10^18 volt or a billion billion volts (US billions).
Preventing the line arcing to ground will be "an issue" - lets just assume it's high enough. Hanging from balloons maybe.
Self capacitance of an isolated sphere is 4.Pi E0.R
Assume  a sparrow approximates to a 1cm radius sphere. This assumption will be found to be non critical. Capacitance is about 1 pF (1E-12F).
This is an indicator of how much charge a given object can hold.
Let's be conservative and work at 1 Exavolt rather than the 100 suggested.
It will suffice.
Energy transferred to 1 capacitor by a potential change = 0.5 x C x V^2
Here C= 1E-12, V = 1E18
Energy = 0.5 x E-12 x (E18)^2 = 5E23 Joule
1 Terrajoule = E12 joule.
1 Petjoule = E15 joule
1 Megaton =~~ 4 Petajoules.
So sparrow energy = 5E23 / 4E15 ~~= E8 megaton
Largest H bomb ever = Tsar Bomba  at 50 MT.
So sparrow has more energy than 2 million or so of largest H bomb ever detonated.
After making allowance for bad assumptions, vague generalisations, specious thinking, general woolliness and lack of coffee, and adjusting everything down generously at all stages, it seems safe to say that your sparrow is toast (and very very very well vaporised toast to boot) AND that living anywhere within about say 100 km of said power line or of said sparrow is liable to be hazardous to your health.
Tsar Bomba = 50 megaton ~= 1 micro-sparrow at 1 Exavolt.

Related (maybe :-) ):
Capacitance - see self capacitance
Isolated spherical capacitor
Nuclear weapon yield
TNT equivalent
TEV and mosquitoes
LHC & TEV ...
Electrostatics
Mega Giga Tera Peta Exa Zetta Yotta Joule
A bomb energy

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import data from .xls to table by removing unwanted columns? I am creating a SSIS package to import data from .xls(EXCEL sheet 97-2003) to Sql DB.But my .xls file consists of unwanted data for first 4 rows .How can i skip those data.
My file look like
Create by:
Modified By:
Date:
Team:
Id     value      sum
1       44         88
2       45         98

I tried by i havent seen any advanced option in excel source to skip the rows as we do for .cs file.Can you please guys help me??


text:
Q: Disable gateways for WooCommerce products I currently have code installed on my website. Its function is to disable "Stripe" as a gateway for an array of products (2422, 2423,2424, 2425).
I would like to customize the code for product_id 3197 to disable bank transfer (backs) and COD (cash on delivery) gateways.
    add_filter( 'woocommerce_available_payment_gateways', 'rudr_payment_methods_by_product_ids' );

    function rudr_payment_methods_by_product_ids( $gateways ){

        // do nothing in /wp-admin
        if( is_admin() ) {
            return $gateways;
        }

        // Add product IDs you would like to unset payment gateways for
        $product_ids = array(
            2422,
            2423,
            2424,
            2425
        );

        // do nothing on "Pay for order" page
        if( is_wc_endpoint_url( 'order-pay' ) ) {
            return $gateways;
        }

        foreach ( WC()->cart->get_cart_contents() as $key => $cart_item ) {
            // count number of items if needed (optional)
            if( in_array( $cart_item[ 'data' ]->get_id(), $product_ids ) ) {
                if( isset( $gateways[ 'stripe' ] ) ) {
                    unset( $gateways[ 'stripe' ] );
                    break; // exit the loop if the specific product is found
                }
            }
        }

        return $gateways;

}

A: add_filter('woocommerce_available_payment_gateways', 'rudr_payment_methods_by_product_ids');

function rudr_payment_methods_by_product_ids($gateways) {

    // do nothing in /wp-admin
    if (is_admin()) {
        return $gateways;
    }

    // Add product IDs you would like to unset payment gateways for
    $product_ids = array(
        2422,
        2423,
        2424,
        2425
    );

    $cod_product_ids = array(3197);
    // do nothing on "Pay for order" page
    if (is_wc_endpoint_url('order-pay')) {
        return $gateways;
    }

    foreach (WC()->cart->get_cart_contents() as $key => $cart_item) {
        // count number of items if needed (optional)
        if (in_array($cart_item['data']->get_id(), $product_ids)) {
            if (isset($gateways['stripe'])) {
                unset($gateways['stripe']);
                break; // exit the loop if the specific product is found
            }
        }
        if (in_array($cart_item['data']->get_id(), $cod_product_ids)) {
            if (isset($gateways['cod'])) {
                unset($gateways['cod']);
            }
            if (isset($gateways['bacs'])) {
                unset($gateways['bacs']);
            }
        }
    }

    return $gateways;
}


text:
Q: Antlr4 does not detect integer from 1 to 8, lexer problem there is a problem with antlr 4 c# where it cannot recognize integer tokens. It works for number 1 and 9 but not 1 to 9!!
I tried rebuilding the grammar but it doesn't work :(.
Here is my grammar:
grammar simplerlang;

// Parser

program   : statement+ ;
statement : let | print ;
let       : VAR '=' INT ;
print     : 'print' (INT | VAR) ;

// Lexer

VAR : [a-z]+ ;
INT : [0–9]+ ;
WS  : [ \n\t]+ -> skip;

And here is my c# code:
using System;
using System.Collections.Generic;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperSimpleTestLang
{
    class Program
    {

        static Dictionary<string, int> variableMap = new Dictionary<string, int>();

        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("> ");
                string _in = Console.ReadLine();
                AntlrInputStream input = new AntlrInputStream(_in);
                simplerlangLexer lexer = new simplerlangLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lexer);
                simplerlangParser parser = new simplerlangParser(tokens);

                IParseTree tree = parser.statement();
                ParseTreeWalker walker = new ParseTreeWalker();
                walker.Walk(new simplerlangCustomListener(), tree);
            }
        }

        class simplerlangCustomListener : simplerlangBaseListener
        {
            public override void ExitPrint(simplerlangParser.PrintContext ctx)
            {
                if (ctx.INT() != null)
                {
                    Console.WriteLine(ctx.INT().GetText());
                }
                else if (ctx.VAR() != null)
                {
                    Console.WriteLine(variableMap[ctx.VAR().GetText()]);
                }
            }

            public override void ExitLet(simplerlangParser.LetContext ctx)
            {
                variableMap.Add(ctx.VAR().GetText(),
                int.Parse(ctx.INT().GetText()));
            }
        }
    }

}

input: print 1
output:
line 1:6 token recognition error at: '1'
line 1:7 missing {VAR, INT} at ''
input: print 0
output: 0
input: print 9
output: 9

A: VAR : [a-z]+ ;
INT : [0–9]+ ;

If you look closely at these two lines, you'll notice that the dash between 0 and 9 is longer than the one between a and z. This means that this isn't a regular dash, but a Unicode emdash (or something similar).
So ANTLR doesn't recognize this as a range, but as a character class matching 0, 9 or an emdash.


text:
Q: Cannot render css in ASP.NET I modified main.min.css and main.full.css (setting another color of background) and page now cannot render css. It's just a HTML.
Master page: (shortened version with links)
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="ZASshop.master.cs" Inherits="ZASshop.NET.ZASshop" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<%@ Register Assembly="ZAScontrols"    Namespace="ZAScontrols"    TagPrefix="zas" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="MasterHead" runat="server">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <link href="/App_Firma/css/main.min.css" rel="stylesheet" type="text/css" media="screen" />
        <link href="/App_Firma/css/firm.css" rel="stylesheet" type="text/css" media="screen" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
        <link href="/App_Firma/DayPilot/Themes/scheduler_8.css" rel="stylesheet" type="text/css"/>
        <link href="/App_Firma/css/custom.css" rel="stylesheet" type="text/css" media="screen"/>
                <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

at the end of this file link to script:
<script src="/App_Firma/js/app.min.js"></script>

and I also got a warnings and error in Chrome console:

LoginPage.aspx:7 Resource interpreted as Stylesheet but transferred
  with MIME type text/html:
  "http://localhost/LoginPage.aspx?ReturnUrl=%2fApp_Firma%2fcss%2fcustom.css".
  LoginPage.aspx:7 Resource interpreted as Stylesheet but transferred
  with MIME type text/html:
  "http://localhost/LoginPage.aspx?ReturnUrl=%2fApp_Firma%2fcss%2ffirm.css".
  LoginPage.aspx:7 Resource interpreted as Stylesheet but transferred
  with MIME type text/html:
  "http://localhost/LoginPage.aspx?ReturnUrl=%2fApp_Firma%2fcss%2fmain.min.css".
  LoginPage.aspx:7 Resource interpreted as Stylesheet but transferred
  with MIME type text/html:
  "http://localhost/LoginPage.aspx?ReturnUrl=%2fApp_Firma%2fDayPilot%2fThemes%2fscheduler_8.css".
  LoginPage.aspx?ReturnUrl=%2fApp_Firma%2fjs%2fapp.min.js:2 Uncaught
  SyntaxError: Unexpected token <

A: Change:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.6.1/css/font-awesome.min.css">

to
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.6.1/css/font-awesome.min.css" type="text/css"/>

you need to close the label with '/'
check this post too, seems to be the same problem:
Resource interpreted as Stylesheet but transferred with MIME type text/html in ASP.NET IIS

A: You must add .css MIME type with text/css value into IIS. Currently, the web server does not understand what .css means.
This will work when the content-type response header value is set to text/css.

A: You need to exclude the css files and images from getting authenticated as following in the configuration file. Using the location tag you can exclude a single file or a directory.
<location path="<relatevie path of your css files>">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>


text:
Q: std::vector for_each error C3867 function call missing argument list I want to use the for_each syntax with std::vector<std::string> but I keep getting the following error:
Error   1   error C3867: 'IO::checkFilePath':

function call missing argument list; use '&IO::checkFilePath' to create a pointer to member

Here is my code:
void checkFilePath(const std::string& filepath);
void checkFileList(const std::vector<std::string>& filelist);

void IO::checkFilePath(const std::string& filepath)
{
    if (!boost::filesystem::exists(filepath) || !boost::filesystem::is_directory(filepath))
    {
        //do smth
    }

}

void IO::checkFileList(const std::vector<std::string>& filelist)
{
        std::for_each(filelist.begin(), filelist.end(), checkFilePath);
}

A: Assuming you intend for checkFilePath to be a member, replace the use of it in the for_each algorithm with:
 [&](std::string const& s){return checkFilePath(s);}

and it will capture this and call the method.  The above requires C++11, which you may not have.  If you have C++03, you either have to use std::bind or boost::bind or write your own functor to capture this or the state required to solve the checkFilePath problem.
If your checkFilePath does not depend on the state of this, simply make the method static and your existing code should compile.  (Alternatively, make it a free function).

A: Function checkFilePath is a non-static member function. It can be called using an object of type IO. So you may not simply specify it as the third parameter of the for_each algorithm.
It would be simpler if this function would be a static member function.


text:
Q: Construction by side identification analogous to flat torus I know that the flat torus and the Kleinian bottle result from identication of opposite sides of a square given some orientation. I am interested in following cases.

$A$ becomes in my understanding two cones which are glued together on their base and is, therefore, homeomorphic to a sphere. I am completely lost regarding $B$ and $C$. Do you have any suggestions?


text:
Q: Best way to map this object into a new object Using lodash or vanilla javascript, I need to convert this json:
{
  "results" : [
    {
        "values" : [
            {"label" : "FOO", "value"  : "foovalue" },
            {"label" : "BAR", "value" : "barvalue1" },
            {"label" : "BAR", "value" : "barvalue2" }
        ]
    },
    {
        "values" : [
            {"label" : "FOO", "value"  : "foovalue"},
            {"label" : "BAR", "value" : "barvalue1"},
            {"label" : "BAR", "value" : "barvalue2"}
        ]
   }
    ]
}

into a new object where the label values become the key and duplicates are made into an array of new objects like this:
[
    [{"FOO" : "foovalue", "BAR" : ["barvalue1", "barvalue2"]}],
    [{"FOO" : "foovalue", "BAR" : ["barvalue1", "barvalue2"]}]
]

I've tried using _.map but it is overwriting the duplicate values and I need them all in an array.
Here is the closest I've come:
var arr = _.map(results, function(o) {
    return _.map(o.values, function(v) {
        var obj = {};
        obj[t.label] = t.value;
        return obj;
    });
});

where arr returns an array of the objects like this (with the objects being overwritten and not combined into a single object) [{"FOO" : "foovalue"},{"BAR" : "barvalue2"}] and I'm stuck trying to make them into the above array.

A: You could map the outer array and reduce the inner array by collecting the values of labels. If more than one collected element use an array.

var results = [{ values: [{ label: "FOO", value: "foovalue" }, { label: "BAR", value: "barvalue1" }, { label: "BAR", value: "barvalue2" }] }, { values: [{ label: "FOO", value: "foovalue" }, { label: "BAR", value: "barvalue1" }, { label: "BAR", value: "barvalue2" }] }],
    grouped = results.map(({ values }) => [
        values.reduce((o, { label, value }) => {
            if (!o[label]) {
                o[label] = value;
                return o;
            }
            if (!Array.isArray(o[label])) {
                o[label] = [o[label]];
            }
            o[label].push(value);
            return o;
        }, {})
    ]);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Passing property during upgrade to MSI that being uninstalled I have a custom action that I want to be executed every time MSI is executed without UI:
<InstallExecuteSequence>
  <Custom Action="InitSetup" Before="CostFinalize">UILevel=2</Custom>
</InstallExecuteSequence>

When upgrade is being executed, part of this action is to validate user password that is being provided in command line:

msiexec /i my.msi PROP_PASSWORD=12345

The PASSWORD property in is marked as Hidden and Secure:
<Property Id="PROP_PASSWORD" Hidden="yes" Secure="yes" />

During upgrade, while removing older version, InitSetup is triggered again but PROP_PASSWORD is not being passed to it so the action is failing and resulting overall upgrade fail.
Is there a way to force PROP_PASSWORD forwarding to the MSI that is being uninstalled?

A: Conditioning: Is it really necessary to validate the license key on uninstall? Could you condition the custom action to not run on uninstall? It is possible to configure it to not run on major-upgrade initiated uninstall - as opposed to normal, manually triggered uninstalls. It involves the property UPGRADINGPRODUCTCODE. By adding NOT UPGRADINGPRODUCTCODE to your condition, the custom action will never run during major upgrades. Something like: UILevel=2 AND NOT UPGRADINGPRODUCTCODE. The condition NOT REMOVE="ALL" would prevent it from running on regular uninstall as well. Conditions are hard - there are many installation modes to test.
Persist Properties: You can also persist the password in the registry and construct your setup to read it back if it is there. This involves a registry search which WiX can easily do.
Live?: Are you live with your previous package? If so, you can patch the live version with a minor upgrade to change the installed product's uninstall sequence. In the above case I suggested to change the conditioning of the custom action, and this is possible with a minor upgrade.
Setup.exe Initiated Uninstall: If you use a setup.exe launcher made with Burn, one option would be to kick off the uninstall of your old version via the launcher, rather than from within the actual MSI itself (which has serious technical limitations due to the requirement for only one MSI installation session active at any time). This would allow you to pass any command line to the uninstall routine.
In my tired state that is all I can produce right now. I'll check back to see if you are live or not, and to see how much I have forgotten to mention.

A: Just to leave a closure on a subject on how I solved it eventually - or more accurately found a work around: Since the custom action had a condition UILevel=2 instead of initiating silent installation with /q instead I instructed to upgrade using /qb-. That will set UILevel to 3. From user experience point of view they will only see notification form and progress bar. It will not display blocking dialogs.


text:
Q: Unable to clone repository from Gitlab: Permission denied, please try again I'm trying to clone an empty repository from my Gitlab account. I simply use the address shown on my Gitlab repository page under SSH:
git@gitlab.xxx.com:USERNAME/project-name.git

Then simply try this in an empty folder, but it keeps telling me permission denided, asking for retry:
git clone git@gitlab.xxx.com:USERNAME/project-name.git
Cloning into 'project-name'...
git@gitlab.xxx.com's password:
Permission denied, please try again.
git@gitlab.xxx.com's password:

and when I choose the https address for clone, this is the message:
remote: HTTP Basic: Access denied
fatal: Authentication failed for ....

I am able to login to Gitlab homepage with that password, so I don't know what is really wrong.
What is wrong? How to fix it?

A: As I'm in Windows, this answer was the life saver:
It happen every time I'm forced to change the Windows password and none of above answers helped to me.
Try below solution which works for me:
Go to Windows Credential Manager (press Windows Key and type credential) to edit the git entry under Windows Credentials. Replace old password with the new one.

A: ssh authentication on Gitlab requires a ssh key. You need to generate one, depending on your host, windows, linux or other. Then you need to add the key to your account.
You can find all the required information here: https://gitlab.com/help/ssh/README.md
If you want to use your http login you should switch to http authentication. At the left of the repository address there's a menu, you can choose ssh or http. Use the latter

A: What finally worked for me was to use:
$ git clone ssh://git@192.168.200.100:2022/USERNAME/project-name.git

I'll break this down as there are a three parts here:

*

*It was critical to specify "ssh://" and change ":USERNAME" to "/USERNAME".

*I do not have a hostname configured for this machine, so I used the IP Address.

*I'm running GitLab in a docker container and port 22 is forwarded via port 2022.

In summary, GitLab suggests this format:
git@192.168.200.100:USERNAME/project-name.git

which results in:
Permission denied, please try again.

regardless of whether the correct password is entered or a password is even set.  Instead, the following format works:
ssh://git@192.168.200.100/USERNAME/project-name.git

GLHF!


text:
Q: Sending email from sheet using google script I am trying to send emails to employees by using gs to pull the info from a sheet. I figured out how to pull the email address, message and subject, however, I want to include information from multiple columns in the message. Below is what I have so far....however I also want to include information from additional columns in the email message. For example, row[1] contains a message, row[3], row[4], row [5] contain values for Hotel 1, Hotel 2, Hotel 3 which i want to include in the message body.
/**
 * Sends emails with data from the current spreadsheet.
 */
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = 2; // Number of rows to process
  // Fetch the range of cells A2:D3
  var dataRange = sheet.getRange(startRow, 1, numRows, 4);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[i];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var subject = 'Your hotel reservation options';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

A: function sendEmails() {
  var sh=SpreadsheetApp.getActiveSheet();
  var sr=2;
  var rg=sh.getRange(sr, 1, sh.getLastRow()-sr+1,sh.getLastColumn());
  var data=rg.getValues();
  for (var i=0;i<data.length;i++) {
    var row=data[i];
    var emailAddress=row[0];
    var message=Utilities.formatString('Starting Message:%s\nHotel1:%s\nHotel2:%s\nHotel3:%s', row[1],row[3],row[4],row[5]);
    //You can add whatever text that you wish between the `%s` and they get replaced the arguments in the order that they appear.
    //If you wish to use the plain text version then use \n for new lines and if you plan to use {htmlBody:} then use `<br />` for new lines.
    var subject='Your hotel reservation options';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}


text:
Q: Deeply equal function error in Javascript I am trying to create a function to check whether two arrays are deeply equal to each other.
An example would be: [1, 2, { a: "hello" }] and [1, 2, { a: "bye" }] would return false.
This is my code so far:
const deeplyEquals = (val1, val2) => {
  let counter = 0;

  for (var i = 0; i < val1.length; i++) {
    if (typeof val1[i] === "object") {
      deeplyEquals(JSON.stringify(val1[i]), JSON.stringify(val2[i]));
    } else if (typeof val2[i] === "object") {
      deeplyEquals(JSON.stringify(val1[i]), JSON.stringify(val2[i]));
    } else if (val1[i] !== val2[i]) {
      counter++;
    }
  }

  return counter === 0 ? true : false;
};

I implemented a counter so that if it found a value in 1 that was not equal to the same value in 2 then it would increment. If the counter was not 0 then it would return false.
For the example, the counter increments to 7 but then right at the end, changes to 0 and therefore returns true instead of false.
I'm sure there would be an easier way to do this but I was wanting to see whether I could make this work as I am unsure why the counter is changing to 0 right at the end.
Thanks for any help!

A: The problem is that the counter is local to each call to deeplyEquals. There's a different counter for each call, and since you're making the calls recursively, you have lots of different counter variables in memory at the same time.
If you wanted to maintain a counter, you'd have to have each recursive call return the counter value (instead of a flag) so the code calling it could increment its counter by that much.
But there's no need in your code. Instead, just return false the first time you find a difference, either during in the call itself or in one of its recursive calls by checking the return value of the recursive call.

There are other issues with the code. Here's what I notice off-the-cuff:

*

*You're calling JSON.stringify, which returns a string, before passing values to deeplyEquals, which will convert arrays and objects to strings. Comparing the strings won't be reliable (because equivalent objects can have their properties in different orders: JSON.stringify({a:1,b:2}) is the string {"a":1,"b":2}, but JSON.stringify({b:2,a:1}) is the string {"b":2,"a":1}). Instead, pass the actual value.

*typeof x returns "object" for arrays and null as well as non-array objects; you need to handle those three cases separately.

*When comparing non-array objects, you need to loop through their properties to compare them.

SO has several questions and answers about doing deep equality checks; probably best to search for those, study them to ensure you understand how they work, and go from there.

A: Why dont you just JSON stringify both arrays and then compare?

const deepEquals(val1, val2){
    let v1 = JSON.stringify(val1);
    let v2 = JSON.stringify(val2);

    return v1 === v2;
}


text:
Q: Current udp packets queue length I have rather simple UDP server written on c.
Sometimes i need to know current length of all udp packets(bytes) queued in socket.
As i understand, getsockopt doesn't get such information.
Linux and FreeBSD solutions are both welcome, thanks!

A: ioctl(FIONREAD, ...) should be roughly what you are looking for,
http://www.daemon-systems.org/man/ioctl.2.html

A: From outside of the server (command line), you can do

netstat -uln

which will show you the length of all listening udp sockets.


text:
Q: Maven Liquibase plugin executing previous changesets I would like to be able to apply the latest changes to a liquibase controlled database via Maven. My POM contains:
<plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.3.5</version>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.23</version>
                </dependency>
            </dependencies>
            <configuration>
                <changeLogFile>src/main/resources/config/database/db-changelog-master.xml</changeLogFile>
                <driver>com.mysql.jdbc.Driver</driver>
                <url>jdbc:mysql://localhost:3306/myDb</url>
                <username>${db.user}</username>
                <password>${db.password}</password>
                <verbose>true</verbose>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>update</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

and when I run mvn liquibase:update I get the following:
[INFO]     driver: com.mysql.jdbc.Driver
[INFO]     url: jdbc:mysql://localhost:3306/myDb
[INFO]     username: dbUser
[INFO]     password: *****
[INFO]     use empty password: false
[INFO]     properties file: null
[INFO]     properties file will override? false
[INFO]     prompt on non-local database? true
[INFO]     clear checksums? false
[INFO]     changeLogFile: src/main/resources/config/database/db-changelog-master.xml
[INFO]     context(s): null
[INFO]     label(s): null
[INFO]     number of changes to apply: 0
[INFO]     drop first? false
[INFO]     ------------------------------------------------------------------------
[INFO] Executing on Database: jdbc:mysql://localhost:3306/myDb
INFO 23/07/15 13:09: liquibase: Successfully acquired change log lock
INFO 23/07/15 13:09: liquibase: Reading from DATABASECHANGELOG
SEVERE 23/07/15 13:09: liquibase: src/main/resources/config/database/db-changelog-master.xml: src/main/resources/config/database/changesets-001.xml::1000::gavin: Change S
et src/main/resources/config/database/changesets-001.xml::1000::gavin failed.  Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'tc_configuration'
already exists
liquibase.exception.DatabaseException:     com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'tc_configuration' already exists

It appears that Liquibase is trying to re-run changesets that have already been executed.
Is there a way to run only the new changesets?

A: Liquibase keeps track of what has already been executed in its own tables. It will not look if the table tc_configuration exists, before deciding whether to run the sql statement that creates it. Instead, it will check in its own tables if a changeset wit a given id has been executed. So in your case, apparently, the tc_configuration table has been created outside of liquibase, or liquibase tables have been manipulated.
If you start with an empty database and only update it with liquibase:update, liquibase will always run only the newest changes, exactly once.


text:
Q: How to copy Default Value using SSIS? I created Transfer SQL Server Objects Task in the SSIS. It seems to work but Default Value doen't copy properly. Is there any way to copy Default Value using SSIS?

A: A default value is usually a constraint. Do you have the option to transfer constraints enabled?
Just a few lines down from where you define the tables to copy, there are two options

*

*CopyAllDefaults

*DefaultsList

Take your pick, and it should move over.


text:
Q: Error from Updater Application Cron Script Error from Updater Application Cron Script
Found non-writable path(s):
/home/USERNAME/public_html/.htaccess.sample
Any Solutions?

A: I guess it's just a permission problem.
Just make this .htaccess.sample writeable for the user that runs the script
You can find the permissions documentation on the official website: http://devdocs.magento.com/guides/v2.0/install-gde/prereq/file-system-perms.html

A: I had the same problem with that .htaccess.sample.
And I thought it was a permission problem but it was not so what I did is I created that .htaccess.sample file and I run my cron using this commands "bin/magento cron:run" then "bin/magento indexer:reindex" and it solves my problem.
I hope this would help


text:
Q: Not able to validate against imported XSD I am trying to validate my XML against an XSD which is imported in another XSD.
Please have a look at the following code:
xml1.xml:
<e1 xmlns="n1"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="n2 main.xsd">
</e1>

xsd1.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="n1"
        elementFormDefault="qualified">
<xsd:element name="e1"/>
</xsd:schema>

main.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="n2"
        elementFormDefault="qualified">

<xsd:import namespace = "n1" schemaLocation = "xsd1.xsd"/>
</xsd:schema>

Validating xml1.xml (in netbeans with xml tools or in java) simply  throws:

cvc-elt.1: Cannot find the declaration of element 'e1'. [3]

What could be the problem?

A: Your model of xsi:schemaLocation requires adjustment.  It is not an include statement that automatically brings XSDs into scope; it is a hint that says for a given namespace where validation might be able to find an appropriate XSD.
When you declare, xsi:schemaLocation="n2 main.xsd", you're hinting to look in main.xsd for the n2 namespace, but you've said nothing about the n1 namespace actually associated with your root element.  Validation encounters the root element in the n1 namespace, consults your hints, finds nothing, and let's you know:

cvc-elt.1: Cannot find the declaration of element 'e1'. [3]

as it should.   Your path forward is clear:  Add a hint for the n1 namespace of your root element:
    xsi:schemaLocation="n2 main.xsd n1 xsd1.xsd"

and your XML document will validate successfully.


text:
Q: javascript NaN issue i need to write a code abbreviate the words greater than 10 letters to be as this : localiztion -> l10n. i used javascript to do this but a NaN error.

    <meta charset="UTF-8">
    <title>Way Too Long Words</title>

       <input type="text">
       <button>abbreviate</button>

How to overcome this issue

A: I see two major problems with your code as it stands:

*

*You currently only set the value of word once, when the document is loaded. You want this to happen every time the button is clicked.

*You don't currently check that word is longer than 10 letters, and try to calculate theResult regardless.
The combination of the two problems above means that word is set to an empty string as soon as the page loads, and clicking the button will always result in theResult being NaN.


text:
Q: CSSTransition for an array of questions I have an array of questions and I am trying to transition how each question moves to the next. I have tried the below code but unable to get it working. Any ideas?
<CSSTransition in={currentQuestion + 1} timeout={300} classNames={{ ...styles }}>
  <div>
    {questions[currentQuestion].questionText}
  </div>
</CSSTransition>

.exit {
    transform: translateX(0px);
    opacity: 1;
}
.exitActive {
    transform: translateX(-50px);
    opacity: 0;
    transition: transform 400ms ease-out, opacity 300ms ease-out;
}
.enter {
    opacity: 0;
    z-index: 1;
    transform: translateX(100px);
}
.enterActive {
    opacity: 1;
    transform: translateX(0px);
    transition: opacity 400ms ease-out, transform 500ms ease-out;
}


text:
Q: How to get friends of users not using my app (Graph 2.4) as there were recent changes in Facebook APIs, rights and endpoints, I would like to open this question once again as I spent almost 2 hours by searching for answer without reasonable answer.
My app (web-based-only at now) is based on contact/friends matchmaking. Thats not an issue at all.
In one part of app they can see all friends using the app, thats fine.
Trouble is, that I need my users to be able to invite them friends, which are not using app.
And here we go:

*

*Send Dialog: Ugly, not intuitive at all, user have to fill in chips
with names.

*invitable_friends: cut out for my purposes

*tagable_friends: can be used until facebook will found that I am
using it different way that I should - I don't like this approach
Goal:

*

*Having a list of friends I can invite into app

Any ideas here in 2017?


text:
Q: getting Fatal error: Call to a member function _query() on a non-object in C:\wamp\www\quotes\paginator.php on line 33 I read the reference given to me and took help from the code but i am getting fatal error. as above .please take look in my code and tell where i am lagging.
I have two pages. index.php and paginator.php
why i am getting fatal error I cant understand.
index.php
     <!DOCTYPE html>

    <?php
    require_once 'Paginator.php';

    $con       = new mysqli( 'localhost', 'root', 'pixster', 'quotes' );
    $limit      = ( isset( $_GET['limit'] ) ) ? $_GET['limit'] : 25;
    $page       = ( isset( $_GET['page'] ) ) ? $_GET['page'] : 1;
    $links      = ( isset( $_GET['links'] ) ) ? $_GET['links'] : 7;
    $query      = "SELECT table2.col2 AS a,table1.col2 AS b, table1.col1 AS  c, table1.q_url AS d FROM table2, table1 WHERE table2.col1 = table1.col4 ";//  AND table2.friendly_url= '".$authorname."'";

   $Paginator  = new Paginator( $con, $query );

   $results    = $Paginator->getData( $page, $limit );
   ?>
   <?php for( $i = 0; $i < count( $results->data ); $i++ ) : ?>

   <?php echo $results->data[$i]['$i']; ?>
   <?php echo $results->data[$i]['$row['b']']; ?>

    <?php endfor; ?>

    <title>quotes Pagination</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">

PHP Pagination

    Sr. No
    Quotes

      <?php for( $i = 0; $i < count( $results->data ); $i++ ) : ?>

      <?php echo $results->data[$i]['$i']; ?>
      <?php echo $results->data[$i]['$row['b']']; ?>

      <?php endfor; ?>

      <?php echo $Paginator->createLinks( $links, 'pagination pagination-sm' ); ?>

paginator.php
      <?php

     class Paginator {

    private $_con;
    private $_limit;
    private $_page;
    private $_query;
    private $_total;

  public function _construct( $con, $query )
 {

 $this->_con = $con;
 $this->_query = $query;

 $rs= $this->_con->query( $this->_query );
 $this->_total = $rs->num_rows;

 }

 public function getData( $limit = 10, $page = 1 ) {

$this->_limit   = $limit;
$this->_page    = $page;

 if ( $this->_limit == 'all' ) {
    $query      = $this->_query;
 } else {
    $query      = $this->_query . " LIMIT " . ( ( $this->_page - 1 ) *     $this->_limit ) . ", $this->_limit";
  }
  $rs             = $this->_conn->query( $query );

    while ( $row = $rs->fetch_assoc() ) {
    $results[]  = $row;
    }

    $result         = new stdClass();
    $result->page   = $this->_page;
    $result->limit  = $this->_limit;
    $result->total  = $this->_total;
    $result->data   = $results;

    return $result;
    }

  public function createLinks( $links, $list_class ) {
   if ( $this->_limit == 'all' ) {
    return '';
    }

   $last       = ceil( $this->_total / $this->_limit );

   $start      = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links :   1;
  $end        = ( ( $this->_page + $links ) < $last ) ? $this->_page +   $links : $last;

  $html       = '
';

    $class      = ( $this->_page == 1 ) ? "disabled" : "";
    $html       .= '
_limit . '&page=' . ( $this->_page - 1 ) . '">«
';

    if ( $start > 1 ) {
    $html   .= '
_limit . '&page=1">1
';
     $html   .= '
...
';
     }

    for ( $i = $start ; $i <= $end; $i++ ) {
    $class  = ( $this->_page == $i ) ? "active" : "";
    $html   .= '
_limit  .     '&page=' . $i . '">' . $i . '
';
  }

    if ( $end < $last ) {
    $html   .= '
...
';
    $html   .= '
_limit . '&page=' . $last .  '">' . $last . '
';
   }

 $class      = ( $this->_page == $last ) ? "disabled" : "";
 $html       .= '
_limit . '&page=' . ( $this->_page + 1 ) . '">»
';

  $html       .= '
';

  return $html;
  }
  }
  ?>

A: Try to solve this basic problem with mysql first :)
Limit and Offset will be your friend

A: Study linke i gave you, if u will have any problems, comeback to this post and i will edit my answer to post you back.
Here you got all info you need to do that
Problem solving steps:
Select all data from given Mysql Table.

Fetch selected data, to get it ready for use.

Throw it into the User Interface with for example loop.

Do Pagination to split your data across X-number of pages.

You have to put your function (methods) inside the class, like:
class Pagination {

function getData(){
}

}

Also construct have two __ not _ :
class Pagination {

   // properties go here

   public function __construct()
   {
   }

   public function getData()
   {
   }
}

To call a function you have to create new class object:
$pagination = new Pagination;

Then u can call methods:
$pagination->getData();

You should first read / watch something about PHP OOP and learn the basics:
some php oop tutorials


text:
Q: Entity Framework buggy when invoking stored procedure via Database.SqlQuery When invoking a stored procedure with a parameter of type int and value 0, Entity Framework sends a null value to the server.
var requiredIntParameter = new SqlParameter("RequiredInt", 0);
var tableParameter = new SqlParameter("@Table", System.Data.SqlDbType.Structured);
... table creation ....
List<ReturnType> result = DBContext.Database.SqlQuery<ReturnType>("EXEC NAMEOFSPROC "
           + "@RequiredInt, "
           + "@Table, "
           requiredIntParameter ,
           tableParameter,
           );

Entity Framework log:
Opened connection at 1/10/2018 4:42:09 PM +01:00
EXEC NAMEOFSPROC @RequiredInt, @Table
-- RequiredInt: 'null' (Type = Int64, IsNullable = false)
-- @Table: '' (Type = Object, IsNullable = false)
-- Executing at 1/10/2018 4:42:09 PM +01:00
-- Completed in 40 ms with result: SqlDataReader

Resulting exception:

The parameterized query '(@RequiredInt int' expects the parameter   @RequiredInt'), which was not supplied.

Note: As Sproc has a table parameter,
((IObjectContextAdapter)this).ObjectContext.ExecuteFunction

is not an option for me!
Using:

*

*EF 6.2.0

*SQL Server 2008

A: There is a Workaround:
var requiredIntParameter = new SqlParameter("RequiredInt", typeof(int));
requiredIntParameter.Value = 0;

Now log is
EXECSPROC @RequiredInt, @Table
-- RequiredInt: '0' (Type = Int32, IsNullable = false)
-- @Table: '' (Type = Object, IsNullable = false)
-- Executing at 1/10/2018 4:42:09 PM +01:00

-- Completed in 40 ms with result: SqlDataReader
And everything is fine!


text:
Q: How to show the units of the numbers? I wrote a code that converts Cartesian coordinates to ellipsoidal coordinates and it works but some variables are in degrees and some of them are in meters. I have to show the difference but I don't know how.
def ell2xyz(latitude,longitude,ellHeight):
    import math
    a=6378137.0000
    b=6356752.3141
    e=(math.sqrt(((a**2)-(b**2))/(a**2)))
    N=a/math.sqrt((1-((e**2)*(math.sin(latitude)**2))))
    x=(float((N+ellHeight)*math.cos(latitude)*math.cos(longitude)))
    y=(float(N+ellHeight)*math.cos(latitude)*math.sin(longitude))
    z=(float((1-e**2)*(N+ellHeight))*math.sin(latitude))
    return x,y,z

latitude,longitude,ellHeight=ell2xyz(41.00000000,29.00000000,500.0000)
print(latitude,longitude,ellHeight)

A: I suggest you use the format method
print("{} degrees {} degrees {} meters".format(latitude,longitude,ellHeight))

A: The thing is all your variables (latitude, longitude and ellHeight) are floats, which are simply numbers. An unit is an abstraction that makes sense for us humans, but your code has no way of knowing what are the units you wish to work with. I believe you merely want to show the units on the screen. In order to do that, you have to manually tell what is what.
Any of the following will work the same:
print(latitude, "degrees,", longitude, "degrees,", ellHeight, "meters")
print("{} degrees, {} degrees, {} meters".format(latitude, longitude, ellHeight))
print(str(latitude) + " degrees, " + str(longitude) + " degrees, " + str(ellHeight) + " meters")

The result will be:

4711572.482946889 degrees, 4179837.81128292 degrees, -1005107.7207451101 meters

A: You can use a list, so you will have both float and string:
def ell2xyz(latitude,longitude,ellHeight):
    import math
    a=6378137.0000
    b=6356752.3141
    e=(math.sqrt(((a**2)-(b**2))/(a**2)))
    N=a/math.sqrt((1-((e**2)*(math.sin(latitude)**2))))
    x=(float((N+ellHeight)*math.cos(latitude)*math.cos(longitude)))
    y=(float(N+ellHeight)*math.cos(latitude)*math.sin(longitude))
    z=(float((1-e**2)*(N+ellHeight))*math.sin(latitude))
    if x > 0:
        x = [x,"N"]
    else:
        x = [x,"S"]
    if y > 0:
        y = [y,"E"]
    else:
        y= [y,"W"]
    z = [z, "m"]
    return x,y,z

latitude,longitude,ellHeight=ell2xyz(41.00000000,29.00000000,500.0000)
print(latitude,longitude,ellHeight)

Result:
[4711572.4829468895, 'N'] [4179837.81128292, 'E'] [-1005107.7207451101, 'm']


text:
Q: Return Type Pthread Create Using C++ I am trying to create a function that returns an object with certain type. The problem is that create thread does not accept it. Can somebody help me with the following code?
struct thread_args
 {
    Key *k;
    QNode *q;
    uint8_t USED_DIMENSION;
};

QLeafNode *st ;
  struct thread_args Structthread2;
     Structthread1.k=min;
     Structthread1.q=start;
      Structthread1.USED_DIMENSION=4 ;

pthread_create( &thread1, NULL,(void*)&FindLeafNode,  ((void *) &Structthread1));
pthread_join( thread1, (void**)st);

QLeafNode* FindLeafNode (Key *k, QNode * r, uint8_t USED_DIMENSION ){

}

A: First off, your thread function is not correctly defined. Only functions of the form:
void* function_name(void* param)

can be passed to pthread_create.
Now, in order to return a pointer to something from this function, you need two pthread functions:
pthread_exit(void *value_ptr);

Call this inside the thread function to return a value through value_ptr and
pthread_join(pthread_t thread, void **value_ptr);

Call this inside the parent thread to wait for the termination of the child with handle thread and retrieve the value returned by pthread_exit in value_ptr.
So your code should look something like:
struct thread_args
 {
    Key *k;
    QNode *q;
    uint8_t USED_DIMENSION;
};

QLeafNode *st ;
struct thread_args Structthread1;
Structthread1.k=min;
Structthread1.q=start;
Structthread1.USED_DIMENSION=4 ;

pthread_create(&thread1, NULL, FindLeafNode,  ((void *) &Structthread1));
pthread_join(thread1, (void**)st);

...

void* FindLeafNode (void* param) {
    struct thread_args* value = (struct thread_args*) param;
    // use value for computations
    QLeafNode* result = ... // allocate result with new / malloc
    pthread_exit((void*)result);
}

A: return a heap-allocated pointer to [so use new to allocate it] your new object (allocated in the thread, and perhaps later freed in the "parent" thread joining it, i.e. using the result).


text:
Q: "fatal error, no screen found" when installing 12.04 with live USB I have downloaded 12.04 and made a bootable USB flash drive. Then I installed this version on my laptop (Dell Vostro 1510).
Unfortunately my laptop does not run with Ubuntu. Actually just after the appearance of the Ubuntu logo the display disappears. When I try to run commands through the command line it does not work neither and the error is the following: fatal error, no screen found. I should mention that the laptop works properly with the bootable USB flash.
Please let me know if there is a solution for this problem.

A: This might happen due to bad USB bootable flash. Recreate your flash with this, if you are a Windows user. If you are a Linux user, you can use this. Then try the installation again.


text:
Q: Why does the XName equality operator appear to refer to itself? I was wondering how equality is defined for XName, and noticed that the equality operator appears to refer to itself (when viewing the decompiled C# using ILSpy 2.4.0.1963)
public static bool operator ==(XName left, XName right)
{
    return left == right;
}

A: This is a bug in your decompiler.
It's actually casting both operands to object to compare by reference.
See the actual source:
    // The overloads of == and != are included to enable comparisons between
    // XName and string (e.g. element.Name == "foo"). C#'s predefined reference
    // equality operators require one operand to be convertible to the type of
    // the other through reference conversions only and do not consider the
    // implicit conversion from string to XName.

    /// <summary>
    /// Returns a value indicating whether two instances of <see cref="XName"/> are equal.
    /// </summary>
    /// <param name="left">The first XName to compare.</param>
    /// <param name="right">The second XName to compare.</param>
    /// <returns>true if left and right are equal; otherwise false.</returns>
    /// <remarks>
    /// This overload is included to enable the comparison between
    /// an instance of XName and string.
    /// </remarks>
    public static bool operator ==(XName left, XName right) {
        return (object)left == (object)right;
    }


text:
Q: How to avoid code review bottlenecks when some of the team pair program There is a school of thought that describes code reviews as the number one priority activity for all developers in a sprint since they are either:
a) A source of unrealised value
b) A source of bugs
While I'm not sure I subscribe to such as black and white view, I do agree with the sentiment.
But enough of the background.
We have a persistent problem where reviews sit on the queue for days at a time. Invariably the bottlenecks are caused by the lead developers as they're more in demand. Also, due to the important nature of their work, they tend to pair program so they don't require their own code reviews to be done as such. Hence there is no real incentive for them to do reviews as a quid pro quo.
The most often used complaint is that they will lose their train of thought while programming. There is some truth in this, but surely they could just review after lunch or first thing in the morning?
Are there any ways round this? On previous projects we have applied a SLA of one day which worked well for the most part but again, the rule tended to be broken by the pair programmers.
Developers take it in turns to do code reviews so the load is already being shared fairly.

A: The teams should be empowered to review their own code, after all there's no one better qualified.
GIT Pull Requests implement one of the easiest and most robust models for this:

*

*Code cannot be merged to master until it's been reviewed by X (two is recommended) other people, usually there's a stipulation of one dev and one tester

*Anyone can code review. A junior asking questions can have the same effect as a senior critiquing. It's about picking up complexity and edge cases.

There are a few things you can do to make it easier:

*

*Pair programming counts as a code review (after all it was developed together)

*Keep changesets small, there are many many many reasons why this is a good idea

*Don't auto-assign to your most experienced, busiest people. Let other team members pick up code and let them take pride in the code base

*Consider creating an extra state (or including it in the Definition of Done) for your stand up boards. Like all bottlenecks, make it visible so people can see work that needs to be done to unblock people

*Consider using automated code review tools so people can focus on the important stuff, not the automatable rules

A: If you perform pair (or mob) programming, do you need peer review?
I've previously written an answer on the reasons why one would want to perform peer code reviews in the first place. However, all of these are also addressed by pair programming. In essence - pair programming is a real-time, highly interactive code review.
It may be easier to say that your code must either be pair programmed (and set up some team norms or guidelines around effective pairing techniques) or go through a code review, but both aren't required. Of course, you can always add a code review to get a third (or fourth) set of eyes on a change, but if you simply have a need to ensure that two people are watching and ensuring the quality of every change, pair programming gets you that.


text:
Q: What exactly triggers main.ts in Angular By building a basic Angular CLI project, we get the following index.html when we run the application:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SimpleCLI</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script type="text/javascript" src="inline.bundle.js"></script>
  <script type="text/javascript" src="polyfills.bundle.js">
  </script><script type="text/javascript" src="styles.bundle.js"></script>
  <script type="text/javascript" src="vendor.bundle.js"></script>
  <script type="text/javascript" src="main.bundle.js"></script></body>
</html>

Next step is our entry point main.ts. Of course the name does not matter and is defined in .angular-cli.json. Could someone clarify the following points?

*

*Is it vendor.bundle.js which contains all Angular code and is responsible for starting the bootstrap process?

*Once the bootstrap process starts how exactly the application knows where to go, namely how does it trigger main.ts? Is it only the property
 "main": "main.ts"

inside .angular-cli.json which defines that?

A: Yes, only angular-cli.json references it for handling the startup of the application.
main.ts is not a module but a simple script-file, executed from top to bottom and can have any other file-name.
The only other thing that affects it as a .ts file, is tsconfig.json, which handles the transpilation to javascript. but it does so by the *.ts file-name pattern not by referencing files individually.

A: *

*No Vendor.bundle.js don't contain angular code. It contain 3rd party plugins, eg. bootstrap, jquery, jquery plugins, which we included in package.json.
It's not responsible for bootstrapping angular application.

*In main.ts file last line  platformBrowserDynamic().bootstrapModule(AppModule) responsible for bootstraping of angular application. platformBrowserDynamic() part of this line indicates that we are about to boot Angular in a browser environment.
3.The bootstrapModule() function helps bootstrap our root module taking in the root module as its argument.

*AppModule is our root module which is the entry module for our application, this can actually be any of the modules in our application but by convention AppModule is used as the root module.

5.In our AppModule, we then need to specify the component that will serve as the entry point component for our application. In our app.module.ts file where we import the entry component (conventionally AppComponent) and supply it as the only item in our bootstrap array inside the NgModule configuration object. eg. bootstrap[AppComponent]

A: main.ts file is the entry point of our web-app.It compiles the web-app and bootstraps the AppModule to run in the browser.
It starts with importing the basic module which we need.
platformBrowserDynamic().bootstrapModule(AppModule)
This code has reference to the parent module i.e AppModule. Hence when it executes in the browser, the file that is called is index.html. index.html internally refers to the main.ts file which calls the parent module i.e AppModule.
When AppModule is called, it calls app.module.ts which further calls the AppComponent based on the bootstrap.
bootstrap:[AppComponent]
In app.component.ts, there is selector:"app-root" which is used in the index.html file. This will display the contents present in app.component.html.

A: main.bundle.js is the one responsible for starting the bootstrap process.
It is built by the Angular compiler based on the config read from angular.json, which is where it is indicated that main.ts is the main bootstrap file.

A: In Angular 7 (Angular CLI project), angular.json file contains all project information which contains information about complete project assets. In this file, main can be configured to any type script file which can then act as module starter for the configured application , as an example say start.ts.
Now start.ts will act as starting point for the application module which should ideally responsible for bootstrapping the application using platformBrowserDynamic().bootstrapModule(YourModuleStarter)


text:
Q: Component doesn't update with state When I click on the add button the state updates but then the list still shows the same stuff. How do I fix it so that it updates with state?
I'm also using sortablejs but I removed it from the code since it doesn't seem to be relevant and I didn't want to clutter the code with unnecessary packages.
import React, { useState } from "react";

import { ListGroup } from 'react-bootstrap';

const DraggableList = () => {

  const [events, setEvents] = useState([
    { id: 1, name: "shrek" },
    { id: 2, name: "fiona" },
    { id: 3, name: "donkey" },
  ]);

  const addEvent = () => {
    let newEvents = events
    let event = {
      id: events.length + 1,
      name: "dragon",
    }
    newEvents.push(event)
    setEvents(newEvents)
    console.log(events)
  }

  return (
    <div>
      <button onClick={addEvent}>Add</button>
      {events.map((item) => (
        <ListGroup.Item key={item.id} action variant="success">{item.name}</ListGroup.Item>
      ))}
    </div>
  );
};

export default DraggableList

A: Because the pointer of the newEvents array never changes. Do let newEvents = [...events] and it should work


text:
Q: How to increase cookies storage limit(4096) in chrome I have implemented cookies using jquery and its working fine if  center name's array length is less than 4096 byte.
but i have to store large amount of  center name's array in cookies (more than 4096 byte).
so when i store center name more than 4096 byte then it can not store in cookies due to length of cookies.
So my question is below
Is there any way to increase storage length of cookies if center name's array is more than 4096 byte in chrome
Cookies length set near to max length after this length no new center name array is stored

Note:
(1) center name is an jquery array eg.(["1","2",etc])
(2) this question is only for chrome browser its working fine in IE 10
hope someone will help..
Thanks

A: I would recommend looking into HTML5 localStorage that allows you to store larger amounts of data instead of passing them back and forth using cookies.

Storage size
Web storage provides far greater storage capacity (5 MB per origin in
  Google Chrome,[6] Mozilla Firefox,[7] and Opera; 10 MB per storage
  area in Internet Explorer;[8] 25MB per origin on BlackBerry 10
  devices) compared to 4 kB (around 1000 times less space) available to
  cookies.

Reference: https://en.wikipedia.org/wiki/Web_storage


text:
Q: How to retry failed Vue Concurrency tasks? I am using Vue Concurrency in my Vue 3 / TypeScript project.
And I want to create a Task that will retry x number of times if a specific kind of error is thrown.
But I can't figure out how to retry the call based on it's error message. I want to retry the call a limited number of times if the error is INVALID_OAUTH. Otherwise just throw the error like normal.
How can this be done?
For example:
const getZohoDeskTicketByIdTask = useTask(function* (signal, ticketId: string) {
  const ticket: string = yield getZohoDeskTicketById({
    ticketId: ticketId,
  });
  // If the above yield returns an error of 'INVALID_OAUTH' it should retry X number of times before failing. If the error is anything else, throw it like normal.
  return ticket;
});

const ticket = await getZohoDeskTicketByIdTask.perform('12345');

A: This can be either handled inside the task instance (therefore one task instance does multiple requests until it finishes with either success or error state) or it can be managed one level higher and you can retry the whole task perform action.
I'm actually struggling to find the difference here, perhaps task.performCount could be useful in some ways but since you want to also check for specific errors and not all task instances error out, it's complicated.
Maybe I'd still just create a generic utility that could be used both for tasks but also outside of them.
And it seems like it already exists:
https://github.com/lifeomic/attempt
try {
  const result = await retry(async (context) => {
    try {
    await getZohoDeskTicketByIdTask.perform('12345');
    } catch (e) {
     if (e.message === 'INVALID_OAUTH') {
       throw e; // rethrow error
     } else {
       // do something else with other errors... maybe also rethrow or cancel task completely with task.cancelAll() ?
     }
    }
  }, options);
} catch (err) {
// handle case when retrying failed
}

I didn't test this code, but I'd start with something like this. Hope it's useful!


text:
Q: Best Match Search Json File I have a json file with something like this:
{
"Cars": [
 {
  "name": 'Honda'
  "color": 'Black'
  "age": 'Old'
  },
 {
  "name": 'Ford'
  "color": ' Red'
  "age": 'Old'
  },
 {
  "name": 'Mazda'
  "color": 'Black'
  "age": 'New'
  }
 ]
}

I want to write a function that will prompt the user to provide a name, color, and age, and then it will search through the json and return the objects that best match the search parameters. I also want the user to be able to only enter some of the parameters.
Examples:

*

*User enters {'name':'Honda', 'color':None, 'age':None}, returns all the information for the Honda

*User enters {'name':None, 'color':'Black', 'age':None}, returns all the information for the Honda and the Mazda

*User enters {'name':None, 'color':'Black, 'age':'New'}, returns all of the information for the Mazda

I can't think of any programmatic ways to do this that aren't incredibly inefficient. The best thing I can think of is basically searching the whole Json for match's to the first key, then searching those for matches of the second key, then searching those for matches of the third key, then printing the resultant. Skipping keys that dont exist in the query payload would help, but that still seems really inefficient.
I'm not sure if I'm allowed to ask technique questions on here, so if the answer is that I should go build said inefficient function and then come back for info on how to improve it, that's fine, but I thought I might as well ask if there were any common examples first.

A: #lets say your json is stored in variable json_var
car_name=input("car name")
car_color=input("car color")
car_age=input("car_age")

car_list=[]
for cars in json_var["cars"]:
    if (cars["name"]==car_name or cars["color"]==car_color or cars["age"]==car_age):
        car_list.append(cars["name"])

print(car_list)


text:
Q: SQL Query: Combining group by with different record entries Given the following table and records:

location
interaction
session

us
5
xyz

us
10
xyz

us
20
xyz

us
5
qrs

us
10
qrs

us
20
qrs

de
5
abc

de
10
abc

de
20
abc

fr
5
mno

fr
10
mno

I'm trying to create a query that will get a count of locations for all sessions that have interactions of 5 and 10, but NOT 20.
So assuming the above, the query will return

count
location

2
us

1
de

FR will not be in the results, because session 'mno' did not have an interaction of 20.
As far as I can tell, I need to group by session first, then group by location afterwards. Which might mean using a nested select statement. I've tried a few things, but am not sure how to proceed. Would appreciate any help on how to approach a query like this.

A: Maybe your example is wrong - if a location session shall have interactions 5 and 10 but not 20 then only 'fr' shall be in the result as both 'us' and 'de' do have 20 in all their sessions.
SQL fiddle here.
with t as
(
  select location, array_agg(interaction) arr
  from the_table
  group by location, session
)
select count(*) cnt, location
from t
where arr @> array[5,10] and not arr @> array[20]
group by location;


text:
Q: Waiting for an async HTTP request to complete This question has been asked in various ways already here, and I understand the problem pretty well.  The general solution is to invoke callbacks for handling HTTP results, but I'm specifically wanting to avoid that.
I imagined I could use a "are we done yet" flag to keep things working, but this isn't working as expected.
//
//  Test the IP the comment came-from.
//
exports.testJSON = function ( obj )
{
    var ip     = obj['ip'] || "";
    var result = null;
    var done   = false;

    //
    //  The URL request we're going to make
    //
    var options = {
        host: 'www.stopforumspam.com',
        port: 80,
        path: '/api?ip=' + ip
    };

    //
    // A GET request
    //
    var re = http.request(options, function(res) {
        var str = '';

        res.on('data', function(chunk) {
            console.log( "Got data " + chunk );
            str += chunk;
        });
        res.on('end', function() {
            console.log( "Got END" );
            result = "..... ";
            done = true;
        });
      }).on('error', function(e) {
         done = true;
         console.log("Got error: ", e);
     });

   re.end();

   while( ! done ) {
   }

   return( result );
};

Sadly this doesn't work - the busy look just spins indefinitely, and I see no console-logging to indicate that I'm receiving data.
Adding in "process.nextTick()" to the "while(!done){}" loop makes no difference either.
Surely I don't need to rework my whole plugin system to cope with a different approach, and the callback updating the "done" flag will work, somehow?

A: If your whole plugin system is using JavaScript, reworking it probably wouldn't be a bad idea. If you don't want to deal with asynchronous code using callbacks, you can look into promises as another solution for managing asynchronous code. The library "q" may be a good place to start with that.
An alternative would be to use node-fibers. I've never used it before, but the examples are straightforward. Take a normal callback pattern for example:
console.log('waiting 2 seconds...');
setTimeout(function() {
    console.log('Finished!');
}, 2000);

A similar example using node-fibers:
var Fiber = require('fibers');

function wait(ms) {
    var fiber = Fiber.current;
    setTimeout(function() {
        fiber.run();
    }, ms);
    Fiber.yield();
}

Fiber(function() {
    console.log('waiting 3 seconds...');
    wait(1000);
    console.log('waiting 2 seconds...');
    wait(1000);
    console.log('waiting 1 seconds...');
    wait(1000);
    console.log('done!');
}).run();

There is a little wrapping to be done to get node-fibers to function, but now you can avoid dealing with callbacks and use async code in a synchronous manner.


text:
Q: Problem installing windows service I am having a problem installing a Windows service. I installed and uninstalled the service numerous times (installutil..... installutil /u) without any problem but something went wrong and now when I attempt to install, I get the error message listed below.  I checked the computer management console, and service CIMediator does not appear on the list of services.  How do I remove the service?
System.ArgumentException: Source CIMediator already exists on the local computer.

A: Just solved the same problem, also after a numerous uninstalls/installs/restarts.
I have my own implementation of service installer (derived from [System.Configuration.Install.Installer][1]), and I have specified application EventLog as following:
    public ProjectInstaller()
    {
        InitializeComponent();

        EventLogInstaller installer = FindInstaller(this.Installers);
        if (installer != null)
        {
            installer.Log = "MyService";
        }
    }

You might have the same feature implemented the following way ([MSDN: EventLog.CreateEventSource Method] [2]):
if(!EventLog.SourceExists("MySource"))
{
    EventLog.CreateEventSource("MySource", "MyNewLog");
}

In my case, during some of the installs EventLog was successfuly created, but during uninstall something went wrong, and EventLog was not removed (although it was not displaying in EventViewer, it was still present in the registry).
So the error "MyService already exists on the local computer", was obviously error about EventLog, not the service itself.
You could try to do the following:
Go to your Start menu and type regedit. This will open Registry Editor. Be careful with it, it is always recommended to back up the whole registry before doing anything (File -> Export), or only the keys you are about to edit/delete.
Open Edit -> Find , type CIMediator and leave only Keys checked. Your service name should appear as key multiple times, on following locations

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\eventlog\CIMediator,
  HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\CIMediator,
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\CIMediator,
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\CIMediator

Try to delete these keys. It worked for me.
1
2

A: Check to see if the key is still there in the registry.
HKLM\System\CurrentControlSet\Services\CIMediator (probably, unless the key is defined differently)
If it is, export the key to a .reg file and then delete it.


text:
Q: Fix point cloud lidR - normalize_height fails I'm working on an airborne lidar survey of around a thousand tiles (500m * 500m) using LAScatalog with lidR. I firstly ran a las_check()... No issues reported:
las_check(CTG_Bertrix)

#>  Checking headers consistency
#>   - Checking file version consistency... ✓
#>   - Checking scale consistency... ✓
#>   - Checking offset consistency... ✓
#>   - Checking point type consistency... ✓
#>   - Checking VLR consistency... ✓
#>   - Checking CRS consistency... ✓
#>  Checking the headers
#>   - Checking scale factor validity... ✓
#>   - Checking Point Data Format ID validity... ✓
#>  Checking preprocessing already done
#>   - Checking negative outliers... ✓
#>   - Checking normalization... no
#>  Checking the geometry
#>   - Checking overlapping tiles... ✓
#>   - Checking point indexation... yes

After this initial check, I still ran filter_duplicates() and after ran a normalize_height() process which actually failed:
#> An error occurred when processing the chunk 998. Try to load this chunk with:  chunk <-
#> readRDS("C:\Users\gef\AppData\Local\Temp\RtmpWK6Gyw/chunk998.rds")
#> las <- readLAS(chunk) 3044 points were not normalizable. Process aborted.

I loaded the considered chunk and ran again las_check():
#>  Checking the data
#>   - Checking coordinates... ✓
#>   - Checking coordinates type... ✓
#>   - Checking coordinates range... ✓
#>   - Checking coordinates quantization... ✓
#>   - Checking attributes type... ✓
#>   - Checking ReturnNumber validity... ✓
#>   - Checking NumberOfReturns validity... ✓
#>   - Checking ReturnNumber vs. NumberOfReturns... ✓
#>   - Checking RGB validity... ✓
#>   - Checking absence of NAs... ✓
#>   - Checking duplicated points... ✓
#>   - Checking degenerated ground points... ✓
#>   - Checking attribute population...
#>      'EdgeOfFlightline' attribute is not populated
#>   - Checking gpstime incoherances
#>     ✗ 1263 pulses (points with the same gpstime) have points with identical ReturnNumber
#>   - Checking flag attributes... ✓
#>   - Checking user data attribute... ✓
#>  Checking the header
#>   - Checking header completeness... ✓
#>   - Checking scale factor validity... ✓
#>   - Checking point data format ID validity... ✓
#>   - Checking extra bytes attributes validity... ✓
#>   - Checking the bounding box validity... ✓
#>   - Checking coordinate reference system... ✓
#>  Checking header vs data adequacy
#>   - Checking attributes vs. point format... ✓
#>   - Checking header bbox vs. actual content... ✓
#>   - Checking header number of points vs. actual content... ✓
#>   - Checking header return number vs. actual content... ✓
#>  Checking coordinate reference system...
#>   - Checking if the CRS was understood by R... ✓
#>  Checking preprocessing already done
#>   - Checking ground classification... yes
#>   - Checking normalization... no
#>   - Checking negative outliers... ✓
#>   - Checking flightline classification... yes

This las file can be downloaded HERE...
As the error message is not really self-explanatory, I would like to know how to find the not normalizable points? How to fix/remove them ?

A: The question has already been asked here at least twice. One occurrence here.
library(lidR)
las = readLAS("bertrix.laz")
normalize_height(las, tin())
#> Interpolation of 3044 points outside the convex hull defined by ground points (outside the triangulation) failed and returned NAs.
#> Erreur : 3044 points were not normalizable. Process aborted.

plot(las, color = "Classification")

As you can see, on the top right you have a building with no ground points at all. All the points are too far from a ground point to allow interpolation especially with TIN. You have three options.

*

*Discard those points normalize_height(las, tin(), na.rm = TRUE) but I don't think it is a good idea

*Use a much larger buffer to catch more ground point after the building. e.g. 80 meters opt_chunk_buffer(ctg) = 80

*Allow interpolation where TIN is not defined even if it's far (e.g. 100 meters) normalize_height(las, tin(extrapolate = knnidw(rmax = 100)))
In all cases interpolation in region with no ground point is relatively weak


text:
Q: Use version number in file links in Sphinx In Sphinx, file links can be generated using the following syntax:
`name_of_file.js <some/location/name_of_file.js>`_

In the conf.py file, a version variable is defined that we can use in the .rst files like such:
|version|

Including the version into the file link using that syntax is not allowed:
`name_of_file.|version|.min.js <some/location/name_of_file.|version|.min.js>`_

So, how can I generate links to files named something like name_of_file.<version_num>.min.js and use the version number from conf.py?

A: I had a need for something similar and after much experimentation I have a workaround for this. Be warned, this is a crummy solution but it works.
The short answer:
You need to split the parts of the link to left and right of |version| and use raw html along with the |version|. Your .rst will look like this:
Example of a link with version in it |link-pre|\ |version|\ |link-post|

.. |link-pre| raw:: html

    name_of_file.min.js

The long answer
There are a couple of hurdles we need to overcome:
Problem 1:
Now, |version| is essentially a substitution definition. When you use a substitution reference in your document, it has to lead with a space like so |version|.
So even in a regular rsT sentence, which is not a link, you can't do name_of_file.|version|.min.js. You will need to do name_of_file.\ |version|.min.js, i.e, escape the space with a \
Problem 2: Nested inline markup is not supported in reST: http://docutils.sourceforge.net/FAQ.html#is-nested-inline-markup-possible
So you can't make a substitution, |version|, within a link \`name_of_file.|version|.min.js`\. This is why we have to use raw-html and break it into parts, and we create 2 more substitution definitions |link-pre| and |link-post|, which will be replaced with their raw-html in the generated output.
I tried using inline :raw-html: role but that did not help, so unfortunately the solution turned out to be verbose.


text:
Q: Enterprise Library - Get value from ParameterValue Expression I am trying to convert Enterprise Library TypeRegistration ConstructorParameters to a collection of key/value pair (a HashTable or an IDictionary in general).
The ConstructorParameters property is an IEnumerableOf(ParameterValue) so my problem is how to extract the values from each ParameterValue object.
Every ParameterValue object contains a Type and an Expression.
For ex. if a ParameterValue contains: "EventLoggingEnabled = false"
then I can get the key (which is the EventLoggingEnabled) using expression.Member.Name
but I can't find a way to get the value (which is "false").
Any thoughts?

A: Have you looked at the implementation of the UnityContainerConfigurator? Even if you don't want to use Unity, you can see how the type registration stuff is handled there and adapt to the Windsor API.
You generally don't need to code to the raw ParameterValue class and poke through the lambda expressions. There are actually three subclasses:

*

*ConstantParameterValue

*ContainerResolvedParameter

*ContainerResolvedEnumerableParameter

The ConstantParameterValue gives you the value directly as the .Value property. ContainerResolvedParameter is used when the value of the parameter needs to be injected by the container, and ContainerResolvedEnumerableParameter is used when you have a collection that needs to be injected. Every instance of ParameterValue is actually one of these types.
So, what you should do is try to cast to each one, and then switch based on the actual type. There's a utility base class, ParameterValueVisitor, that lets you implement the Visitor pattern over ParameterValues to make your code cleaner.
So, what I'd do is drop the picking through lambdas - you don't need to do it. Implement a visitor to pull out the information you need using the base class, then the pre-digested information will be available to you in the concrete classes. Look at the UnityContainerConfigurator for an example of how this is done.

A: This works, when the Expression is not ResolvedEnumerable.
    var dependencies = new Hashtable();

        foreach (ParameterValue pv in constructorParameters)
        {
            MemberExpression exp = pv.Expression as MemberExpression;
            if (exp != null)
            {
                String key = exp.Member.Name;
                Object val = GetValue(exp);

                dependencies.Add(key, val);
            }
        }

    // ...

    private Object GetValue(MemberExpression member)
    {
        var objectMember = Expression.Convert(member, typeof(Object));
        var getterLambda = Expression.Lambda<Func<Object>>(objectMember);

        return getterLambda.Compile().Invoke();
    }


text:
Q: Modifying a Template for I'm using a template for vocabulary and I need to modify it a little bit.
\newcommand{\entry}[5]{\markboth{#1}{#1}\textbf{#1}\ {/#2/}\ \textit{#3}\ $\bullet$\ {#4}}
% Defines the command to print each word on the page, \markboth{}{} prints the first word on the page in the top left header and the last word in the top right

Currently, the commend for each entry has the following structure; four arguments for the: word, pronunciation, classification and definition. For example
naive /naív/ Adjective • showinga lack of experience, wisdom, or judgment.
But many words have multiple meanings, so I would need to use lists inside the entry commend like this:
word /pronunciation/ Noun • meaning 1 • meaning 2
Adjective • meaing 1 meaning 2
Can anyone teach me how to modify it?

A: The problem is that TeX is macro-based: it substitutes up to 10 patterns passed to a macro. I.e. you don't have a functional approach available in LaTeX, as far as I know. I.e. it's not that easy to deal with an unkonwn number of variables in advance.
So here is one way to do it, straight forward: split the \newcommand used in overleaf into several, and just call them one by one. There may be more elegant ways to do it.
So just call \entry (topic and pronounciation), \type (noun, adverb etc.) and one of the \meanX (depending of the number of meanings passed) macros. Use indenting to better follow more complex entries in the Latex-source-code. Don't forget to use an appropriate package to show correct phonetics/pronunciation: mine is just an indication.
\documentclass[10pt]{article}
%\usepackage{}% use the appropriate package for phonetics/pronunciation

\newcommand{\entry}[2]{\textbf{#1}\ {/#2/}}
\newcommand{\type}[1]{\textit{#1}\ $\bullet$}
\newcommand{\meansA}[1]{{#1.}}
\newcommand{\meansB}[2]{{#1;}{ #2.}}
\newcommand{\meansC}[3]{{#1;}{ #2;}{ #3.}}

\begin{document}
    \entry{Right}{(rait)}
     \type{adjective}
      \meansA{morally good}
     \type{noun}
      \meansB{law}{justice}
     \type{adverb}
      \meansC{direction}{directly}{correctly}

    \entry{Latex}{LAH-tekh}
    \type{abbreviation}
    \meansA{a typesetting program}
    \type{noun}
    \meansA{a milky fluid found in many plants}
\end{document}

Result:

P.S.: It might be wise to use \providecommand instead.


text:
Q: Errno 10048 when trying to read again from network through Bacpypes I use a python library called Bacpypes in order to read bacnet points in network. In my first trial of reading my points with function MultipleReadProperty , there is no problem. I get all values without any problem. But in second poll i get an error about socket like following :
[0.0, 1149064.0, 1941115.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 13525024.0, 448152.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
[31/Jan/2015:11:39:33] HTTP Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 670, in respond
    response.body = self.handler()
  File "C:\Python27\lib\site-packages\cherrypy\lib\encoding.py", line 217, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "C:\Python27\lib\site-packages\cherrypy\_cpdispatch.py", line 61, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "C:\Users\Sansal\Desktop\Projeler\sayac_okuma8\main2.py", line 231, in sayac_oku
    readings_from_counters=ReadCounters(counters_list)
  File "C:\Users\Sansal\Desktop\Projeler\sayac_okuma8\main2.py", line 153, in ReadCounters
    this_application = ReadPointListApplication(points_list, this_device, args.ini.address)
  File "C:\Users\Sansal\Desktop\Projeler\sayac_okuma8\main2.py", line 43, in __init__
    BIPSimpleApplication.__init__(self, *args)
  File "C:\Python27\lib\site-packages\bacpypes-0.10.6-py2.7.egg\bacpypes\app.py", line 555, in __init__
    self.mux = UDPMultiplexer(self.localAddress)
  File "C:\Python27\lib\site-packages\bacpypes-0.10.6-py2.7.egg\bacpypes\bvllservice.py", line 85, in __init__
    self.directPort = udp.UDPDirector(self.addrTuple)
  File "C:\Python27\lib\site-packages\bacpypes-0.10.6-py2.7.egg\bacpypes\udp.py", line 144, in __init__
    self.bind(address)
  File "C:\Python27\lib\asyncore.py", line 342, in bind
    return self.socket.bind(addr)
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.

As seen at first line, i get all values from network with no problem.
To solve problem, i used stop() function of Bacpypes library in a few points of code. Especially just before the code that starts polling. But, it appears that i cant somehow close the socket. Could you please make some suggestions about this issue?
Thanks in advance.

A: Bacpypes has recently been update to version 0.15 and a lot of effort has been made in the documentation. There a re a lot of new features and the code has been simplified for typical things like whois, IAm.
I suggest you have a look http://bacpypes.readthedocs.io/en/latest/
and here : https://github.com/JoelBender/bacpypes/blob/master/samples/MultipleReadProperty.py
I can also suggest BAC0 (http://bac0.readthedocs.io/en/latest/), which is built on the top of bacpypes and provide out-of-the box features to communicate with BACnet devices. (Disclaimer : BAC0 is my project and I'm contributor to bacpypes)


text:
Q: Can I use phpunit tests on functions that are not in class? I have a small .php file with that one function which I've pasted below. I would like to test that function.
Is there any way of how I can use phpunit? I'm not using composer.json.
<?php public function LoginMe($a, $b) //nick, psw
        {
        require 'includes/mysql_connection.php';
        require 'includes/config.php';
        require 'includes/messages.php';
        require 'backend/LogsSystem.php';

                // Some code

                return false;
        } ?>

A: For example, if your script is called authentication.php, this can be a hint for test:
<?php
use PHPUnit\Framework\TestCase;
include 'authentication.php';
class authenticationTest extends TestCase
{
    public function testAuthentication()
    {
    //your test here, call LoginMe with expected parameters
    }
}

You may find interesting this too: PHP Testing, for Procedural Code


text:
Q: Number of elements/words in a shell array variable I have looked at the question How to count number of words from String using shell on SO, which explains how to count words inside a variable.
But this only counts one word inside my variable so I have no idea how to fix it.
I have the following variables:
vmfarm1=(host1.com host2.com host3.com host4.com )
maximus=(host11.com host 12.com host 13.com)
firefly=(host5.com)

I need to find a way to count all the host names into a number inside the variables.
After this, the number inside that was counted, have to be used as a variable in this line.
I have tried:
echo "$input" | wc -w
printf ' \n|/4.vmfarm1 ' >>  textfile.txt

I have to write the 4 above by myself to the number and I need it to be done automatically, this is why I need a variable.

A: vmfarm1, maximus and firefly are not just variables, these are arrays.
Use the proper syntax: ${#vmfarm1[@]} is the number of entries in your array.

A: In Bash and ksh, expanding an array as if it was a normal string variable, gives the first element of the array. That is, $somearray is the same as ${somearray[0]}. (*)
So,
somearray=(foo bar doo)
echo "$somearray"
echo "$somearray" | wc -w

prints foo and 1, since foo is only one word. If you had somearray=("foo bar doo" "acdc abba") instead, then the wc would show three words.
You'll need to use "${somearray[@]}" to expand all elements of the array as distinct shell words (arguments), or "${somearray[*]}" to expand them as a single shell word, joined with spaces (**)
In any case, note that the number of elements in an array, and the number of words (in the wc -w or the human language sense) are not the same, see below. Use "${#somearray[@]}" to get the number of elements in the array.
somearray=("foo bar doo" "acdc abba")
echo "${#somearray[@]}"                # 2 elements, that contain
echo "${somearray[@]}" | wc -w         # 5 whitespace separated words in total

(*) ignoring sparse and associative arrays for now.
(**) assuming default IFS.

A: To print the number of elements in an array variable in various shells with array support:

*

*csh/tcsh/zsh/rc/es/akanga: echo $#array

*ksh¹/bash¹/zsh: echo "${#array[@]}"

*fish: count $array

*yash: echo "${array[#]}"

*Bourne/POSIX shells (where the only array is "$@"): echo "$#"
Now for the number of whitespace delimited words in all the elements of an array variable, that's where you may want to use wc -w, but you'd need to feed it the content of all the elements separated by at least one white space for instance with:
printf '%s\n' $array:q | wc -w        # csh/tcsh
printf '%s\n' "${array[@]}" | wc -w   # ksh/bash/zsh/yash
printf '%s\n' $array | wc -w          # fish/zsh/rc/es/akanga
printf '%s\n' "$@" | wc -w            # Bourne/POSIX

Or you could do the splitting of the elements into further whitespace-delimited words and count them in the shell itself.

*

*csh/tcsh (split on SPC/TAB/NL)
(set noglob; set tmp=($array); echo $#tmp)

*ksh/bash/yash ($IFS splitting, SPC/TAB/NL by default)
(set -o noglob; set -- ${array[@]}; echo "$#")

*zsh ($IFS splitting, SPC/TAB/NL/NUL by default)
echo ${#${=array}}

*rc/es ($ifs splitting):
tmp = `{echo $array}
echo $#tmp

*fish (counts all sequences of non-whitespace (according to PCRE) characters):
count (string match -ar -- '\S+' $array)

*Bourne/POSIX ($IFS splitting):
(set -f; set -- $@; echo "$#")

¹ note that given that ksh/bash arrays are sparse and have indices that start at 0 instead of 1 in every other shell, that number will generally not be the same as the maximum index in the array

A: Given an array arr, its length (number of elements) is given by ${#arr[@]}.
Using this with your vmfarm1 array:
printf ' \n|/%d.vmfarm1 ' "${#vmfarm1[@]}" >>textfile.txt

A: This may be not smart, but I think you can get number of hosts in array.
vmfarm1=(host1.com host2.com host3.com host4.com)
#maximus=(host11.com host12.com host13.com)
#firefly(host5.com)
COUNT=0

for i in ${vmfarm1[@]};
do
    HOSTCOUNT=`echo $i |wc -l`
    COUNT=$((COUNT + HOSTCOUNT))
done

printf "vmfarm1:%2d\n" $COUNT

Thanks


text:
Q: Morse code to a normal text doesn't work with Hashmap I was trying to make an morsecode translater. I already had the sentence to the morse code but now I am trying to do it the other way. But I am stuck here. I make it with some getters and setters where I can give input forn the sentence and for the choose between sentence to morse code and morse code to sentence.
My public static void main where I make put in my sentence and where i check which row in the hashmap i need to make the sentence:
import java.util.Collection;
import java.util.HashMap;
import java.util.*;

public class MorseCodeTest {
    public static void main(String[] args){
        MorseCode morseCode = new MorseCode();
        morseCode.setType();
        int type = morseCode.getType();
        morseCode.setInput();
        String zin = morseCode.getInput().toLowerCase();
        int i = 0;

        if (type == 1) {
        while (i < zin.length()) {
                HashMap<Character, String> letters = new HashMap<Character, String>();
                letters.put('a', ".-");
                letters.put('b', "-...");
                letters.put('c', "-.-.");
                letters.put('d', "-..");
                letters.put('e', ".");
                letters.put('f', "..-.");
                letters.put('g', "--.");
                letters.put('h', "....");
                letters.put('i', "..");
                letters.put('j', ".---");
                letters.put('k', "-.-");
                letters.put('l', ".-..");
                letters.put('m', "--");
                letters.put('n', "-.");
                letters.put('o', "---");
                letters.put('p', ".--.");
                letters.put('q', "--.-");
                letters.put('r', ".-.");
                letters.put('s', "...");
                letters.put('t', "-");
                letters.put('u', "..-");
                letters.put('v', "...-");
                letters.put('w', ".--");
                letters.put('x', "-..-");
                letters.put('y', "-.--");
                letters.put('z', "--..");
                letters.put(' ', "/");

                System.out.print(letters.get(zin.charAt(i)) + " ");
                i++;
            }

        }
        else {
            while (i < zin.length()) {
                HashMap<String, Character> morse = new HashMap<String, Character>();
                morse.put(".-", 'a');
                morse.put("-...", 'b');
                morse.put("-.-.", 'c');
                morse.put("-..", 'd');
                morse.put(".", 'e');
                morse.put("..-.", 'f');
                morse.put("--.", 'g');
                morse.put("....", 'h');
                morse.put("..", 'i');
                morse.put(".---", 'j');
                morse.put("-.-", 'k');
                morse.put(".-..", 'l');
                morse.put("--", 'm');
                morse.put("-.", 'n');
                morse.put("---", 'o');
                morse.put(".--.", 'p');
                morse.put("--.-", 'q');
                morse.put(".-.", 'r');
                morse.put("...", 's');
                morse.put("-", 't');
                morse.put("..-", 'u');
                morse.put("...-", 'v');
                morse.put(".--", 'w');
                morse.put("-..-", 'x');
                morse.put("-.--", 'y');
                morse.put("--..", 'z');
                morse.put("/", ' ');

                Collection<Character> values = morse.values();

                for (Character Character: values) {
                System.out.print(Character);
                }
                i++;
            }
        }
    }
    }

this are my getters and setters:
import java.util.Scanner;

public class MorseCode {
    String input;
    int type;

    public MorseCode() {
        this.input = "";
        this.type = 0;
    }

    public String getInput() {
        return input;
    }

    public void setInput() {
        Scanner input = new Scanner(System.in);
        System.out.println("Zin");
        this.input = input.nextLine();
    }

    public int getType() {
        return type;
    }

    public void setType() {
        Scanner input = new Scanner(System.in);
        System.out.println("morse naar zin in van zin naar morse?");
        this.type = input.nextInt();
    }
}

the get/setInput function is for the sentence what i want to translate and the type is in which way I want to tanslate it. I hope that someone can help me with solving this problem.

A: with this code you are just printing out every letter you added to your map:
Collection<Character> values = morse.values();

for (Character Character: values) {
  System.out.print(Character);
}

Depending on your input you want to split the morse-code and get the value from the map.
For example if your user inputs ".- -.... -.-." you could split the String and get every value and get the value from the map. Instead of the while-loop in the else-block.
String[] parts = zin.split(" ");
StringBuilder sb = new StringBuilder();
for (String part: parts) {
    sb.append(morse.get(part));
}
System.out.println(sb);