text:
Q: SSIS Fuzzy Lookup for dates I am trying to match clients using three fields: FirstName, LastName, Gender, and DOB. It's my understanding that SSIS Fuzzy Lookup only applies to strings (never seen this in documentations, just some bloggers said so) so in this scenario, could I somehow use DOB to build "confidence"? How does this tool compare the dates?
Here is a thread on this issue: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d2e53f8c-abfc-461e-9263-fd46b95247c0/ssis-fuzzy-lookup-and-dates?forum=sqlintegrationservices

A: I do a lot of Name/DOB searches and it's really difficult to get right. You can consider sorting using a function similar to the one below. This will basically take two 8-digit dates (YYYYMMDD) and count the number of miss-matched digits.
For example these date pairs have 1 miss-matched digit:

*

*1976-10-20 and 1976-01-20 (10 vs 01)

*1976-10-20 and 1975-10-20 (76 vs 75)

Depending on how much data dealing with, this is good for sorting (aka putting your best match first) but not for filtering (because there is no indexing involved).
ALTER FUNCTION dbo.BirthDateRank ( @DOB1 DATE, @DOB2 DATE )
RETURNS INT
AS
    BEGIN
        -- 10/31/2016 --> 10312016
        DECLARE @xDOB1 VARCHAR(10) = REPLACE(CONVERT(CHAR(10), @DOB1, 101), '/', '');
        DECLARE @xDOB2 VARCHAR(10) = REPLACE(CONVERT(CHAR(10), @DOB2, 101), '/', '');

        DECLARE @i INT = 0;
        DECLARE @iRet INT = 0;

        WHILE @i <= LEN(@xDOB1)
        BEGIN
            SET @iRet = @iRet + CASE WHEN SUBSTRING(@xDOB1, @i, 1) = SUBSTRING(@xDOB2, @i, 1) THEN 0 ELSE 1 END

            SET @i = @i + 1
        END

        RETURN @iRet;

    END;
GO


text:
Q: Access Denied with system account I run some SP-Code within the System Acoount. But even with that user I still receive an access denied acceptioon. I also tried other user accounts (with admin rights)
Error message:
Attempted to perform an unauthorized operation.
 at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException ex)
 at Microsoft.SharePoint.SPSecurableObject.CheckPermissions(SPBasePermissions permissionMask)
 at Microsoft.SharePoint.SPRoleAssignmentCollection.Init()
 at Microsoft.SharePoint.SPBaseCollection.GetEnumerator()
 at OLXPermissionEventReceiver.OLXPermissionEventReceiver.OLXPermissionEventReceiver.<>c__DisplayClass1.<SetPermissionsToListItem>b__0()

Code:
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            try
            {

                SPSite tmpSite = new SPSite("Http://example.com);

                SPUserToken sysUser = tmpSite.SystemAccount.UserToken;

                using (SPSite site = new SPSite(siteUrl, sysUser))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        try
                        {
                            SPPrincipal principal = (SPPrincipal) group;
                            item.BreakRoleInheritance(false);
                            web.AllowUnsafeUpdates = true;
                            // Works until here
                            List<SPRoleAssignment> roleAssignmentList = new List<SPRoleAssignment>();
                            bool cateringRoleFound = false;
                            foreach (SPRoleAssignment roleAssignment in item.RoleAssignments)
                            {

                            }

                        }
                    }
                }
            }
        }

It looks like the "foreach" - loop is throwing the error. Any idea?

A: I spotted two issues here:
Your running under elevated privlages (application pool account) and then your getting a new spsite object under system account using its token??? before all of that your getting the first spsite object but not disposing of that object awell! it could be that the application pool doesnt have the correct permissions todo what your asking it todo!
i bet if you debug you would find that SystemAccount.UserToken has access denied over it as your performing impersonation over elevated rights.... iv already answered how to do this correctly here and why:
SharePoint -access to path is denied
so for you its easy:
/// <summary>
/// get the system token from the list of users to elevate spsite
/// </summary>
/// <param name="spSite"></param>
/// <returns></returns>
protected static SPUserToken GetSystemToken(SPSite spSite)
{
    SPUserToken res = null;
    bool oldCatchAccessDeniedException = spSite.CatchAccessDeniedException;
    try
    {
        spSite.CatchAccessDeniedException = false;
        res = spSite.SystemAccount.UserToken;
    }
    catch (UnauthorizedAccessException)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite elevatedSPSite = new SPSite(spSite.ID))
                res = elevatedSPSite.SystemAccount.UserToken;
            // (***)
        });
    }
    finally
    {
        spSite.CatchAccessDeniedException = oldCatchAccessDeniedException;
    }
    return res;
}

now as you were doing you can now do this instead:
        SPUserToken sysToken = null;
        //let sharepoint dispose of the first spsite object to get token, you can change to any url or keep it the same if its the current site your trying to get
        using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
        {
            //get the system token from the method GetSystemToken and passing the spSite that you want to run under
            sysToken = GetSystemToken(spSite);

            //now wer have the token from the method above we can call as you did creating a new spsite object that is impersonated
            using (SPSite impersonatedSite = new SPSite(siteUrl, sysToken))
            {
                //we are impersonating the [@"SHAREPOINT\SYSTEM"] account
                //wrap around using as were using .openWeb which makes a new spweb object under the impersonated user account
                using (SPWeb web = impersonatedSite.OpenWeb())
                {
                    try
                    {
                        SPPrincipal principal = (SPPrincipal) group;
                        item.BreakRoleInheritance(false);
                        web.AllowUnsafeUpdates = true;
                        // Works until here
                        List<SPRoleAssignment> roleAssignmentList = new List<SPRoleAssignment>();
                        bool cateringRoleFound = false;
                        foreach (SPRoleAssignment roleAssignment in item.RoleAssignments)
                        {

                        }

                    }
                }
            }
        }

that should solve your issue, its for 2010 but should apply to 2013.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell find and store the file name How do I search for a file and store the file name in a variable.
I can find the file info by doing
Get-Item myf* | Select-Object Name

I get
Name
----
myfile101.csv

How do I get just the file name without the "Name" heading

A: Some options for your specific use case
Get-Item myf* | Select-Object -ExpandProperty Name
(Get-Item myf* | Select-Object Name).Name

A bit of backgroud
The Select-Object Name still returns an object, not just a string.
You can verify yourself by adding | Get-Member
   TypeName: Selected.System.IO.DirectoryInfo

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Name        NoteProperty string Name=myfile


text:
Q: Crossinheritance in C# I am looking for the best way to model a scenario in C#, which I would describe as "crossinheritance".
First, I have a directed graph, which nodes can be of two different types: Connector and Component. I create an interface IObjectBase which contains properties both Connector and Component have, like a list of IObjectBase-Children. Then I create interfaces for the Connectors and Components which inherited from IObjectBase:
public interface IObjectConnector : IObjectBase ...
public interface IObjectComponent : IObjectBase ...

The implementation looks similar, I create an abstract class for the BaseObject and inherit it for Connector and Component classes:
public abstract class ObjectBase : IObjectBase ...
public class ObjectConnector : ObjectBase, IObjectConnector ...
public class ObjectComponent : ObjectBase, IObjectComponent ...

So far so good. The problem is, that the directed graph can exist in two different "states" or "modes" - in Editor-Mode and in Configuration-Mode. Depending on the mode, there are Properties and methods Connectors and Components both have (like adding children only when in editor-mode or a "isSelected" property only when in configurator-mode).
So, I would need to have 4 different objects: ComponentConfig, ComponentEdit, ConnectorConfig, ConnectorEdit
I started with thinking about further inherit IObjectConnector and IObjectComponent:
public interface IObjectConnectorEditor : IObjectConnector
public interface IObjectConnectorConfigurator : IObjectConnector
...

and create objects while inheriting from the existing Components and Connectors:
public class ObjectConnectorEditor : ObjectConnector, IEditor
...
public class ObjectComponentEditor: ObjectComponent, IEditor

The problem now is: I would need to implement the IEditor-interface in both Editor-classes, which would be an awefull redundancy. But I cannot create an implementation of IEditor from which the objects would inherit, because I can only inherit from exactly one class in C#, so the following will not work:
public abstract class Editor : IEditor ...
public class ObjectConnectorEditor: ObjectConnector, Editor

What would you suggest as the best architectural solution for this problem?
Thanks in advance,
Frank

A: Remember single responsibility. You want your objects to be all information containers, connectors and editors?
I would propose a different design where these responsibilities are split up, with a class hierarchy that represents Objects, Connectors, Components and Editors.

A: I agree with Polity's answer, but if you really want to fake up multiple inheritance in C#:
Create Component, Connector, Edit, and Config as separate classes. Also create IComponent, IConnector, IEdit, and IConfig as separate, matching interfaces.
Now you can create ComponentConfig, implementing IComponent and IConfig, and just delegate the interface methods to private instances of Component and Config.
class ComponentConfig : IComponent, IConfig
{
    private IComponent component;
    private IConfig config;

    public ComponentConfig() {
        component = new Component();
        config = new Config();
    }

    public ComponentMethod() {
        return component.Componentmethod();
    }

    public ConfigMethod() {
        return config.ConfigMethod();
    }

}

See http://en.wikipedia.org/wiki/Delegation_pattern

A: First of all, improve your naming: in this context Object has no meaning, call it Node. You're using your nodes in two different contexts, so it's reasonable to have an IEditorNode interface and a IConfiguratorNode interface. If these share some methods, it's reasonable to have a super-interface, so they are declared only once. So far we have:
interface INode {
}

interface IEditorNode : INode {
  int f(); // Needed later
}

interface IConfiguratorNode : INode {
}

These interfaces serve a double purpose: they make it possible to use Components and Connectors interchangeably and they limit the methods available to the Editor and to the Configurator to what they actually need to see. Note that there's no need to use interfaces if neither of these reasons are relevant.
You have two types of nodes: Connector and Component. If these don't have specific methods that are used either in the Editor or in the Configurator but not in both, just define them as classes and make them implement both IEditorNode and IConfiguratorNode. Otherwise it may make sense to distinguish these through interfaces:
interface IEditorComponent : IEditorNode {
}

interface IConfiguratorComponent : IConfiguratorNode {
}

Make the Component class implement both these interfaces:
class Component : IEditorComponent, IConfiguratorComponent {
}

The Connector class is analogous.
Unfortunately C# doesn't support multiple inheritance of implementation, so your only alternative to factor together common Editor or Configurator functions is to put them in separate classes, give Component and Connector a private attribute of each of these classes and delegate the implementation:
class EditorHelper {
  public int f() {
    return 42;
  }
}

class Connector : IEditorConnector, IConfiguratorConnector {
  EditorHelper eh;

  public Connector() {
    eh = new EditorHelper();
  }

  public int f() {
    return eh.f();
  }
}


text:
Q: How to extract generic type in this complex type definition in TypeScript? https://stackblitz.com/edit/xh93ag?file=index.ts
Consider I have these types
type TDomainConditionOperator =
    '=' | '!=' | '>' | '>=' | '<' | '<=' | '=?' |
    '=like' | 'like' | 'not like' | 'ilike' | 'not ilike' | '=ilike' |
    'in' | 'not in' | 'child_of' | 'parent_of'
    ;
type TDomainCondition = [string, TDomainConditionOperator, any];
export type TDomain = TDomainCondition | '|' | '&' | '!';

export type TReferenceValue<T, TypeOnly extends boolean = false> = TypeOnly extends true ?
    T :
    T | number | Upsert<T>;

export type TToOne<T, TypeOnly extends boolean = false> = TypeOnly extends true ?
    TReferenceValue<T, TypeOnly> :
    TReferenceValue<T, TypeOnly> | Domains;

export type TToMany<T, TypeOnly extends boolean = false> = TypeOnly extends true ?
    Array<TReferenceValue<T, TypeOnly>> :
    Array<TReferenceValue<T, TypeOnly>> | Domains | ToManyCommands;

class Domains {}
class ToManyCommands {}
class Upsert<T> {}

And I created this type for extracting T from TToMany and TToOne
export type ExtractOdooRelation<T> = (
        T extends TToMany<infer S> ?
            (
                Exclude<S, Domains | ToManyCommands> extends Array<infer S1> ?
                    S1 : 1
            ) : (
                T extends TToOne<infer R> ?
                    Exclude<R, Domains> : 2
            )
    ) extends TReferenceValue<infer R1, boolean> ?
        Exclude<R1, number | Upsert<T>> : 3
;

However it is not working as expected.
class StockMove {}

// I expect it resolves as type  StockMove but not never
const whyIsThisType_Never: ExtractOdooRelation<TToMany<StockMove, false>>;

What seems to be missing or wrong?

My goal is to write a type for autocompleting the object structure below
    class ResPartner {
        name: string;
    }

    class ResGroup {
        name: string;
    }

    class ProductProduct {
        name: string;
    }

    class StockMove {
        group_id: TToOne<ResGroup>;
        product_id: TToOne<ProductProduct>;
        partner_id: TToOne<ResPartner>;
    }

    class StockPicking {
        move_lines: TToMany<StockMove>;
    }

    // Developer should have Typescript type checking and autocomplete backed for writing this object
    await stockPickingFactory.deep_search_read<StockPicking>({
        move_lines: {
            read: ['group_id', 'product_id'],
            preload: {
                company_id: {
                    read: ['partner_id'],
                    preload: {
                        partner_id: {}
                    }
                },
            }
        }
    });

A: The correct type is
export type ExtractOdooRelation<T> =
    (
        T extends TToMany<infer S> ? (
            Exclude<T, Domains | ToManyCommands>
        ) : (
            T extends TToOne<infer S> ?
                Exclude<S, Domains> : never
        )
        // It is a bit weird that need to first infer R before infer Q in Array for TToMany
    ) extends TReferenceValue<infer R> ? (
        R extends Array<infer Q> ?
            Exclude<Q, number | Upsert<Q>> :
            Exclude<R, number | Upsert<R>>
    ) : never
;


text:
Q: Use scanf() to read an unknown number of integers in c I need to read an unknown number of rows, each containing an unknown number of integers, this number varying from row to row.
The integers are separated from each other by a single space and there is no space at the end of the line.
The output being the sum of all integers.
exemple input:
5
2 2
4 4 4
6 6
3 3

output:
39

A: The fact that the numbers are entered over several lines is actually irrelevant. Basically you just want to sum up numbers entered by the user until the input stream ends.
You probably want something like this:
#include <stdio.h>

int main() {
  int sum = 0;
  int number;

  while (scanf("%d", &number) == 1)
  {
    sum += number;
  }

  printf("Sum of all numbers is %d\n", sum);
}

End the input with Ctrl+D.
Example of execution:
1 2 3
4 5
6 7
8
Sum of all numbers is 36

Press Ctrl+D after entering 8.
Explanation of while (scanf("%d", &number) == 1)
scanf returns the number of items successfully scanned or EOF when the input stream ends. So here we decide to stop the loop if scanf returns anything else than 1 (meaning that the user has either pressed Ctrl+D triggering an EOF, or has entered something that is not a number (e.g. ABC).


text:
Q: IE Problem - jQuery append inside a table tag for each Ajax request I am appending some html inside a table tag while performing each Ajax request.I need to show the appended html immediatly after performing the ajax request.
It is working fine in FF, but in IE it shows the appended html only after completing all the ajax requests.
Following is the code
while(cond)

{

$.ajax({
                // other codes
                success: function(data) {
                    $('#tblPOUpdateResult tr:last').after(GetHtmlFromProblems(data));
                }
            });
}

function GetHtmlFromProblems(data) {

    var output = "";
    output = "
" + data.PurchaseOrderNumber + "	";

    if (data.Result.WasSuccessful == true) {
        output = output + "
 Sucess
	";
    }
    else {
        output = output + "
Failed
	";
    }

    if (data.Result.Problems.PurchaseOrderNotFound == true) {
        output = output + "Purchase order was not found";
    }

    if (data.Result.Problems.NoChangesToSave == true) {
        output = output + "There is no change to update
";
    }

    if (data.Result.Problems.PurchaseOrderIsForADifferentVendor == true) {
        output = output + "Purchase Order belongs to a different vendor
";
    }

    if (data.Result.Problems.PurchaseOrderIsNotDirectShip == true) {
        output = output + "Purchase Order is not Direct ShipSet
";
    }

    if (data.Result.Problems.LineIsNotForSpecifiedPart == true) {
        output = output + "Purchase Order Line is specified for different part
";
    }

    if (data.Result.Problems.QuantityReceivedExceedsQuantityOrdered == true) {
        output = output + "Quantity received exceeded quanity ordered
";
    }

    if (data.Result.HasAnyProblem == false) {
        output = output + "There is no problem
";
    }
    output = output + "
";

    return output;
}

Html Page:

                                    Purchase Order Number

                                    Status

                                    Problems

Any help is much appreciated :) I m using IE 7.

A: Try the table-layout property as given here:
http://msdn.microsoft.com/en-us/library/ms531161%28v=VS.85%29.aspx

You can optimize table rendering
  performance by specifying the
  tableLayout property. This property
  causes Windows Internet Explorer to
  render the table one row at a time,
  providing users with information at a
  faster pace.

HTH

A: I have found the solution myself.
The reason why append was not working was my jQuery ajax request was synchronous. i.e) I had set the async :false property in ajax function.
Once I removed the async property. It worked properly :)


text:
Q: How to keep the snakemake shell file while running in cluster While running my snakemake file in cluster I keep getting an error,
snakemake -j 20 --cluster "qsub -o out.txt -e err.txt -q debug" -s
seadragon/scripts/viral_hisat.snake --config json="<input file>"
output="<output file>"

Now this gives me the follwing error,
Error in job run_salmon while creating output file
/gpfs/home/user/seadragon/output/quant_v2_4/test.
ClusterJobException in line 58 of seadragon/scripts/viral_hisat.snake
:
Error executing rule run_salmon on cluster (jobid: 1, external: 156618.sn-mgmt.cm.cluster, jobscript: /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh). For detailed error see the cluster log.
Will exit after finishing currently running jobs.
Exiting because a job execution failed. Look above for error message

Now I don't find any way to track the error, since my cluster does not give me an way to store the log files, on the other hand /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh file is deleted immediately after finishing.
Please let me know if there is an way to keep this shell file even if the snakemake fails.

A: I am not a qsub user anymore, but if I remember correctly, stdout and stderr are stored in the working directory, under the jobid that Snakemake gives you under external in the error message.

A: You need to redirect the standard output and standard error output to a file yourself instead of relying on the cluster or snakemake to do this for you.
Instead of the following
my_script.sh

Run the following
my_script.sh > output_file.txt 2> error_file.txt


text:
Q: Building sample software with unicode I'm starting to develop a Windows service using the sample code provided by Microsoft. I've compiled the resource only DLL, but I'm getting errors when I build the first file provided here: https://learn.microsoft.com/en-us/windows/win32/services/svc-cpp
I'm getting several errors related to converting different string data types:
Here is an example line of code:
SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));

Which is producing this error:
E0167   argument of type "const wchar_t *" is incompatible with parameter of type "LPTSTR"

Here is another example:
SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));

It is producing this error:
E0144   a value of type "const wchar_t *" cannot be used to initialize an entity of type "LPWSTR"

And this one:
if (!GetModuleFileName("", szPath, MAX_PATH))

is producing this error:
C2664   'DWORD GetModuleFileNameW(HMODULE,LPWSTR,DWORD)': cannot convert argument 1 from 'const char [1]' to 'HMODULE'

My project is set to use the Unicode character set in the Project Properties dialog. I expected the sample code to build without problems, so I didn't want to go in and start converting or casting the variables to fix the problems. I feel like there must be a setting or something I need to change.
What is the best way to deal with these errors?


text:
Q: Grub not recognizing btrfs partition after Ubuntu installation Recently I've installed Ubuntu 20.04 (ext4). On the same disk was installed Linux Mint 19 (btrfs). I was able to mount partition, copy files, etc. It wasn't corrupted.
After installing Ubuntu grub was unable to recognise files of Linux Mint system and make record in boot menu. I was running grub from ubuntu terminal.

A: There's problem with mounting partition in Ubuntu. Btrfs partition is mounted not in / but /@/. There's need to add symbolic links to /@/etc/ and /@/bin/ by executing
ln -s /@/etc/ /etc
ln -s /@/bin/ /bin

After this simple solution Grub recognises btrfs recognises Linux Mint system and after update appaired in boot menu.


text:
Q: Mrecord shapes orientations and rankdir Is there any solution to not change the orientation of Mrecord shapes when the rankdir diagram attribute change ?
Here is a simple diagram example with the two outputs:
digraph g {
  rankdir=LR // or rankdir=TB

  node [shape=Mrecord]

  1 [label="{<in1>In[1]}|Node[1]|{<out2>Out[2]|<out3>Out[3]}"]
  2 [label="{<in1>In[1]}|Node[2]|{<out2>Out[2]|<out3>Out[3]}"]

  1:out3 -> 2:in1
}

Output with rankdir=LR:

Output with rankdir=TB:

I would like to have a rankdir=LR for the diagram, but with Mrecord shapes aspect as in the TB diagram... How can I do that ? With subgraph ? Or maybe with HTML-Like Labels (but they are more complex to use) ?
Other related question: record nodes and rankdir in graphviz

A: According to https://stackoverflow.com/a/20184005/938081, Putting {} around the label text will change the direction of the Mrecord separators. Example:

2 [label="{{<in1>In[1]}|Node[2]|{<out2>Out[2]|<out3>Out[3]}}"]

The result is the following (same code as previous post):


text:
Q: bash multiple heredocs et al I have a bash build script that I (well, Jenkins, but that's immaterial, this is a bash question) executes like this:
sudo -u buildmaster bash <<'END'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
END

Now I'd like to pass in a variable (Jenkins parameterized build), say PLATFORM. The trouble is that if I refer to $PLATFORM in my heredoc, it is undefined (I used 'END' to avoid variable substitution). If I turn the 'END' into END, my scripts becomes really unreadable with all the escapes I need to use.
So the question is, is there some (easy, readable) way of passing in two heredocs, one with quotes, and one without, into the same bash invocation? I was looking for something like this
sudo -u buildmaster bash <<PREFIX <<'END'
PLATFORM=$PLATFORM
PREFIX
# previous heredoc goes here
END

in the hope that it would simply concatenate, but I can't get the two heredocs to work (I guess bash is not Perl)
My fallback plan is to create temp files, but I was hoping there's a trick I don't know and that somebody could teach me :-)

A: In this case you could consider using bash with its -s argument:
sudo -u buildmaster bash -s -- "$PARAMETER" <<'END'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
PARAMETER=$1
END

(note that you have a syntax error, your closing END is quoted and shouldn't be).

There's another possibility (so that you have lots of options—and this one might be the simplest, if it applies) is to have your variables exported, and use the -E switch to sudo that exports the environment, e.g.,
export PARAMETER
sudo -E -u buildmaster bash <<'EOF'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
# you can use PARAMETER here, it's fine!
EOF

Along these lines, if you don't want to export everything, you may use env as follows:
sudo -u buildmaster env PARAMETER="$PARAMETER" bash <<'EOF'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
# you can use PARAMETER here, it's fine!
EOF

A: Substituted your quoted prefix into your unquoted full document:
# store the quoted part in a variable
prefix=$(cat <<'END'
ARGS=something
ARGS="$ARGS or other"
END
)

# use that variable in building the full document
sudo -u buildmaster bash <<END
$prefix
...
END


text: Q: Finite distance propagation for charged particles Usually, when it comes to studying QFT at a finite distance, the underlying problem is neutrino oscillations. Could it be relevant in some sense to study finite-distance propagation of charged particles, e.g., electrons or W-bosons? Are there physical scenarios for which the account of finite space-time regions is important?


text:
Q: Is there any API to add path.repo configuration to already running ElasticSearch Instances? I have single node Elasticsearch instance that has been running from about a month now. I need to start backing it up. But the backup-restore API need an entry in the elasticsearch.yml. I need to restart the ES to make it reflect that change. Is there any alternative to it? Is there anyway i can make an entry or pass the backup location as a parameter to the API so that i can run without restarting the ES instance?

A: Any settings update in path, path.repo or path.logs requires a whole cluster restart to apply those changes.


text:
Q: Best way to add support for a new subnet I currently have a network where all of the clients are served 192.168.0.0 subnet addresses with a subnet mask of 255.255.255.0.  Since I am running out of addresses to serve within that subnet, I would like clients to start being served 192.168.4.0 subnet addresses as well, but am unsure of the easiest way to do this.
My current thinking is that I should modify my DHCP server to start serving 192.168.4.0 addresses while modifying all subnet masks being served to 255.255.0.0.  However, I think I would have to go and change any static IP addresses that I have configured to use the new subnet mask in order to communicate with the new subnet.  Is there a way to add this new subnet without having to modify my already-existing static configurations for the 192.168.0.0 subnet?

A: I guess the short answer to this question is no.  I ended up doing some doing some cleanup and expanding the DCHP address range for the existing subnet, but if I want to add support for ranges outside of the subnet it looks like I'll have to manually change some subnet masks.


text:
Q: Where can I find Rails application directory on AWS? I deployed my rails application on AWS via Elastic BeanStalk and now I want to open that directory. What would be it's path?

A: Rails apps are deployed to /var/app/current/.


text:
Q: Why Linux mv command can operate both file and directory whitout option -r? rm and cp command should use option -r to distinguish file and directory. I think it means that they operate file and directory in a different way? However, mv command dosen't need it. This my problem. I want to understand how they work and their differences.And also, i want to know where do I go to find the answer the next time I have a similar problem?
My english is poor. Please forgive me if there are any mistakes.
Any answer maybe helpful. Thanks.

A: You may picture a directory as a "list" of what it actually contains (rather than a physical folder).
When you move a directory to another place using mv, you simply need to move the reference to this list on the disk, the content remaining unchanged.
rm and cp, however, need to browse this list because each item inside it need to be processed individually. Thus the -r if they contain subdirectories.

A: If you have files in your folder and you want to copy or move it, you need to do the -r. It means recursive, it copys/moves the folder and also the files inside the folder.
When you have a folder without any files inside, you don't need to put that -r in the code, because the folder is empty.


text:
Q: Gromov–Hausdorff closure of non-positively curved graphs Setup:
Let $\Gamma$ be the set of non-positively curved weighted connected graphs, with finitely many points, which are isometrically embedded in $\mathbb{R}^n$; for some $n\in \mathbb{N}$;$n\geq 2$.  Thus, an element $\gamma$ of $\Gamma$ is a triple $(E_{\gamma},V_{\gamma},W_{\gamma})$ where $E_{\gamma}$ and $V_{\gamma}$ are respectively finite sets of edges and vertices and where the weights $W_{\gamma}:V_{\gamma}\rightarrow \mathbb{R}$ satisfy: there exists some $\delta>0$ such that:
$$
\min_{e\in E_{\gamma}}\, \min_{v \in V_{\gamma}(e)} W_{\gamma}(v)>\delta;
$$
where $V_{\gamma}(e)$ denotes the set of vertices in $V_{\gamma}$ which are adjacent to $e$.
We make $\gamma$ into a metric space by equipping it with the usual graph distance:
$$
d_{\gamma}(e,\tilde{e}) := \min_{[x]} \sum_{[x]} \, W_{\gamma}(x)
,
$$
where the infimum is taken over all sequences $[x]:=(e,\dots,\tilde{e})$ of vertices beginning with $e$ and terminating at $\tilde{e}$.

Background:
We note that, on page 4 (d) of Ballmann - Lectures on spaces of nonpositive curvature, any such $\gamma$ is a metric space of non-positive curvature.
This is because:

*

*It is geodesic,

*For any $e_1,e_2,e_3 \in \gamma$ we have:
$$
d_{\gamma}(e_1,m) \leq \sqrt{2^{-1}d_{\gamma}^2(e_1,e_2)+ 2^{-1}d_{\gamma}^2(e_1,e_3) - 2^{-2}d_{\gamma}(e_2,e_3)}
.
$$

Question:
My question is:  What is the closure of $\Gamma$ in the Gromov–Hausdorff space of embedded compact metric subspaces of $\mathbb{R}^n$?  For example, does it contain all non-empty compacts subsets of $\mathbb{R}^n$?


text:
Q: Move a polygon to a different place on the globe, while maintaining its true geographical size? (QGIS) I'm trying to do something similar to the Greenland vs Africa comparison -- superimpose one country over another, showing how their true sizes compare (the example on the right).

Thought this would be a simple thing to do, but now that I am trying to do it, I'm having a hard time figuring it out. Is there a simple way to do this, ideally using Qgis?

A: you should project your data into an equal area projection (e.g. cylindrical equal area, EPSG:9835). Then you can move your polygon to another place in order to illustrate the size difference. After saving your edit, you can project back to Mercator so that the shape of Africa (or your other country of interest) is the same.

A: You can achieve this visually in a Print Layout without manipulating your data.

*

*Create two maps in print layout. Center one map on country 1, and the other map on country 2. Change the item Id of each map to the name of the country in that map.

*Move the front map on top of the back map, and resize one of the map so they're the same size. Turn off the background for the front map. Set both maps to the same scale.

*Set the CRS of both maps to an equal area projected coordinate system. Note that the scale of the map item may change when you change the CRS, so make sure to change it back so both maps are at the same scale.

*

*Here's what Africa and Greenland look like with both maps in EPSG:54036 World_Cylindrical_Equal_Area.

Looks terrible, right? That's because Greenland is really close to the North Pole, and Africa is centered on the Equator. They're never going to look good in the same projection.

*In cases where the two countries are at very different latitudes, and/or one of them is close to a pole, they won't look "right" in the same projection. Change the CRS of each map to a projection centered on the country in that map. Ideally these would be similar types of projections, eg both Albers equal area conic. Unfortunately in the case of Greenland, the options are quite limited. Try out some different combinations, and see what you're happy with.

*

*Here's what Greenland and Africa look like in EPSG:5938 WGS 84 / EPSG Greenland Polar Stereographic and EPSG:102022 Africa_Albers_Equal_Area_Conic, respectively:

*Here's what Greenland and Africa look like with the Greenland map changed to EPSG: 3574 WGS 84 / North Pole LAEA Atlantic, and Africa still in Africa_Albers_Equal_Area_Conic:

A: I suggest you save as, the shape that you want to move as a new shapefile and move it however ever you want. However, have the original shapefile that is not moved. Having separate shapefiles allows you to maneuver the shape and save your edits without tampering with the original and correct dataset.

A: You can move around the globe many countries here
https://thetruesize.com/


text:
Q: Android: BLE clear cancel autoConnect In my application I use auto connect to connect the BLE device as soon as it is available.
How I can cancel the autoConnect when I want
My Code for the auto connect:
bluetoothAdapter.getRemoteDevice(macAddress).connectGatt(this, true, callBack)

And how cancel it?

A: You just call disconnect() on the returned BluetoothGatt object.
If you don't need the BluetoothGatt object anymore, call close() to free resources in the Bluetooth stack.


text:
Q: clients connecting to TCP iterative server even after backlog queue is full Here's an iterative server I've created to handle basic client-server chat application.
I am trying to run TCPserver on a terminal window and TCPclient on multiple terminal windows.
More than 5 the clients are getting connected(neither getting blocked nor failing. They immediately connect successfully) despite of the fact that I set the backlog value (listen system call) in server socket to be 5.
I expected that no more than 5 clients could be connected(only 1 would be accepted at a time).
Is my understanding of the backlog value set in the listen system call wrong?
Please clarify.

int listen(int sockfd, int backlog);
The backlog argument defines the maximum length  to  which  the queue of pending connections for sockfd may grow.

Here are the actual programs for reference.
TCPserver.c
#include<stdio.h>
#include<stdlib.h>

#include<sys/types.h>
#include<sys/socket.h>

#include<netinet/in.h>
#include<unistd.h>
#define BACKLOG 5

#include <netinet/in.h>
#include <arpa/inet.h>

#include<string.h>

int main()
{
    //create the server socket
    int sd;
    sd=socket(AF_INET,SOCK_STREAM,0);
    if(sd==-1)
    {
        perror("Some error occured in creating the socket: ");
        //Interprets the value of errno as an error message, and prints it to stderr
        exit(EXIT_FAILURE);
    }
    else
        printf("Socket created!\n");

    //define the server address
    struct sockaddr_in server_address;

    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(9002);
    server_address.sin_addr.s_addr = INADDR_ANY;
    //inet_addr("192.168.137.163");//INADDR_ANY;

    //bind the socket to our specified IP and port
    int bind_status = bind(sd, (struct sockaddr *) &server_address, sizeof(server_address));
    if(bind_status == -1)
    {
        perror("An error occurred in binding the socket: " );
        exit(EXIT_FAILURE);
    }
    else
        printf("Bind Successful!\n");

    //listen for connections
    int listen_status = listen(sd, BACKLOG);
    if(listen_status == -1)
    {
        perror("Error occured in listening: ");
        exit(EXIT_FAILURE);
    }
    else
        printf("Server is listening!\n");

    while(1)
    {
        //Accept a connection and create a new socket for this connection
        int new_sd;
        struct sockaddr_in client_address;
        int client_address_size = sizeof(client_address);

        new_sd= accept(sd, (struct sockaddr*) &client_address, &client_address_size);
        if(new_sd==-1)
        {
            perror("Can't accept connection: ");
            exit(EXIT_FAILURE);
        }
        else
            printf("Accept successful!\nA new client has connected. He'll soon send you a message.\n (You can chat or say \"exit\" to stop chatting)\n\n");

        //send a message to the client
        char buffer[256] = "Welcome to the server, lets chat! \n (You can chat or say \"exit\" to stop chatting)\n";
        send(new_sd,buffer,sizeof(buffer),0);

        //start chat
        while(1)
        {
            memset(buffer,0,256);
            int n = recv(new_sd, buffer, sizeof(buffer),0);
            if(n==-1 || strcmp(buffer,"exit\n")==0 || strcmp(buffer,"exit")==0)
                break;
            printf("\nclient said: %s\n",buffer);

            memset(buffer,0,256);
            printf("Say something: ");
            fgets(buffer,256,stdin);
            n = send(new_sd, buffer, sizeof(buffer), 0);
            if(n==-1 || strcmp(buffer,"exit\n")==0)
                break;
        }

        //close the sockets
        close(new_sd);
        printf("\nConnection ended. waiting for new connection now . . .\n");
    }

    close(sd);

    return 0;
}

and Here's the client
TCPclient.c
#include<stdio.h>
#include<stdlib.h>

#include<sys/types.h>
#include<sys/socket.h>

#include<netinet/in.h>

#include<unistd.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include<string.h>
int main()
{
    //create the socket
    int sd = socket(AF_INET,SOCK_STREAM,0);

    if(sd==-1)
    {
        perror("Some error occurred in creating the socket: ");
        exit(EXIT_FAILURE);
    }
    else
        printf("Socket created!\n");

    //specify an address for the socket
    struct sockaddr_in server_address;

    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(9002);
    server_address.sin_addr.s_addr = inet_addr("127.0.0.1");//INADDR_ANY;

    //Connect to the server
    int connection_status = connect(sd,(struct sockaddr *) &server_address, sizeof(server_address));

    if(connection_status == -1)
    {
        perror("There was an error connecting to the remote socket: ");
        exit(EXIT_FAILURE);
    }
    else
        printf("Connected to the server! Waiting in the queue for the server to accept the connection...\n");

    char buffer[256];
    //get the connection message from the server
    recv(sd, &buffer, sizeof(buffer), 0);
    printf("Server Said: %s\n", buffer);

    //start chat
    while(1)
    {
        memset(buffer,0,256);
        printf("Say something: ");
        fgets(buffer,256,stdin);
        int n = send(sd,buffer,sizeof(buffer),0);
        if(n==-1 || strcmp(buffer,"exit\n")==0)
            break;

        memset(buffer,0,256);
        n = recv(sd,buffer,sizeof(buffer),0);
        if(n==-1 || strcmp(buffer,"exit\n")==0)
            break;

        printf("\nServer said: %s\n",buffer);
    }

    //close the socket
    close(sd);

    return 0;
}

Someone suggested I check if syncookies have been enabled on my system. When I perform cat /proc/sys/net/ipv4/tcp_syncookies, I get 1.

A: The backlog is the "queue of pending connections" -- once you accept a connection, it is no longer pending, and comes off the queue, leaving room for 5 more pending connections.
If you want to limit to 5 connections, then you need to count how many you have accepted (and not closed). Any more attempts to connect would then wait in the queue.

A: Your system has enabled SYN cookies, which allows the TCP stack to behave as if it has a very large listen queue. It was designed to mitigate DOS via SYN flooding.
The listen man page states about the backlog argument:

When syncookies are enabled
         there is no logical maximum length and this setting is ignored.

If you really want no more than 5 pending clients to wait on the server, you will have to manually maintain your own queue, and close new connections if your queue is full.
Note that this solution does not actually affect the behavior of the operating systems listen queue. The solution is to continually clear the listen queue of any backlog and close those connections if your server already has 5 pending connections in its own queue.
Probably in your case, the easiest way to achieve that is with two threads. One doing the accepting, the other handling connections off the queue.
The fragment below illustrates this in pseudo-code. It assumes proper thread mutual exclusion and signaling is performed by the queue operations.
accepting_thread () {
    int queue_count = 0;

    for (;;) {
        new_conn = accept();
        if (q_size(q) < 5) {
            q_enqueue(q, new_conn);
        } else {
            close(new_conn);
        }
    }
}

handling_thread () {
    for (;;) {
        new_conn = q_dequeue(q);
        /* ... */
        close(new_conn);
     }
}

To get clients that are terminated early to see a reset, you can enable the linger option with a 0 timeout value. Most TCP stacks will cause a RST to be generated when the socket is closed.


text:
Q: Time Complexity of finding a basin The following algorithm is used to find a basin in matrix. The whole question is as follows:

2-D matrix is given where each cell represents height of cell. Water
  can flow from cell with higher height to lower one. A basin is when
  there is no cell with lower height in the neighbours
  (left,right,up,down,diagonal). You have to find maximum size basin
  block.

I have implemented the code. I am looking for timeComplexity. In my opinion time complexity is O(n * m) where n and m is the row and column of the matrix. Please verify.
public final class Basin {

    private Basin() {}

    private static enum Direction {
        NW(-1, -1), N(0, -1), NE(-1, 1), E(0, 1), SE(1, 1), S(1, 0), SW(1, -1), W(-1, 0);

        private int rowDelta;
        private int colDelta;

        Direction(int rowDelta, int colDelta) {
            this.rowDelta = rowDelta;
            this.colDelta = colDelta;
        }

        public int getRowDelta() {
            return rowDelta;
        }

        public int getColDelta() {
            return colDelta;
        }
    }

    private static class BasinCount {
        private int count;
        private boolean isBasin;
        private int item;

        BasinCount(int count, boolean basin, int item) {
            this.count = count;
            this.isBasin = basin;
            this.item = item;
        }
    };

    /**
     * Returns the minimum basin.
     * If more than a single minimum basin exists then returns any arbitrary basin.
     *
     * @param m     : the input matrix
     * @return      : returns the basin item and its size.
     */
    public static BasinData getMaxBasin(int[][] m) {
        if (m.length == 0) { throw new IllegalArgumentException("The matrix should contain atleast one element."); }

        final boolean[][] visited = new boolean[m.length][m[0].length];
        final List<BasinCount> basinCountList = new ArrayList<>();

        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                if (!visited[i][j]) {
                    basinCountList.add(scan(m, visited, i, j, m[i][j], new BasinCount(0, true, m[i][j])));
                }
            }
        }

        return getMaxBasin(basinCountList);
    }

    private static BasinData getMaxBasin(List<BasinCount> basinCountList) {
        int maxCount = Integer.MIN_VALUE;
        int item = 0;
        for (BasinCount c : basinCountList) {
            if (c.isBasin) {
                if (c.count > maxCount) {
                    maxCount = c.count;
                    item = c.item;
                }
            }
        }
        return new BasinData(item, maxCount);
    }

    private static BasinCount scan(int[][] m, boolean[][] visited, int row, int col, int item, BasinCount baseCount) {

        // array out of index
        if (row < 0 || row == m.length || col < 0 || col == m[0].length) return baseCount;

        // neighbor "m[row][col]" is lesser than me. now i cannot be the basin.
        if (m[row][col] < item) {
            baseCount.isBasin = false;
            return baseCount;
        }

        // my neighbor "m[row][col]" is greater than me, thus not to add it to the basin.
        if (m[row][col] > item) return baseCount;

        // my neighbor is equal to me, but i happen to have visited him already. thus simply return without adding count.
        // this is optimisitic recursion as described by rolf.
        if (visited[row][col]) {
            return baseCount;
        }

        visited[row][col] = true;
        baseCount.count++;

        for (Direction dir : Direction.values()) {
            scan(m, visited, row + dir.getRowDelta(), col + dir.getColDelta(), item, baseCount);
            /**
             *  once we know that current 'item' is not the basin, we do "want" to explore other dimensions.
             *  With the commented out code - consider: m3
             *  If the first 1 to be picked up is "1 @ row2, col4." This hits zero, marks basin false and returns.
             *  Next time it starts with "1 @ row 0, col 0". This never encounters zero, because "1 @ row2, col4." is visited.
             *  this gives a false answer.
             */
//            if (!baseCount.basin) {
//                System.out.println(baseCount.item + "-:-:-");
//                return baseCount;
//            }
        }

        return baseCount;
    }

A: Yes, your code (assuming it works; I have not tested it) is O(n * m) in time, and O(n * m) in space.
Complexities cannot be lower than O(n * m), since any cell can be a part of a neighbouring max-basin in the general case, and all must therefore be (in general) examined. Your complexity is O(n * m) due to the two nested for-loops in getMaxBasin, and the fact that visited[i][j] can only be set at a single place (inside scan()), and prohibits later visits of the same cell.
Due to recursion, every time you chain a call scan(), you are adding to the stack. With a sufficiently-long chain of scan() calls, you could run into stack limits. The worst-case scenario is a zig-zag pattern so that the stack ends up containing a scan() call for each an every cell.


text:
Q: Using Jsoup, select the element that comes after a text An HTML page is something as follows:
bananas
<myTag ...> ... </myTag>

The myTag tag does not have an id or name. How can I select it, given only the information that it comes after the text bananas?
Sure you can select the tag by counting the placement order of all myTag elements, but I am asking the cleanest way in the case of no id or name or any other attribute.

A: Here are some options I can see:
Option 1: Use CSS query
The Jsoup CSS engine doesn't permit text node selection. However, you can use this option if and only if myTag and bananas have the same parent element.
:containsOwn(bananas) > myTag

DEMO
DESCRIPTION
:containsOwn(bananas) /* Select any element (1) having a TextNode as direct
                         child containing bananas */
> myTag               /* Select child elements of (1) with tag name myTag */

Option 2: Visit all nodes
This option involves more code writing. You can act in three steps:

*

*Visit manually each node in the document (see NodeVisitor).

*IF a TextNode is found and contains bananas
THEN move to 3.
ELSE visit next node.

*IF TextNode has a sibling node with name myTag
THEN a myTag node has been found; visit next node
ELSE visit next node.


text:
Q: Write a search result of a data frame into a new column I guess that this is one of the easiest tasks, but I have no idea how to do it.
I have a data.frame with a lot of data, a receipt number with an account number to which it was expensed.
ACCOUNT RECEIPT
10000   2121
12000   1515
21000   2121
50200   1515
47500   1474
90000   1474

I now want to search for the first receipt number and list all account numbers in a new column. I am currently not sure if the result should also list the account of the current receip, because one can see it anyway.
ACCOUNT RECEIPT RESULT
  10000    2121 21000
  12000    1515 50200
  21000    2121 10000
  50200    1515 12000
  47500    1474 90000, 140000
  90000    1474 47500, 140000
 140000    1474 47500, 90000

I really like to use dplyr, maybe it is already possible to do it with it, I just can't see the solution..

A: I don't think you need multiple rows for each RECEIPT in your final table.
I'd propose this solution
library(dplyr)

dt = read.table(text="ACCOUNT RECEIPT
10000   2121
12000   1515
21000   2121
50200   1515
47500   1474
90000   1474", header=T)

dt %>%
  group_by(RECEIPT) %>%
  summarise(ALL_ACCOUNTS = paste(ACCOUNT, collapse = ", "))

# # A tibble: 3 x 2
#   RECEIPT ALL_ACCOUNTS
#     <int>        <chr>
# 1    1474 47500, 90000
# 2    1515 12000, 50200
# 3    2121 10000, 21000

Where, as you mentioned, you get one row for each RECEIPT value and then all corresponding ACCOUNT values.
To achieve exactly what you mentioned in your question try this
library(dplyr)

dt = read.table(text="ACCOUNT RECEIPT
                10000   2121
                12000   1515
                21000   2121
                50200   1515
                47500   1474
                90000   1474
                140000  1474", header=T)

dt %>%
  left_join(dt, by="RECEIPT") %>%            # join same dataset to get all combinations of accounts
  filter(ACCOUNT.x != ACCOUNT.y) %>%         # filter out cases with same account numbers
  group_by(ACCOUNT.x, RECEIPT) %>%           # group by pairs of first account number and receipt
  summarise(REST_ACCOUNTS = paste(ACCOUNT.y, collapse = ", ")) %>%   # combine rest of account numbers
  ungroup() %>%                              # forget the grouping
  arrange(RECEIPT) %>%                       # order by receipt (only if needed for better visualisation)
  rename(ACCOUNT = ACCOUNT.x)                # change the name (only if needed for better visualisation)

# # A tibble: 7 x 3
#   ACCOUNT RECEIPT REST_ACCOUNTS
#     <int>   <int>         <chr>
# 1   47500    1474 90000, 140000
# 2   90000    1474 47500, 140000
# 3  140000    1474  47500, 90000
# 4   12000    1515         50200
# 5   50200    1515         12000
# 6   10000    2121         21000
# 7   21000    2121         10000


text:
Q: Amazon Elastic Beanstalk: Can multiple applications share a single Amazon RDS database instance? When creating an application in Amazon Elastic Beanstalk, you have the option of creating a new Amazon RDS database instance.  Is it possible to associate an existing RDS database instance with an Elastic Beanstalk application?

A: If you want to share an RDS instance between multiple applications, the best thing to do is set that up independent of your beanstalk application.
Set up privs for each application and configure each application to use the RDS instance.
You will probably have to manually configure your application security group to access the database instance.

A: I was facing same issue and fixed using following steps :
1) Go to EC2 instance and note your security group example "sg-121212121212"
2) Go to RDS Security Group ad=nd inbound traffic
3) Edit rule select all traffic and add your new ebs security group "sg-121212121212"
Hope it will helpful

A: A single database can only be used with one Elastic Beanstalk environment. Although, it can be moved between environments.
Also important to remember that a clone operation doesn't clone the database.


text:
Q: using offsetTop with AngularJS ng-repeat I am using ng-repeat to output a paragraph by repeating individual letters into a span element.

hi Ms

The content of these letters spans will be multiple lines in the paragraph.
line one of letters
even more letters here
and a few more

My end goal is to be able to detect which spans are on which line in order to style them differently.
My thought is to use the offsetTop value of each of the spans in order to detect the different lines. So, in the above answer I would have three different offsetTops.
I'm running into some problems when creating a directive to do this (based on this question). What's happening, is I'm getting many more offsetTops for values that should be in the same line.
Here's a Code Pen of me working through this problem in Angular.
Just to prove to myself that this could be done, I did it without Angular here.
In these pen's I'm console logging the top value and there should be as many tops as there are lines.
This is my first (real) time making a directive, so I'm wondering if I'm just not using element properly.
Any direction would be helpful, thanks for helping!

A: One big difference between how you are doing it without Angular is that you are running that logic after everything has rendered, but with Angular the directive is firing off on each span the moment that span gets rendered. I believe this is why you are seeing the top continually give you different values.
If you add a timeout to the directive it will wait until the DOM has completed rendering before running the function inside the timeout.
myApp.directive('positioner', function($timeout) {
return {
  restrict: 'A',
  link: function($scope, element){

    $timeout(function(){
        var top = element[0].offsetTop;
        var height = element[0].offsetHeight;

        console.log(top);
    }, 0);
  }
};

Using just this timeout of zero gives me 3 distinct top values.


text:
Q: the VM is running with native name encoding of latin1 which may cause Elixir to malfunction as it expects utf8 How to solve this warning being prompted every time I execute Elixir code or enter iex?

warning: the VM is running with native name encoding of latin1 which may cause Elixir to malfunction as it expects utf8. Please ensure your locale is set to UTF-8 (which can be verified by running "locale" in your shell)

$ locale
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=en_US.utf8
LANGUAGE=en_US:
LC_CTYPE=UTF-8
LC_NUMERIC="en_US.utf8"
LC_TIME="en_US.utf8"
LC_COLLATE="en_US.utf8"
LC_MONETARY="en_US.utf8"
LC_MESSAGES="en_US.utf8"
LC_PAPER="en_US.utf8"
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT="en_US.utf8"
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04 LTS
Release:        14.04
Codename:       trusty

A: On centOS 7 the following worked for me:
localedef -c -f UTF-8 -i en_US en_US.UTF-8
export LC_ALL=en_US.UTF-8

Should work for most if not all RHEL distributions. Cheers!

A: I encountered this when using a docker image. Adding the following line to my Dockerfile solved this:
ENV LANG=C.UTF-8

A: This happens when you SSH from your Mac laptop to a Linux server (including a virtual Linux server running on your laptop). SSH forwards the LANG and LC_* environment variables from the local shell to the remote shell, and some of the values used on the Mac are not valid on the Linux server.
The problem can be fixed in various ways, including installing the missing locales on the server. I recommend simply disabling the SSH environment forwarding, either on the server (remove AcceptEnv in /etc/ssh/sshd_config) or on the laptop (remove SendEnv in /etc/ssh/ssh_config).
Read more in How to fix a locale setting warning from Perl?

A: Apparently unset LC_ALL= was the issue, I checked
$ cat /etc/default/locale
LANG="en_US.utf8"
LANGUAGE="en_US:"

ensuring LC_ALL is missing, to fix it, I executed:
$ sudo update-locale LC_ALL=en_US.UTF-8

this command added LC_ALL to /etc/default/locale file:
$ cat /etc/default/locale
LANG="en_US.utf8"
LANGUAGE="en_US:"
LC_ALL=en_US.UTF-8

and error is gone.

A: in the nix-shell this command helped me:
export LOCALE_ARCHIVE=/usr/lib/locale/locale-archive

ref: https://nixos.wiki/wiki/Locales

A: I'm using erlang inside a docker container and the other solutions didn't cut it. The command update-locale may not be available inside a docker ubuntu container, so I've stole some code that installs it from https://hub.docker.com/r/voidlock/erlang/~/dockerfile/.
apt-get update && apt-get install -y --no-install-recommends locales
export LANG=en_US.UTF-8 \
    && echo $LANG UTF-8 > /etc/locale.gen \
    && locale-gen \
    && update-locale LANG=$LANG

A: For me setting the locale in my init script /etc/init/my_start_script.conf did the trick
env LC_ALL=en_US.UTF-8
export LC_ALL

A: sudo dpkg-reconfigure locales

on Ubuntu 18.04.5 LTS did it!


text:
Q: Downsides of Extending a USB Bluetooth Antenna? I found an interesting video about how to extend the range on a USB Bluetooth antenna by resoldering a new antenna in its place: (https://www.youtube.com/watch?v=cwKWOdOHiWY).
I'm planning on using a Bluetooth enabled portable EEG as a input device for an arts display in a few months, and I'm somewhat concerned about interference from the audience's Bluetooth enabled phones.
The performer wants to be able to walk around the audience as a part of the performance, which might be about 20m from the stage where the computuer will be located.
What are the potential downsides of this approach? Is the extension antenna more prone to interference? Is it a good application for this kind of project? Is it better to have the extended antenna mounted on the ceiling near the center of the room?


text:
Q: FTP upload from an in-experienced developer Hoping you can help. I am in the very early days of developing a website and have learnt the basis of HTML and CSS.
I have uploaded my code via an FTP client, but I cannot see the pictures. I have copied across into a folder next to the .html files, but they do not show on the web.
Fully appreciate that this is likely to be an easy question to answer, but can anyone help to explain where I am going wrong?
Code - https://jsbin.com/vaxeqofota/1/edit?html,css,output
Thanks
Lewis


text:
Q: How do I reinstate the "Add Block" feature that changes with the update? When a new line was passed in the text editor, the + came up as follows and it was possible to choose what to add. Now this is just working at the end of the page so it is not possible to add it easily. How do I make every blank row appear?
Exactly where it was supposed to appear?

An image of the menu that will appear.


text:
Q: How to always show keyboard in pageviewcontroller I want to always display keyboard in all views in pageviewcontroller.
All views have uitextfield and I coded becomefirstresponder in viewdidload so the keyboard appears.
But problem is that when i set new viewcontroller or swipe in pageviewcontroller the keyboard disappears and re-appears.
Can I always show keyboard?
Thanks.

A: Go simple.. set invisible textfield (means hidden one)! Set that as a first responder basically, this text field should be in base view controller means out of page view. as soon as you swipe the page shift responder to the required text field. hence it will not disappear and appear on page shift.

A: UITextField resigns as first responder on any tap/swipe gesture. You need to handle it in your scrollview delegate method when you detect the scroll ended and then set the current page view controller's UITextField as first responder.


text:
Q: Tax calculation in vba, run type error '13' type mismatch Option Explicit

Private Sub Workbook_Open()

Dim Salary As Double
Dim Income As Double
Dim Tax As Double
Dim SalaryAfterTax As Double
Dim strOutput As String

Salary = InputBox("Please indicate your salary", "Salary Calculation")

Income = CDbl(Salary)

Select Case Income
Case Is >= 151000
     Tax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (150000 - 37400) * 0.5 + (Salary - 150000) * 0.5

Case Is >= 37401
     Tax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (Salary - 37400) * 0.4

Case Is >= 2441
     Tax = 2440 * 0.1 + (Salary - 2440) * 0.2

Case Else
     Tax = 2440 * 0.1

End Select

SalaryAfterTax = Income - Tax

strOutput = "Your salary after tax is" & SalaryAfterTax

MsgBox strOutput, "Final Salary"

End Sub

A: Change:
MsgBox strOutput, "Final Salary"

To:
MsgBox strOutput, vbOKOnly, "Final Salary"

Or:
MsgBox Prompt:=strOutput, Title:="Final Salary"

You are trying to put a string in where a button type is supposed to be.


text:
Q: Пауза в выполнении функции C# Занимаюсь созданием эмулятора консоли. Поле ввода сделано как TextBox и команды обрабатываются по событию PreviewKeyDown текстбокса (по нажатию Enter). После обработки команда должна выдавать строковый результат и выводить его в textBox. Все бы было ничего, если бы не появилась необходимость создать тип команд, который требует дополнительного пользовательского ввода, например, некоторые команды должны требовать определенных привилегий, сокрытых админским паролем.
Вот упрощенный вид того, что я пытаюсь сделать:
private string expectUserInput( string inviteString ) {
    CLI_TextBox.Text += "\r\n" + inviteString;
    CLI_TextBox.CaretIndex = CLI_TextBox.Text.Length;

    return "some result";
}

private string enable( ) {
    string password = expectUserInput("Password: ");
    // If password is correct - do some staff;
    return "someStaffResult";
}

private void CLI_TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        string result;
        string lineContent = CLI_TextBox.GetLineText(CLI_TextBox.GetLastVisibleLineIndex());
        if (lineContent == "enable") {
            result = enable();
        }

    }
    else if (e.Key == Key.Up || e.Key == Key.Down)
    {
        e.Handled = true;
    }
}

Моя задумка (ну или по крайней мере гипотетическая идея) заключается в том, что бы сделать функцию expectUserInput() как бы ожидающей определенного события (в моем случае это опять же нажатие на клавишу Enter, но правда на это событие уже есть свой обработчик), и пока это событие не наступит, она не выполнится, и не выполнится enable(). Перелопатил гугл, но так решения и не нашел. Понял только, что копать нужно в сторону async/await и генерации собственных событий (возможно), но как это применить в данной ситуации не совсем пойму. Возможно кто-нибудь сталкивался с подобной проблемой и находил успешное ее решение?

A: не совсем понял вопрос. но возможно вам поможет то что я недавно нашёл. можно ожидать определённого действия без блокировки основного потока
DispatcherFrame frame = new DispatcherFrame();
//здесь подписываетесь на какое-либо событие и ожидаете
Dispatcher.PushFrame(frame);

//в теле обработчика после определённых действий продолжаете выполнение программы
frame.Continue = false;


text:
Q: AngularJS: How to use $index inside ng-repeat I have such ul:

            {{availableAlphaName.Name}}

data-original-index must have index value. But if I set data-original-index to $index it will be always 0 because every instance gets its own scope.
Please, help to resolve this issue.

A: You should specify track by $index within the ng-repeat

            {{availableAlphaName.Name}}


text:
Q: VLAN tagging for non VLAN compliant devices Okay so I'm a little new to VLANS, so forgive me if this is a silly question. I have a firewall set up with a few VLANS:
ID 1: This is the primary, and set to untagged. This will be used as a management VLAN ID 30: 'Guest' for the less trusted devices ID 40: 'iot' for our it devices. I wan them segregated for QOS and security reasons ID 50: 'Trusted' for staff to access specific resources on the LAN.
My question is this. The majority of devices connecting to VLAN 30 and 50 will be standard workstations, with NICs that don't understand VLAN tagging. If I set port-based VLAN, I still have to have it as a tagged VLAN, as that's how it's set on the firewall (The firewall is running a 'bridge' port to pipe all 4 VLANS over to the layer 2 switch), and of course, will only allow one of those VLANS to come back untagged. If I set it as a tagged VLAN, the workstation doesn't understand it and gives a 169 IP. if I set it to an untagged, same deal - I assume as the firewall is only expecting tagged traffic from those VLANS. What am I missing here?
Context: My firewall is a Watchguard, my switch is an HP Aruba

A: There is a few things that aren't quite clear here in the question, and comments, so I'm hopefully going to clear up how I would expect a system link this to work (with hp aruba switches).
On the link between the firewall and the switch (the configuration on both sides):
Have VLAN 1 configured as untagged.
Have VLAN 30/40/50 configured as tagged.
On the switch ports that are leading to 'guest' devices, you would configure those ports as 'untagged' on VLAN 30.
Assuming the ports for 'guest' are ports 1-10 (and the firewall is port 50), the commands would be something like:
vlan 30
name Guest
tagged 50
untagged 1-10
exit

The same goes for ports used by trusted staff, these would be 'untagged' on VLAN 50.
The command untagged, basically means: Any traffic arriving on a port that is not otherwise tagged, will be assigned this VLAN.


text:
Q: Ingesting to ElasticSearch a json file using curl I have the following error when I try to ingest a json file
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}},"status":400}

My file is like this:
   [{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
},
{
"name":"John2",
"age":30,
"cars":[ "Ford2", "BMW2", "Fiat2" ]
}]

It works if I only have one record not more than one.
The curl command is like this:
curl -XPOST localhost:9200/cars/doc/1 -H "Content-Type: application/json" -d @cars.json


text:
Q: Serving static html files to a meteor template using Iron Router I've recently set up a meteor website and am really loving how easy it is to build templates from data in my mongo db.
One part of my website I just want to render a static html file in my layout template I've setup. At the moment I have a layout file that looks like this
<template name="mainLayout">

    {{> yield region="navBar"}}

    {{> yield}}

    {{> yield region="footer"}}

</template>

All I want to do is when I hit a specific route instead of finding a template and filling it with data from the db I just want to insert a static html page into that main part of my layout.
Is this possible or do you have any suggestions on other ways to solve this?
I can't think of a way to standardise what I have in these html files so they all fit one template so its much easier to just serve them as static pages.


text:
Q: GDAL undefined reference Qt С++ Скачал библиотеку GDAL с помощью OSGeo4W, пробывал через MinGW несколько раз, не получалось.. Подключил в .pro файл библиотеку, не знаю правильно ли, но вроде работает:
INCLUDEPATH +=  "C:\OSGeo4W64\include"
LIBS += C:\OSGeo4W64\lib\gdal_i.lib

Затем в main, пытаюсь выполнить одну функцию и получаю ошибку "undefined reference".
#include <QCoreApplication>
#include "gdal.h"
#include "gdal_priv.h"
using namespace std;

int main(int argc, char *argv[])
{
     QCoreApplication a(argc, argv);
     GDALAllRegister();

     return a.exec();
 }

Что делать подскажите?


text:
Q: swift package --verbose generate-xcodeproj giving error: reachedTimeLimit I'm attempting to generate an Xcode project and am getting:
error: reachedTimeLimit
Unfortunately I don't see a lot of help googling this error nor does there appear to be a way to extend whatever the current time limit is from the command line.
Any ideas?

A: There is a hardcoded 10 second time limit for package resolving baked into SPM - see the code in DependencyResolver.swift.
Line 1365 has let timeLimit = 10, and there is no way of changing this externally, except of course building your own version of SPM with a higher timeout.
I haven't dug deep enough into the resolver algorithm, but it seems that your dependency tree is pretty complex for the resolving to take so long.


text:
Q: Unsupported URL on ios 8 I'm trying to fetch a json from google places with the following code:
NSString *query = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%@&sensor=true&key=%@", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY];
NSLog(@"%@",query);
NSURL *googleRequestURL=[NSURL URLWithString:query];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Error fetching data: %@",[error description]);
    } else {
        //To-do
    }
}];

The resulting url is: https://maps.googleapis.com/maps/api/place/search/json?location=37.337566,-122.041202&radius=1000&types=accounting|bowling_alley|doctor&sensor=true&key=MY_KEY
(my key is ommitted for obsious reasons)
Which works fine from my laptop's browser, but return the error:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe47bc138f0 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe47be9dbe0 "unsupported URL"}

I tried using http instead of https (in the browser it returns a json with some error message, but still returns something) with no success.
What am I doing wrong?

A: This is how I got it resolved. Good Luck!
NSString *google = @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%@&key=%@";
NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY];
NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];


text:
Q: Store response.data in a global variable I'm trying to store response.data into a variable that can then be used outside of it's scope however it seems to always come back as undefined.
As you can see in the code, the first axios calls returns a token and then I later want to be able to use this token within the headers of the POST call.
const server = () => {
  var token;

  axios.get('http://xxxxx').then(
    response => {
      token = response.data;
    }
  );

  var configuration = {
    configToken: token
  };

  async function login() {
    return fetch('https://xxxx', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${configuration.configToken}`,
      },
    })
  }

  login();
};

export default server;

A: axios request you send depending on the server path. check if your server is https or http


text:
Q: why the code doesn't alert Worky-worky? var a = function() {
  function someSetup(){
    var setup = 'done';
  }
  function actualWork() {
    alert('Worky-worky');
  }
  someSetup();
  return actualWork;
}();

why the above code doesn't alert Worky-worky?it shows undefined.thank you

A: Because you only return the function, not call it.
Perform a(); after this code execution, this will call the function that's returned by anonymous self-executing function, thus actualWork.

A: you are trying to return a function that has no return type (actualWork()).
It doesn't do the alert() because you didn't call the function properly.
actualWork()
return actualWork; is actually returning a variable, but because you didn't assign anything to that variable you're getting undefined back.
should do the trick.


text:
Q: Cannot make use_strict_mode work with custom session handler upon 'files' I want to implement custom session handler upon internal files handler similar to this: http://php.net/manual/en/class.sessionhandler.php#example-5380 (example 1).
But with session.use_strict_mode = 1.
I have been trying to test this sample code, but I can't seem to get it to work:
session_module_name('files');
ini_set('session.use_strict_mode', '1');

class MySessionHandler extends SessionHandler{}
session_set_save_handler(new MySessionHandler(), true);

session_start();
var_dump(session_id());

After delete an existing session file and rerun script, it create new file with the same id.
When there is no session_set_save_handler() it works as expected: new file is created with new id.

A: I wrote a simple minimal implementation for this.
<?php
session_module_name('files');
ini_set('session.use_strict_mode', '1');

session_set_save_handler(new MySessionHandler(), true);

session_start();
var_dump(session_id());

class MySessionHandler extends SessionHandler
{
    /**
     * Getting full path to session file
     *
     * It's depend on internal realization of 'files' hander.
     * Must be reviewed after each php release.
     */
    private function getFullPathName(string $key) : string
    {
        if (empty($filename = session_save_path())) {
            $filename = sys_get_temp_dir();
        } elseif (strpos($filename, ';') !== false) {
            $data = explode(';', $filename);
            $count = $data[0];
            $filename = end($data);
            for ($i = 0; $i < $count; $i++) {
                $filename .= '/' . $key[$i];
            }
        }
        return $filename.'/sess_'.$key;
    }

    public function validateId($key)
    {
        return file_exists($this->getFullPathName($key));
    }
}

I think this is a bug but maybe it's not.


text:
Q: Remove function call from select statement I have a oracle query which brings no of product records from the database & the result has a flag which shows whether particular product was ordered in last 12 months. This is derived by checking the order table to see if there was any order placed in last 12 months.
I have a different query, for simplicity I am showing the part of it here.
Product Table - tblProducts
Product_Id   Name   Description   Size   Default_QTY......

Orders Table - tblOrders
Order Id    ProductId    QTY    Price   Date_Purch......

Now, the query that fetches products, has a function that accepts the product Id & returns boolean value whether the product was purchased earlier. Here along with product I am going to join many other tables which returns considerable amount of records (close to 100000) & Order table is huge (28 Million records so far). Because of this calling function in the select statement can impact performance. Is there any other way I can check if product is present in orders table?
Select ProductId, Name, Description, Size, fun_IsPurcInLast12(ProductId) From tblProduct

A: The correlated subquery is worth checking:
-- test data
with
  tblProducts(ProductId, Name, Description, pSize) as (
    select 1, 'P1', 'D1', 7 from dual union all
    select 2, 'P2', 'D2', 4 from dual union all
    select 3, 'P3', 'D3', 8 from dual ),
  tblOrders(OrderId, ProductId, Date_Purch) as (
    select 1, 1, date '2017-05-13' from dual union all
    select 2, 1, date '2018-11-06' from dual union all
    select 3, 2, date '2013-01-30' from dual )
-- end of test data

select ProductId, Name, Description,
       case when exists (select 1
                           from tblOrders
                           where ProductId = p.ProductId
                             and Date_Purch > add_months(sysdate, -12))
            then 1
            else 0
       end as flag
  from tblProducts p

Index on (ProductId, Date_Purch) would be nice. Result:
 PRODUCTID NAME DESCRIPTION       FLAG
---------- ---- ----------- ----------
         1 P1   D1                   1
         2 P2   D2                   0
         3 P3   D3                   0

A: You may do a LEFT JOIN on DISTINCT orders
SELECT productid,
       name,
       description,
       size,
       CASE
            WHEN o.productid IS NOT NULL THEN 'YES'
            ELSE 'NO'
       END
  AS ispurcinlast12
FROM tblproduct p
LEFT JOIN (
     SELECT DISTINCT productid
       FROM tblorders
     WHERE date_purchased >= ADD_MONTHS(SYSDATE,-12)
) o ON p.productid = o.productid

Add an index on  productid,date_purchased   on tblOrders


text:
Q: C# IEnumerable query I have a question regarding this c# code. I can follow the last part  using selenium where it is entering data into the text field. But I have problem in understanding  how this function works  private IEnumerable GetXlData() and how the valus are being takenup by EnterData(string firstName, string lastName) this test.
I can follow that data1  and data2 hold the first and second column values  but how this alue being returned and being used by the EnterData(string firstName, string lastName) test.
namespace XYZ
{
    [TestFixture]
    public class readXl
    {
        ReadXLS xl = new ReadXLS("TestData.xls", "Sheet1");

        private IEnumerable<string[]> GetXlData()
        {
            foreach (ExcelData e in xl.TestData)
            {
                string data1 = e["firstName"];
                string data2 = e["lastName"];

                yield return new[] { data1, data2};
            }
        }

        [Test, TestCaseSource("GetXlData")]
        public void EnterData(string firstName, string lastName)
        {
            driver.FindElement(By.Name("FirstName")).SendKeys(firstName);
            driver.FindElement(By.Name("LastName")).SendKeys(lastName);
        }
    }
}

A: See documentation for TestCaseSource. NUnit is essentially doing this:
foreach (var x in GetXlData())
{
    EnterData(x[0], x[1]);
}

A: The TestCaseSource attribute in NUnit is used in so-called data-driven testing. The mechanism works like this:

*

*Its input (i.e. what is given to the attribute as method name) must be an enumerator method that returns object (string[] in your case, but it could be an untyped object as well).
This object must match the signature of the decorated test method (Enterdata()).

*The decorated test method then is executed as many times in a row as the enumerator method returns values, each time with the values that were provided by the enumerator method (therefore these methods are also called 'data factories').

Data-driven tests of this kind are very useful to throw a bunch of different data to a single algorithm, without needing to write the same test code again and again.


text:
Q: Selecting certain strings in a data frame I have a 138x50 data frame of the following type:
B = matrix( c("ehre","e", "eh", "ehr", "ehrr", "f", "fi", "fie", "fiee", "fiel", "seil", "s", "se", "sei", "seii", "leiht", "l", "le", "lei", "leih", 3, 0, 0, 0, 1), nrow=5, ncol=5, byrow = FALSE)
colnames(B)<-c("ana1_1", "ana2_1", "ana3_1", "ana4_1", "points")

I want to create a new df "A", only containing correct answers and replacing wrong answers with an empty cell/NA:
A = matrix( c("ehre",NA, NA, NA, NA, NA, NA, NA, NA, "fiel", "seil", NA, NA, NA, NA, "leiht", NA, NA, NA, NA, 3, 0, 0, 0, 1), nrow=5, ncol=5, byrow = FALSE)
colnames(A)<-c("ana1_1", "ana2_1", "ana3_1", "ana4_1", "points")

*

*How do I create A, not by deleting wrong but by selecting right answers? (as this would require less answers to type in).

*How do I count the number of strings in a row (to create column 5)?

Thank you very much for your response!

A: You can use grep to do this.  Create a vector of elements that you wanted to be as non-NA based on the 'ana' columns.
 v1 <- c('ehre', 'seil', 'leiht', 'fiel')

We paste these together with collapse='|' for the pattern argument in grep
 pat <- paste0('^(', paste(v1, collapse='|'), ')$')

Create an index for the 'ana' columns
 indx <- grepl('^ana', colnames(B))

I am creating a new object 'A1' which will be the modified matrix 'B' that have only the 'ana' columns.
 A1 <- B[,indx]

The output of grepl will be a logical vector.  We negate (!) it and the assign the corresponding elements of the columns in  'A1' to NA
A1[!grepl(pat, A1)] <- NA

To create the 'points' column (though in the example it is already created), we get a logical index of non-NA values in the 'ana' columns (!is.na(A1)), get the rowSums, and cbind with the original dataset.
cbind(A1, Points=rowSums(!is.na(A1)))
#     ana1_1 ana2_1 ana3_1 ana4_1  Points
#[1,] "ehre" NA     "seil" "leiht" "3"
#[2,] NA     NA     NA     NA      "0"
#[3,] NA     NA     NA     NA      "0"
#[4,] NA     NA     NA     NA      "0"
#[5,] NA     "fiel" NA     NA      "1"

It may be better to store the results in 'data.frame' as the 'Points' is a 'numeric' vector which gets transformed to 'character' by keeping it in a matrix (as matrix can have only a single class).

A: I start with your B, which also happens to contain "points", but that column isn't required. I recreated it later. So I first change all non-matches to NA, then I count the number of non-NA in each row (ignoring the "points" column) to tally up the points. The correct object is just a vector of correct answer that you are looking for.
B = matrix( c("ehre","e", "eh", "ehr", "ehrr", "f", "fi", "fie", "fiee", "fiel", "seil", "s", "se", "sei", "seii", "leiht", "l", "le", "lei", "leih", 3, 0, 0, 0, 1), nrow=5, ncol=5, byrow = FALSE)
colnames(B)<-c("ana1_1", "ana2_1", "ana3_1", "ana4_1", "points")

correct <- c("ehre","fiel","seil","leiht")
A <- B
A[!A%in%correct] <- NA
A[,"points"] <- apply(A[,colnames(A)!="points"], 1, function(x)sum(!is.na(x))) #tally up non-NA's to indicate points

This procedure results in the following output for A:
     ana1_1 ana2_1 ana3_1 ana4_1  points
[1,] "ehre" NA     "seil" "leiht" "3"
[2,] NA     NA     NA     NA      "0"
[3,] NA     NA     NA     NA      "0"
[4,] NA     NA     NA     NA      "0"
[5,] NA     "fiel" NA     NA      "1"


text:
Q: getting erro as "connected to an idle instance" oracle I have two oracle DB's, but I am getting "idle instance in primary db as below
Also db1 is working fine.

[oracle@db1 ~]$ export ORACLE_SID=SPM1
[oracle@db1 ~]$ sqlplus '/as sysdba'

SQL*Plus: Release 11.2.0.1.0 Production on Wed Aug 20 12:57:25 2014

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

Connected to an idle instance.

A: whenever oracle process are getting hanged for any database instatnces, then type of error will occur.
to resolve this, we need to hard reboot to database server. i did the same and its resolved.


text:
Q: Position elements of same class with jQuery I have done some research in several forums about this topic but have not figured out the solution.
I want the top position of an element to be relative to another element's height. The div that contains these elements repeats with the same class, and only set position for the first div and repeat the same top for the other elements.
How can I make the .bottom-content top position, place at the end of the .top height, and be different on every .container?
I have tried with .closest, .find, .next.
This is the code example:

$(document).ready(function() {

    var pTop = $(".container .top-content .top").height();

    $(".container .column .bottom-container").css({
      "top" : pTop + "px",
    });
});
.container {
 position: relative;
 display: inline-block;
 vertical-align: top;
 }

.top-content {
  position: absolute;
  width: 100%;
  z-index: 100;
 }

.top {
  position: absolute;
  background-color: red;
 }

.column {
  display: inline-block;
  height: 200px;
  width: 60px;
  background-color: gray;
}

.bottom-content {
  position: relative;
}

.bottom-content {
  width: 50px;
  height: 50px;
}

      Height change with dynamically content.

other thing

        BOTTOM CONTENT 1

other thing

        BOTTOM CONTENT 2

other thing

        BOTTOM CONTENT 3

other thing

      Height change with dynamically content, is always different size.

other thing

        BOTTOM CONTENT 1

other thing

        BOTTOM CONTENT 2

other thing

        BOTTOM CONTENT 3

other thing

A: Lot's of code, the key point is:
since you have multiple top container so calling this $(".container .top-content .top"); will return multiple top, you need to call .each() to treat them separately.
var topHeight = _self.height(); will give you the current top container's height.
Inside you call botContainer.each() this you will get 6 (in my example you will get 9 bottom container, you need to filter out the one you don't need to update the height so use this if:
if (botIndex >= (bl) * (topIndex / (tl)) && botIndex < (bl) * (topIndex + 1 / (tl))) {...}

$(document).ready(function() {
  var topContainer = $(".container .top-content .top");
  var botContainer = $(".container .column .bottom-container");
  tl = topContainer.length;
  bl = botContainer.length;

  topContainer.each(function(topIndex) {
    var _self = $(this);
    var topHeight = _self.height();

    botContainer.each(function(botIndex) {

      if (botIndex >= (bl) * (topIndex / (tl)) && botIndex < (bl) * (topIndex + 1 / (tl))) {

        var bc = $(this);
        bc.css({
          "margin-top": topHeight + "px",
        });
      }
    });

  });

});
.container {
  position: relative;
  display: inline-block;
  vertical-align: top;
}

.top-content {
  position: absolute;
  width: 100%;
  z-index: 100;
}

.top {
  position: absolute;
  background-color: red;
}

.column {
  display: inline-block;
  height: 200px;
  width: 60px;
  background-color: gray;
}

.bottom-content {
  position: relative;
}

.bottom-content {
  width: 50px;
  height: 50px;
}

      Height change with dynamically content.

other thing

        BOTTOM CONTENT 1

other thing

        BOTTOM CONTENT 2

other thing

        BOTTOM CONTENT 3

other thing

      Height change with dynamically content, is always different size.

other thing

        BOTTOM CONTENT 1

other thing

        BOTTOM CONTENT 2

other thing

        BOTTOM CONTENT 3

other thing

      Height change with dynamically content, is always different size.is always different size.is always different size.

other thing

        BOTTOM CONTENT 1

other thing

        BOTTOM CONTENT 2

other thing

        BOTTOM CONTENT 3

other thing


text:
Q: How can I selectively modify the lines in a file where the modifications depend on analyzing the select lines as a whole rather than individually TL;DR I need to align the columns of the entries in fstab while ignoring the comments:
/dev/foo              /foo         ext4        defaults   0    2
# comment line 1
/dev/bar /bar ext4 defaults 0 2
# comment line 2
UUID=1234567890     /baz      ext4      defaults   0       2

should become
/dev/foo         /foo  ext4  defaults  0  2
# comment line 1
/dev/bar         /bar  ext4  defaults  0  2
# comment line 2
UUID=1234567890  /baz  ext4  defaults  0  2

in, ideally, one swooping command.
</tldr>
My fstab consists of a large block of documentation in comment lines ending with the field descriptions and finally the entries. There are comment lines interspersed in the entry section.
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

# table entries begin ...

I'd like to align columns in the entry lines using the column -t command or equivalent but want to ignore the comments. If I don't ignore the comment lines, even they will be subjected to alignment. While editing the file in vim, I can visually select the lines from the first entry onward and run '<,'> !grep '^[^\#]' | column -t but grep will filter out the comment lines and as a result, they won't be present in the output, which replaces the selection in vim. I can't run the column command on each matching line individually because column doesn't work that way.
Is there a simple command that accomplishes this task? It need not be achievable in vim as I can simply delegate it to an external command from within.

A: tr -s \[:blank:] \  </etc/fstab |       # squeeze all tabs/spaces to 1 space
sed 's/^#/ # # # # # #/'        |       # create 6 tiny comment fields
column -t                       |       # get columns
sed '/^\( *#\)\{6\}/{s//#/;s/  */ /g;}' # fix and squeeze spaces for comments


text:
Q: Proof for the cancellation law of addition for natural numbers I'm trying to prove this by induction but I'm afraid I didn't quite make good use of the induction hypothesis. Here's my attempt where I assume $0\in \mathbb{N}$ (that's what I mean by $\mathbb{N_{0}}$):
Proof. We are trying to show that $\forall m,n,p\in \mathbb{N_{0}}:m+p=n+p\implies m=n$.
Base case: Fix $m,n\in \mathbb{N_{0}}$. If $p=0$ and $m+p=n+p$. Then,
\begin{align*}m&:=m+0=m+p=n+p=n+0:=n\end{align*}
So, $p=0\implies (m+p=n+p\implies m=n)$.
Induction step: Suppose $m+q=n+q\implies m=n$ for an arbitrary but fixed $q\in \mathbb{N_{0}}$. We may further assume\begin{align*}m+(q+1)=n+(q+1)\tag{$1$}\end{align*}
From $(1)$ we know that $(m+q)+1=(n+q)+1$. Now, our induction hypothesis abstractly tells us (my interpretation): $a+b=c+b\implies a=c$. Since $1=1$ and $a+1=c+1$ where $a=m+q$ and $c=n+q$ then $a=c$,that is $m+q=n+q$ but, again, from the induction hypothesis we can conclude now $m=n$ what finishes our induction on $p$.

A: You are trying to use the $p=1$ case of the claim, which you can't at that point. Instead, the needed $$x+1=y+1\implies x=y$$ is immediately one of the Peano axioms (perhaps written in terms of the successor function intead of "$+1$")

A: The explanation in the inductive step of your proof is a little weird ('abstractly tells us'?) ...
Also, while the cancellation theorem indeed says that if $a + c = b + c$, then $a = b$, you are in the middle of proving exactly that. So, there is a real danger of circular reasoning here.
But why even bring up $a$, $b$, and $c$?
Like you say, you can go from
$m+(q+1)=n+(q+1)$
to
$(m+q)+1=(n+q)+1$
to
$m+q=n+q$
to
$m = n$
Of course, for the first step you need to assume Association (can you assume that? Have you proven that? It can be proven from the Peano axioms using induction) and for the second step you need to already have shown that $m+1 = n + 1 \implies m +n$ ... or simply regard that as an 'obvious' mathematical truth (as Hagen points out, this is actually an elementary Peano axiom)


text:
Q: How to fix one DIV as header and one DIV as a footer with minimum code ? NO BOOTSTRAP In a HTML5 webpage that is not using BOOTSTRAP or any other boilerplate I have 3 DIVS:

*

*HEADER

*CONTENT

*FOOTER

How do I fix HEADER to the top of the page and the FOOTER to the botton while letting content to scroll freely ? header and footer must not show scrollbars at all.
header and footer must have 100px of height each and both must be on-top of the CONTENT DIV.
elements of the 3 divs must be active (user must be able to click on any link)
I am looking for the most simple HTML code that works for most current browsers, desktop and mobile.
thank you
gabriel

A:

header, footer {
  position: fixed;
  min-height: 100px;
}
header {
  top: 0;
}
footer {
  bottom: 0;
}
main {
  margin-top: 100px;
}
<!DOCTYPE html>

 Content


text:
Q: How to call C++ function from external file? i have 3 C++ source files and i need to call a function from one file into another
getch.cpp
#include<stdio.h>
#include "getch2.h"
main()
{
 char ch='x';
 fun(ch);
}

getch2.cpp
#include<stdio.h>
void fun(char);
main()
{

}
void fun(char x)
{
printf("the ascii value of the char is %d",x);
}

func.h
void fun(char);

when i compile getch2.cpp i get the error
C:\Users\amolsi\AppData\Local\Temp\cc1k7Vdp.o   getch.cpp:(.text+0x18): undefined reference to `fun(char)'
C:\Users\amolsi\Documents\C files\collect2.exe  [Error] ld returned 1 exit status

A: *

*Your main functions need to be changed to:
int main() { ... }

*Both getch.cpp and getch2.cpp contain main functions. You cannot use them together to form an executable. They'll have to be used to create separate executables.

*In order for you to use fun from getch.cpp and getch2.cpp to build executables, you need to move the definition of void fun(char){...} from getch2.cpp to another .cpp file. Let's call it func.cpp.

*Use getch.cpp and func.cpp to build one executable.

*Use getch2.cpp and func.cpp to build the other executable.
Update, in response to OP's comment
File func.h:

void fun(char);

File func.cpp:

void fun(char x)
{
   printf("the ascii value of the char is %d",x);
}

File getch.cpp:

#include <stdio.h>
#include "func.h"

int main()
{
   char ch='x';
   fun(ch);
   return 0;
}

File getch2.cpp:

#include<stdio.h>
#include "func.h"

int main()
{
   char ch='y';
   fun(ch);
   return 0;
}

Use getch.cpp and func.cpp to build executable getch.exe.
Use getch2.cpp and func.cpp to build executable getch2.exe.

A: Your #include is fine, the problem is that you don't implement fun anywhere.


text:
Q: define the prompted number is prime or not i want a code to define the prompted number by user is prime or not . since it's an assignment
i'm not allowed to use ' isprime ' predefined code .
the following approach was not useful :
N = input( 'please enter a positive enteger value = ' ) ;
Quotient = floor(N - (mod(N,2)./2)) ;
for i = 1 : Quotient
    if mod(N,i ) == 0
        fprintf(' your prompted number is not prime ' ) ;
        if mod(N,i) ~= 0
            fprintf(' your prompted number is   prime ' ) ;
        end
    end
end

for example if i enter a prime number like 13 it results in this :
 your prompted number is  prime

but if i enter a Non-prime num like 12 it repeats the ' your prompted number is prime ' message for 10 times .

A: Try to find factors and as soon as you find one you know it's not prime:
prime = true

for f = 2:ceil(sqrt(N)) %// Start from 2 as prime numbers DO have 1 as a factor. Anything larger than sqrt(N) will have to have a corresponding factor smaller than this so there is no point checking them
    if mod(N,f) == 0
       prime = false;
       break;
    end
end

There are 2 problems with your code. First, as already explained by paxdiablo, you need to start your loop from 2. Secondly you have nested your if statements, and since they are mutually exclusive conditions, the inner condition will never trigger.

A: for i = 1 : Quotient
    if mod(N,i ) == 0

That will give you every number since x mod 1 is always zero. In other words, the remainder (when you divide any positive integer by one) is zero, since all of them divide perfectly.
You need to start at 2 rather than 1.
In addition, once you've found out the number is not prime, you should stop the loop since there's no possibility of it becoming prime again after that :-) And, for efficiency, you only need to go up to the square root of the number since, if it has a factor above that, you would have already found the equivalent factor below that.
The pseudo-code for such a beast would be:
set isprime to true
set chkval to 2
while chkval * chkval <= number:
    if number mod chkval is zero:
        set isprime to false
        exit while
    end if
    increment chkval
end while
if isprime:
    say number, " is prime"
else:
    say number, " is composite"


text:
Q: add legend and tooltip using xaml.cs file I am drawing the charts in xaml.cs file such as
chart = new RadCartesianChart();
chart.Name = "Chart";
chart.Margin = new Thickness(10,20,10,20);
chart.BorderThickness = new Thickness(1);
chart.Background = new SolidColorBrush(Colors.LightGray);
chart.BorderBrush = new SolidColorBrush(Colors.Black);
ObservableCollection<MultiSeries> multiseries = mainWindowViewModel.GetSeies(Row, Col);
multiseries.ToList().ForEach(series =>
{
  chart.Series.Add(SeriesHelper.getLineSeries(series));
}
chart.SetValue(Grid.ColumnProperty, Col);
chart.SetValue(Grid.RowProperty, Row);
ChartGrid.Children.Add(chart);

and I am trying to add tooltip and legend to this chart
but I don't no how to add tooltip and legend .

A: Use this statement:
chart.Behaviors.Add(new ChartTooltipBehavior());