text:
Q: Access to PNRS of multiple Sabre PCCs from a single EPR (User id) token using Sabre SOAP API I am creating a batch processing application to process PNRs from multiple PCCs using Sabre soap APIs. The application needs to access PNRs from different PCCs. The Sabre API documentation mentions that you can access PNRs created in a PCC only through the token created in that PCC. The problem is, I would not know the PCC of a PNR till I call the GetItinerary (ReservationRQ) on that PNR. I want to know if we can create an EPR in one PCC or IPCC that can have access to PNRs created in other PCCs so that I can maintain only one token in my application.
To be more specific,I am in process of writing following application logic

*

*The users submit PNRs for processing (Amendments)

*The front-end application queues the PNRs in a database table

*The batch processing application picks up the PNR

*Retrieves PNR details from Sabre using GetReservationRQ)

*Batch application processes PNR as per the instructions provided by the user

*Repeat steps 4 to 5 for each PNR

Any help is greatly appreciated.
Please let know if you need more detail.

A: You do can retrieve PNRs from different PCCs using one webservice credentials. An admin will be able to manage the user access to those PCCs setting the branch access from your IPCC.
Hope this helps.
P.

A: You need to first branch those PCCs in order to access them. If this is the case you can use ContextChangeLLSRQ (Gui equivalent of AAA) to access and operate on other PCCs


text:
Q: Cannot make callout from a Trigger that is fired through a batch apex I'm trying to call a method which do an api call. But I'm getting an error because this method get call through the process ran by batch. So even if I directly call the API calling method it gives me an error 'Callout from triggers are currently not supported'. And when I call future method then it says future method cannot be called from batch. I have already implemented the Database.AllowsCallout interface in the batch class.
Please help in this.Thank you.

A: Salesforce does not allow callouts in triggers or future methods from the batch class. I think your current code requires a little restructuring where you can make the callouts directly from the batch by isolating the logic that is being called in the trigger and calling it from the batch instead.
The other way to do that would add identification (like a field or picklist) to the record using the batch and using another batch just to make the callouts.

A: So, a good practice is to delegate callouts to queueable Apex. This allows the Queueable class to be invoked from either

*

*Trigger

*Batchable execute()

If you add an intermediate Async_Request__c object that contains the callable parameters, you can build interesting async patterns that provide retry on error and logging of every callout. One example of this can be found in Advanced Apex, 4th Edition, chapter on Asynchronous Processing
You could also delegate callouts via Platform Events which execute asynchronously. The Platform Event subscriber would accept the callout params and then do the callout

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create XmlElement attributes with prefix? I need to be able to define an attribute with a prefix in a xml element.
For instance...
<nc:Person s:id="ID_Person_01"></nc:Person>

In order to do this I though that the following would have worked.
XmlElement TempElement = XmlDocToRef.CreateElement("nc:Person", "http://niem.gov/niem/niem-core/2.0");
TempElement.SetAttribute("s:id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

Unfortunately, XmlElement.SetAttribute(string, string, string) does not seem to support parsing the prefix as I receive the error below.

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

How would I define an attribute with prefix?

A: If you've already declared your namespace in the root node, you just need to change the SetAttribute call to use the unprefixed attribute name. So if your root node defines a namespace like this:
<People xmlns:s='http://niem.gov/niem/structures/2.0'>

You can do this and the attribute will pick up the prefix you've already established:
// no prefix on the first argument - it will be rendered as
// s:id='ID_Person_01'
TempElement.SetAttribute("id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

If you have not yet declared the namespace (and its prefix), the three-string XmlDocument.CreateAttribute overload will do it for you:
// Adds the declaration to your root node
var attribute = xmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
attribute.InnerText = "ID_Person_01"
TempElement.SetAttributeNode(attribute);

A: The XMLDocument.CreateAttribute method can take 3 strings: specified Prefix, LocalName, and NamespaceURI.  You could then add the attribute to the element.  Something like this might work for you:
XmlAttribute newAttribute = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
TempElement.Attributes.Append(newAttribute):

A: Try creating the attribute directly and adding it to the element:
XmlAttribute attr = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
attr.InnerText = "ID_Person_01";
TempElement.Attributes.Append(attr);

A: Since my search kept taking me here, I'll answer this for XElement.  I don't know if this solution is also valid for XmlElement, but it will hopefully at least help others using XElement, who end up here.
Based on this I added xml:space="preserve" to all data-nodes in some template, before looking up and adding their contents. It's weird code IMO (I would prefer three parameters as shown above, but it does the job:
 foreach (XElement lElement in root.Descendants(myTag))
 {
      lElement.Add(new XAttribute(root.GetNamespaceOfPrefix("xml") + "space", "preserve"));
 }


text:
Q: JPA+Hibernate Google Cloud Sql As Google presented new service - Google Cloud Sql, I decided to migrate gwt+jpa+hibernate+spring+maven web application to gae.
So I have a problem while starting my app locally and on gae.
I have an error creating dao bean caused by this:
     [ERROR] Caused by: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode;
[ERROR]     at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:625)
[ERROR]     at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
[ERROR]     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
[ERROR]     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
[ERROR]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
[ERROR]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)

So it seemed to me, that I was using jpa-1.0 instead of jpa-2.0 with hibernate (cause jpa 1.0 lacks of method:

getValidationMode()

I checked my libs...everthing is ok - using jpa 2.0 with hibernate-jpa-2.0-api.jar.
But I found a promlem:
When I use my code without gae and I use another db everthing is ok. The fact is that appengine sdk include its own JPA and the version is 1.0 (quote from here Using JPA with App Engine)

The JPA and datastore JARs are included with the App Engine Java SDK. You can find them in the appengine-java-sdk/lib/user/orm/ directory.
  Copy the JARs to your application's war/WEB-INF/lib/ directory.

When an application starts, it use jpa 1.0(with no method getValidationMode() in javax.persistence.spi.PersistenceUnitInfo) from appengine sdk instead of mine.
So, how can I come over this problem to make my app use right jars?
Here is my persistence.xml also:
   <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

        <!-- A JPA Persistence Unit -->
        <persistence-unit name="PersistenceUnit"
            transaction-type="RESOURCE_LOCAL">
            <provider>org.hibernate.ejb.HibernatePersistence</provider>

            <properties>
                <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
                <property name="hibernate.hbm2ddl.auto" value="update" />
                <property name="hibernate.show_sql" value="true" />
                <property name="hibernate.connection.url" value="jdbc:google:rdbms://bragininim:test/test"></property>
                <property name="hibernate.connection.driver_class"
                    value="com.google.appengine.api.rdbms.AppEngineDriver"></property>

                <!-- Connection -->
                <property name="hibernate.connection.username" value="****" />
                <property name="hibernate.connection.password" value="****" />

            </properties>
        </persistence-unit>

    </persistence>

A: There is some issue with Hibernate JPA support, because it used JPA 2.0 specification. But Google App Engine only support JPA1.0 specification. I also had same issue, there for I used Spring Hibernate support(instead of Hibernate JPA).
For your problem also I think better to use Spring Hibernate support.

A: You should use an older version of hibernate (compatible with jpa 1). GAE forces these things upon you. Actually I didn't know it supports JPA - I thought only JDO is supported.

A: I don't understand why you define username and password in the persistence.xml.
I thougth that you didn't need those credentials cause the app access to DB is restricted from console administration of Google SQL Cloud, where you specify allowed app's IDs.

A: If you are using eclipse, I think that a GAE project for java just copies the GAE jars to the WEB-INF\lib, remove the JPA jars from DataNucleus and Geronimo and copy your Hibernate jar.
I never tried this I am guessing.
Good luck!


text:
Q: ASP.NET MVC implement custom validator use IClientValidatable I ask similar question here but in this question I use another implementation, exactly this way the following codes show my implementations:
Model:
public class Department {

    public long Id { get; set; }

    [IsDateAfter("Date2", true, ErrorMessage = "O My")]
    public DateTime Date1 { get; set; }
    public DateTime Date2 { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }

}

Custom Validator:
public sealed class IsDateAfter : ValidationAttribute, IClientValidatable {

    private readonly string testedPropertyName;
    private readonly bool allowEqualDates;

    public IsDateAfter(string testedPropertyName, bool allowEqualDates = false)
  {
        this.testedPropertyName = testedPropertyName;
        this.allowEqualDates = allowEqualDates;
    }

    protected override ValidationResult IsValid(object value, ValidationContext
 validationContext) {
        var propertyTestedInfo =
validationContext.ObjectType.GetProperty(this.testedPropertyName);
        if (propertyTestedInfo == null) {
            return new ValidationResult(string.Format("unknown property
 {0}", this.testedPropertyName));
        }

        var propertyTestedValue =
 propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);

        if (value == null || !(value is DateTime)) {
            return ValidationResult.Success;
        }

        if (propertyTestedValue == null || !(propertyTestedValue is
 DateTime)) {
            return ValidationResult.Success;
        }

        // Compare values
        if ((DateTime)value >= (DateTime)propertyTestedValue) {
            if (this.allowEqualDates) {
                return ValidationResult.Success;
            }
            if ((DateTime)value > (DateTime)propertyTestedValue) {
                return ValidationResult.Success;
            }
        }

        return new
 ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        var rule = new ModelClientValidationRule {
            ErrorMessage = this.ErrorMessageString,
            ValidationType = "isdateafter"
        };
        rule.ValidationParameters["propertytested"] =
 this.testedPropertyName;
        rule.ValidationParameters["allowequaldates"] =
 this.allowEqualDates;
        yield return rule;
    }
}

Script:

$.validator.unobtrusive.adapters.add(
'isdateafter', ['propertytested', 'allowequaldates'], function (options) {
    options.rules['isdateafter'] = options.params;
    options.messages['isdateafter'] = options.message;
});
$.validator.addMethod("isdateafter", function (value, element, params) {
alert(params.propertytested);
var startdatevalue = $('input[name="' + params.propertytested + '"]').val();
if (!value || !startdatevalue) return true;
return (params.allowequaldates) ? Date.parse(startdatevalue) <= Date.parse(value) :
 Date.parse(startdatevalue) < Date.parse(value);
}, '');

And My _Layout page (Master page)
<!DOCTYPE html>

<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

                My MVC Application

            @Html.Partial("_LogOnPartial")

@Html.ActionLink("Departments", "Index", "Department")

        @RenderBody()

of course in Edit And Create View pages the other script source are as following:

A part of Create Page Dom:
<fieldset>
<legend>Department</legend>

Date1

<input id="Date1" class="text-box single-line valid" type="text" value="" name="Date1"
 data-val-required="The Date1 field is required." data-val-isdateafter-
 propertytested="Date2" data-val-isdateafter-allowequaldates="False" data-val-
isdateafter="O My" data-val="true">

Date2

<input id="Date2" class="text-box single-line valid" type="text" value="" name="Date2"
 data-val-required="The Date2 field is required." data-val="true">

I try All of implementation be the same as here but that not work in client side and need to postback, I don't have any other implementation for example register in global.asax
like this, Does any one know about it? I really confused, I tried 2 way but none of them give the true answer.

A: You have messed up your script inclusions. In your _Layout you have included the following scripts in that order:

Now obviously jquery.validate.min.js and jquery.validate.js represents the same script, the first being the minified version. But since you haven't included the jquery.validate.unobtrusive.js script (this is done much later in your view), your custom jQuery.IsDateAfter.js script will contain errors since it will not know about the $.validator.unobtrusive.adapters object that you are using. So here's how the scripts in your layout should look:

You could also add your custom jQuery.IsDateAfter.js script to the layout at the end if you wish in case it is used in many views and if not you could add it to the view:

That's the only script you should have in the view. You should remove any other jquery.* script inclusions from  your Edit And Create View pages.
Remark: you will also notice that I have removed all Microsoft*.js scripts from your Layout. They are obsolete and should no longer be used in ASP.NET MVC 3.


text:
Q: Build deb project failed I am trying to compile a deb project and it failed on the testing. Is there a way to skip the test? I already tried the option DEB_BUILD_OPTIONS=nocheck debuild -us -uc but the project still trying to make a test.
As I know it should be an option inside debian/rules to skip it. Can you help me what I have to add to this file?
Thanks


text:
Q: Haskell Maybe adder without Arguments I am wondering if it is possible to wirte the Function
add :: Maybe Int -> Maybe Int
add Just x = Just (x+1)
add Nothing = Nothing

without the x. Similar to
f = Just.(+1)

However
add Just = Just.(+1)

throws an error: Equations for 'add' have different numbers of arguments.
Can someone please explain me why this does not work?

A: You need to pattern match somewhere - there's no way to "get the value out" without doing so. You can use some unsafe function, like fromJust, but

*

*it's unsafe - doing a case and pattern matching is better

*it's still doing pattern matching in it, so you're not really avoiding doing it.

The "proper modular" way to do this, would be to write this common pattern as a higher-order function, so that you can reuse it:

*

*in the Nothing case, you return Nothing

*in the Just case, you return Just of some function applied to the arg inside

Taking into account the two things above, we reach the following
maybeMap :: (a -> b) -> Maybe a -> Maybe b
maybeMap _ Nothing = Nothing
maybeMap f (Just x) = Just (f x)

which you can now use to write your desired function:
add :: Maybe Int -> Maybe Int
add x = maybeMap (+1) x
-- or we can eta reduce it - taking an argument and calling a function with it is the same as just returning the function directly
add = maybeMap (+1)

This function is traditionally called map, because you're mapping "the values inside a container" to something else.
This is something that you very often need to do for different "containers" (and some other kinds of things), so we have a type class for it in the standard library (base), named after some theoretical things:
class Functor f where
  fmap :: (a -> b) -> f a -> f b
instance Functor [] where
  fmap = map
instance Functor Maybe where
  fmap = maybeMap

Additionally, the error you're seeing is something else entirely. In Haskell, when writing a function definition, your different cases are not allowed to have different numbers of arguments taken:
-- not allowed, since in the first case you've taken two args,
-- but in the second you've only taken one.
bla :: Integer -> Integer -> Integer
bla 0 y = 42
bla x = id

-- this is fine, in both cases we have two arguments
bla :: Integer -> Integer -> Integer
bla 0 y = 42
bla x y = y

A: The first parameter is a Maybe Int, hence it is not sufficient to only specify the Just data constructor: this data constructor has one parameter x. You thus should use (Just x), (Just _) or Just {} to match where the last two ignore the value wrapped in the Just data constructor. But in that case you thus can not access that value.
Your function however is a special case of an fmap :: Functor f => (a -> b) -> f a -> f b with f ~ Maybe and as mapping function (+1). Indeed, the Functor instance of Maybe is implemented as [src]:

instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)

You thus can implement add as:
add :: Maybe Int -> Maybe Int
add = fmap (1+)


text:
Q: Export/import ACL using csv I want to export in a csv file the ACL of every subfolder starting from a root folder and then to import them of mirroring folders on another computer.
I'm using this code to export from C:\Users\user\Desktop\a :
Get-ChildItem "C:\Users\user\Desktop\a" -Recurse | ?{ $_.PsIsContainer } | %{
$Path = $_.FullName
# Exclude inherited rights from the report
(Get-Acl $Path).Access | ?{ !$_.IsInherited } | Select-Object `
    @{n='Path';e={ $Path }}, IdentityReference, AccessControlType, `
    InheritanceFlags, PropagationFlags, FileSystemRights
} | Export-CSV "C:\Users\user\Desktop\Permissions.csv"

and this code to import ACL:
$par = Import-Csv -Path "C:\Users\user\Desktop\Permissions.csv"
foreach ( $i in $par ) {
    $path= $i.Path
    $IdentityReference= $i.IdentityReference
    $AccessControlType=$i.AccessControlType
    $InheritanceFlags= $i.InheritanceFlags
    $PropagationFlags=$i.PropagationFlags
    $FileSystemRights=$i.FileSystemRights
    echo $path $IdentityReference
    $acl = Get-Acl C:\Users\user\Desktop
    $permission = $i.IdentityReference,$i.FileSystemRights,$i.AccessControlType
    $accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl $path
}

Permissions.csv is something like this:
#TYPE Selected.System.Security.AccessControl.FileSystemAccessRule
"Path","IdentityReference","AccessControlType","InheritanceFlags","PropagationFlags","FileSystemRights"
"C:\Users\user\Desktop\a\b","DITOADMIN\pluto","Allow","None","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pluto","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\admin","Allow","None","None","FullControl"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pippo","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"

unfortunately, import action doesn't work since only last permission is imported (so only for pippo user and not for pluto).
anybody knows why?

A: I've fixed it.
the problem was the line, the path I use here was wrong (should be the path from the CSV import)
$acl = Get-Acl C:\Users\user\Desktop
$permission = $i.IdentityReference,$i.FileSystemRights,$i.AccessControlType

I've changed with
$acl = Get-Acl $path
$permission = $IdentityReference, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType

bye

A: It's almost perfect.  Here you add the permission from the CSV to the folder, but you keep the old permission on it.  You dont "reset/copy" the ACL from one folder to the other.
So instead of getting the ACL of the receiving folder:
$acl = Get-Acl $path
Ive create a new one:
$acl = New-Object System.Security.AccessControl.DirectorySecurity
But then, i lose the Owner attribute.  So i need a way to export the owner in the CSV with the rights..


text:
Q: How to find matches that do not include a string in regular expressions I'm trying to create a regular expression that will match #rn: but not if it is followed by msg.
So
#rn:abc -> matches
#rn:msh -> matches
#rn:xy -> matches
#rn:defg -> matches
#rn:msg - does not match

I have tried \#rn\:[^m][^s][^g] and \#rn\:[^(msg)] but they don't work.
Can it be done?

A: \#rn\:(?!msg)

This shoudl do it for you.Here lookahead ensure that after #rn: there is not msg.See demo.
https://regex101.com/r/tX2bH4/28


text:
Q: How to create a granular bash script with multiple variables with ssh connections I have the below script:
bash Script:
#!/bin/bash
###########
printf "\n"
marker=$(printf "%0.s-" {1..60})
printf "|$marker|\n"
printf "|%-10s | %-13s | %-29s |\n" "Hostname" "RedHat Vesrion" "Perl Version"
printf "|$marker|\n"

remote_connect() {
   target_host=$1
   marker=$(printf "%0.s-" {1..60})
   rhelInfo=$(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no cat /etc/redhat-release| awk 'END{print $7}')
   perlInfo=$(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no "rpm -qa | grep -i mod_perl")
   if [[ $? -eq 0 ]]
   then
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "$rhelInfo" "$perlInfo"
   else
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "Unable to get the ssh connection"
fi
}  2>/dev/null
export -f remote_connect
< /home/zabbix/hostsList.txt  xargs -P30 -n1 -d'\n' bash -c 'remote_connect "$@"' --

The above script runs pretty well for me while running in parallel mode.
Script results:
|------------------------------------------------------------|
|Hostname   | RedHat Vesrion | Perl Version                  |
|------------------------------------------------------------|
|foxnl41    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl84    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl42    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl63    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl10    | 6.7           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl55    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl95    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |
|foxnl85    | 6.9           | mod_perl-2.0.4-11.el6_5.x86_64 |

Concern ?
I have two variables: rhelInfo and perlInfo to get store  information.  But it is using two ssh calls to the servers to get the values.
Could I have only one SSH call to execute multiple commands and set both variables?

A:
Could I have only one SSH call to execute multiple commands and set both variables?

Sure. You could do:
# this looks too long - so a function
_ssh() {
  ssh -i /home/zabbix/.ssh/ssh_key \
      -o StrictHostKeyChecking=no \
      -o PasswordAuthentication=no \
      "root@$target_host" \
      "$@"
}
export -f _ssh

# the function to-be-executed on the remote
remotework() {
    rhelinfo=$(awk 'END{print $7}' /etc/redhat-release)
    perlinfo=$(rpm -qa | grep -i mod_perl)
    # output elements separated by byte 0x01
    printf "%s\001" "$rhelinfo" "$perlinfo"
}
export -f remotework

remote_connect() {
    # execute bash on the remote
    # with `remotework` function serialized
    # and execute the `remotework` function
    # properly `printf %q` quote everything for unquoting done by ssh+remote shell
    tmp=$( _ssh "$(printf "%q " bash -c "$(declare -f remotework); remotework")" )
    # split the output of ssh by byte 0x01
    {
       IFS= read -d $'\x01' -r rhelInfo &&
       IFS= read -d $'\x01' -r perlInfo
    } <<<"$tmp"
}

or similar variation of it. Basically ssh gives you a bidirection stream of data - you can stream anything with a separator in between ("custom protocol") and then split the data on that separator. I.e. the problem is not limited to ssh - research data serialization/deserialization in bash. Above I have chosen the byte 0x01 to be the separator - you can use a separate line with unique uuid, use base64 -w0 to convert data to a single line, or similar or use another format.
remotework() {
    awk ... | base64 -w0
    echo ' '
    rpm ... | base64 -w0
    echo
}
...
   IFS=' ' read -r rhelInfo perlInfo <<<"$tmp"
   rhelInfo=$(<<<"$rhelInfo" base64 -d)
   perlInfo=$(<<<"$perlInfo" base64 -d)

You can also serialize variables with declare -p and then eval them - this is in my opinion more dangerous, so it's better to use a separator.

A: Suggesting to replace following lines:
   rhelInfo=$(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no cat /etc/redhat-release| awk 'END{print $7}')
   perlInfo=$(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no "rpm -qa | grep -i mod_perl")
   if [[ $? -eq 0 ]]; then
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "$rhelInfo" "$perlInfo"
   else
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "Unable to get the ssh connection"
   fi

With following lines:
   sshResponseArr=( $(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no "awk 'END{print}'  /etc/redhat-release; rpm -aq|grep -i mod_perl") )
   if [[ $? -eq 0 ]]; then
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "${sshResponseArr[6]}" "${sshResponseArr[8]}"
   else
     printf "|%-10s | %-13s | %-20s |\n" "$target_host" "Unable to get the ssh connection"
   fi

Explanation
First I call multi-line commands in the ssh request. Placing all the commands in a single argument with " (as you did).
The real trick is to read multi-line ssh response into bash array variable sshResponseArr
By default the array is parsed by   spaces.
I assume (as you did) that words positioning in the array is consistent across all hosts therefore:
$rhelInfo is ${sshResponseArr[6]}
And $perlInfo is ${sshResponseArr[8]}
Alternative conservative handling of sshResponseArr as an array of 2 lines response from ssh command:
 mapfile -t sshResponseLinesArr < <(ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no "awk 'END{print}'  /etc/redhat-release; rpm -aq|grep -i mod_perl")
 lastLineInReleaseFile=${sshResponseLinesArr[0]}
 mod_perl_response=${sshResponseLinesArr[1]}

A: You can run both commands in one ssh run and then parse the results, like this for example:
...
remote_data=($(
    ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" -o StrictHostKeyChecking=no -o PasswordAuthentication=no "
        rhelInfo=\$(cat /etc/redhat-release | awk 'END{print \$7}')
        perlInfo=\$(rpm -qa | grep -i mod_perl)

        echo \$rhelInfo \$perlInfo
"))

rhelInfo=${remote_data[0]}
perlInfo=${remote_data[1]}
...

Explanation:
remote_data=( $(ssh ...) ) - will create an array 'remote_data' and fill it with values from output of the command in $() Array will automatically split values by space, tab or new line. So it this case we will have remote_data=( 6.9 mod_perl-2.0.4-11.el6_5.x86_64 )
And then these values are assigned to variables:
rhelInfo=${remote_data[0]}
perlInfo=${remote_data[1]}

BTW echo(and cat)) is an overkill here, so this could be simplified to:
...
remote_data=($(
    ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" \
        -o  StrictHostKeyChecking=no \
        -o PasswordAuthentication=no "
           awk 'END{print \$7}' /etc/redhat-release
           rpm -qa | grep -i mod_perl
    "
))

rhelInfo=${remote_data[0]}
perlInfo=${remote_data[1]}
...

A: Here is how I do remote data collection using ssh
Some remarks

*

*As this function is intended to collect datas, not to connect host (as they don't stay connected), I've renamed them ;-)

*Avoid useless forks! use printf -v varname ... instead of varname=$(printf ...)

*Moved STDERR redirection 2>/dev/null at more suited place.

*use local to reserve variables names into function scope.

*printf must have correct number of arguments, corresponding to number of %s see This format string has 3 variable....

*Don't use -i switch to grep if not needed!
remote_collect() {
    local target_host=$1 host_answer rhelInfo perlInfo
    {
        read -r host_answer
        read -r rhelInfo
        read -r perlInfo
    } < <(
        ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" \
            -o StrictHostKeyChecking=no -o PasswordAuthentication=no \
            /bin/sh <<-EOF
        hostname
        awk 'END{print $7}' </etc/redhat-release
        rpm -qa | grep mod_perl
EOF
    ) 2>/dev/null
    if [[ $? -eq 0 ]] ;then
        printf "| %-10s | %-14s | %-29s |\n" \
            "host_answer" "$rhelInfo" "$perlInfo"
    else
        printf "| %-10s | %-46s |\n" \
            "target_host" "Unable to get the ssh connection"
    fi
}

Notice: the EOF mark could be preceded by tabulations Tab, but not spaces! I've dropped tabulation before posting to ensure they won't be converted in space during cut'n paste.
And the head line could be
printf -v marker '%61s' ''
marker=${marker// /-}
printf "+%s+\n| %-10s | %-14s | %-29s |\n+%s+\n" \
   "$marker" "Hostname" "RedHat Version" "Perl Version" "$marker"

+-------------------------------------------------------------+
| Hostname   | RedHat Version | Perl Version                  |
+-------------------------------------------------------------+
| hostok     | 6.3            | mod_perl-2.0.4-10.el6_5.armf  |
| hostbad    | Unable to get the ssh connection               |

Pretty table using UFT-8 borders
printf -v sl %31s '';sl=${sl// /$'\U2500'}
printf '%b%-12s%b%-16s%b%-31s%b\n' \
    \\U250c "${sl::12}" \\U252c "${sl::16}" \\U252c "$sl" \\U2510 \
    \\U2502 ' Hostname' \\U2502 ' RedHat Version' \\U2502 ' Perl Version' \
    \\U2502   \\U251c "${sl::12}" \\U253c "${sl::16}" \\U253c "$sl" \\U2524

then:
    if [[ $? -eq 0 ]] ;then
        printf "\U2502 %-10s \U2502 %-14s \U2502 %-29s \U2502\n" \
            "$host_answer" "$rhelInfo" "$perlInfo"
    else
        printf "\U2502 %-10s \U2502 %-46s \U2502\n" \
            "$target_host" "      Unable to get the ssh connection"
    fi

and finally
# printf -v sl %31s '';sl=${sl// /$'\U2500'} # uncomment if $sl not at main scope
printf '\U2514%s\U2534%s\U2534%s\U2518\n' "${sl::12}" "${sl::16}" "$sl"

should produce:
┌────────────┬────────────────┬───────────────────────────────┐
│ Hostname   │ RedHat Version │ Perl Version                  │
├────────────┼────────────────┼───────────────────────────────┤
│ hostok     │ 6.3            │ mod_perl-2.0.4-10.el6_5.armf  │
│ hostbad    │       Unable to get the ssh connection         │
└────────────┴────────────────┴───────────────────────────────┘

A: I am Keeping it here after testing from my side with @F. Hauri answer..
#!/bin/bash
###########
printf -v sl %32s '';sl=${sl// /$'\U2500'}
printf '%b%-12s%b%-16s%b%-32s%b\n' \
    \\U250c "${sl::12}" \\U252c "${sl::16}" \\U252c "$sl" \\U2510 \
    \\U2502 ' Hostname' \\U2502 ' RedHat Version' \\U2502 ' Perl Version' \
        \\U2502   \\U251c "${sl::12}" \\U253c "${sl::16}" \\U253c "$sl" \\U2524

remote_collect() {
    target_host=$1
    {
        read -r rhelInfo
        read -r perlInfo
    } < <(
        ssh -i /home/zabbix/.ssh/ssh_key "root@${target_host}" \
            -o StrictHostKeyChecking=no -o PasswordAuthentication=no \
            /bin/sh <<-EOF
        cat /etc/redhat-release | awk 'END{print \$7}'
        rpm -qa | grep mod_perl
EOF
    ) 2>/dev/null

    if [[ $? -eq 0 ]] ;then
        printf "\U2502 %-10s \U2502 %-14s \U2502 %-28s \U2502\n" \
            "$target_host" "$rhelInfo" "$perlInfo"
    else
        printf "\U2502 %-10s \U2502 %-14s \U2502  %-29s \U2502\n" \
            "$target_host" "?" "Unable to connect"
    fi
 # printf -v sl %31s '';sl=${sl// /$'\U2500'} # uncomment if $sl not at main scope
 printf '\U2514%s\U2534%s\U2534%s\U2518\n' "${sl::12}" "${sl::16}" "$sl"

} 2>/dev/null
export -f remote_collect
< /home/zabbix/hostsList.txt  xargs -P30 -n1 -d'\n' bash -c 'remote_connect "$@"' --

Output 1:
┌────────────┬────────────────┬────────────────────────────────┐
│ Hostname   │ RedHat Version │ Perl Version                   │
├────────────┼────────────────┼────────────────────────────────┤
│ foxnl46    │ ?              │  Unable to connect             │
└┴┴┘
│ foxnl27    │ 6.7            │ mod_perl-2.0.4-11.el6_5.x86_64 │
└┴┴┘
│ foxnl32    │ 6.7            │ mod_perl-2.0.4-11.el6_5.x86_64 │

If i remove the last printf it all turns okay expect the last line for table.
Output 2
┌────────────┬────────────────┬────────────────────────────────┐
│ Hostname   │ RedHat Version │ Perl Version                   │
├────────────┼────────────────┼────────────────────────────────┤
│ foxnl46    │ ?              │  Unable to connect             │
│ foxnl27    │ 6.7            │ mod_perl-2.0.4-11.el6_5.x86_64 │
│ foxnl32    │ 6.7            │ mod_perl-2.0.4-11.el6_5.x86_64 │


text:
Q: Implementing Mod Rewrite in Dynamic PHP website I have built a website in PHP that takes cars from a csv file, imports them by cron into the database. The cars are displayed in a file which is showroom.php by ?id=slugname-from-database-row, the slug is created on import, however I do lack the knowledge to get the rewriting to work as it seems to conflict with news_content.php?id=slugname-from-database-row which displays the latest news and works the exact same way as showroom.php.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options -Multiviews
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
#RewriteRule ^([^/]+)/?$ news_content.php?id=$1 [L]
RewriteRule ^([^/]+)/?$ showroom.php?id=$1 [L]
<IfModule>

Only page or the other works, if I comment out the above line like so in .htaccess the re-writing works fine on showroom.php:
http://127.0.0.1/showroom.php?id=604010047-honda-cr-z-3-door-15-ima-sport-hybrid-manual

gets rewritten to:
http://127.0.0.1/604010047-honda-cr-z-3-door-15-ima-sport-hybrid-manual

If uncomment out the above line relating to news_content.php in .htaccess the showroom.php page does not work or vice versa!
The news page works like this as above:
http://127.0.0.1/news_content.php?id=test-slug-news-item-from-database

gets rewritten to:
http://127.0.0.1/test-slug-news-item-from-database

Its driving me mad! Any help much appreciated!

A: Try this
For News
RewriteRule ^([A-Za-z0-9_\-]+).html$ news_content.php?id=$1 [L]

For Showroom
RewriteRule ^([A-Za-z0-9_\-]+).htm$ showroom.php?id=$1 [L]


text:
Q: How to configure /etc/pam.d/sshd and nsswitch.conf in order to avoid all remote calls for ssh with local user? I have created an NSS and a PAM module in order to authenticate and get users and groups from a custom remote server.
In order to get them used by the system I am adding a line in /etc/pam.d/sshd:
auth       sufficient   myPAMmodule.so

and in /etc/nsswitch.conf:
passwd:     files sss myNSSmodule
shadow:     files sss myNSSmodule
group:      files sss myNSSmodule

The question is how to configure these (or anything else) in order to avoid calling my modules in case an ssh is made with a local user.
Adding a linux module with sufficient before my module
auth       sufficient  pam_env.so

seems necessary. By adding an initgroups line without my module
initgroups: files sss

makes id command to work only locally for local user ( but gets only primary group for user).
But still whenever I perform ssh user@localhost I still see remote calls for local users.


text:
Q: Invoke interrupt from R code I have a generic function to catch all exceptions included in my package logR::tryCatch2  defined as:

tryCatch2 <- function(expr){
    V=E=W=M=I=NULL
    e.handler = function(e){
        E <<- e
        NULL
    }
    w.handler = function(w){
        W <<- c(W, list(w))
        invokeRestart("muffleWarning")
    }
    m.handler = function(m){
        attributes(m$call) <- NULL
        M <<- c(M, list(m))
    }
    i.handler = function(i){
        I <<- i
        NULL
    }
    V = suppressMessages(withCallingHandlers(
        tryCatch(expr, error = e.handler, interrupt = i.handler),
        warning = w.handler,
        message = m.handler
    ))
    list(value=V, error=E, warning=W, message=M, interrupt=I)
}

As you can see in the last line it returns a list which is more or less self describing.
It makes the real reaction to the exceptions delayed after the tryCatch2 call by simple !is.null:

f = function(){ warning("warn1"); warning("warn2"); stop("err") }
r = tryCatch2(f())
if(!is.null(r$error)) cat("Error detected\n")
# Error detected
if(!is.null(r$warning)) cat("Warning detected, count", length(r$warning), "\n")
# Warning detected, count 2

It works as expected, I can react with my own code. But in some cases I would like to not stop the interrupt process which is caught too. At the moment it seems I would need to add additional parameter to tryCatch2 which would control if interrupts should be catch or not. So the question asks about some invokeInterrupt function which I could use in the following way:
g = function(){ Sys.sleep(60); f() }
r = tryCatch2(g())
# interrupt by pressing ctrl+c / stop while function is running!
if(!is.null(r$interrupt)) cat("HERE I would like to invoke interrupt\n")
# HERE I would like to invoke interrupt

I think if R is able to catch one it should be also able to invoke one.
How can I achieve invokeInterrupt functionality?

A: I can propose a partial solution, which relies on the tools package.
invokeInterrupt <- function() {
  require(tools)
  processId <- Sys.getpid()
  pskill(processId, SIGINT)
}

However, be aware that throwing the interrupt signal (SIGINT) with pskill doesn't appear to be very robust. I ran a few tests by sending the exception and catching it with your function, like so:
will_interrupt <- function() {
    Sys.sleep(3)
    invokeInterrupt()
    Sys.sleep(3)
}

r = tryCatch2(will_interrupt())

On linux, this worked well when executed from the R commandline. On windows, the R commandline and R Gui did close when executing this code. There is worse: on both linux and windows, this code crashed Rstudio instantly...
So, if your code is to be executed from the R commandline on Linux, this solution should be OK. Otherwise you might be out of luck...

A: Late answer but I have found that rlang::interrupt can throw "user interrupts":

interrupt() allows R code to simulate a user interrupt of the kind that is signalled with Ctrl-C.
  It is currently not possible to create custom interrupt condition objects.

Source: ?rlang::interrupt
Internally it calls the R API function Rf_onintr which is an alias for the function onintr.
Basically an interrupt is "just" a special condition with these classes:
interrupt and condition (see the R source code).
If you just want to simulate an interrupt to test tryCatching (without the need to interrupt a running R statement) it suffice to throw a condition with these classes via signalCondition:
interrupt_condition <- function() {
  structure(list(), class = c("interrupt", "condition"))
}

tryCatch(signalCondition(interrupt_condition()),
                         interrupt = function(x) print("interrupt detected"))
# [1] "interrupt detected"


text:
Q: Sniffing the Router for Packets I have used WireShark software to sniff my Network Interface. What if i wanted to sniff the router that what other computers on the network are doing? Is there any way to do that?
Computers are connecting through WiFi.

A: The router is a bit of a red-herring in the question as it is unlikely to have the ability to mirror the wifi data out to your PC. The best you could do with the router would probably be to put your PC between the router and the internet and sniff that traffic, but you would miss out on any traffic that stayed within the LAN.
A better approach might be to feed Wireshark the wifi passphrase and let it decrypt over the air. A guide to that is here:
http://wiki.wireshark.org/HowToDecrypt802.11


text:
Q: scheduled email release what will be the best method of releasing a scheduled email say 2 days before an event in RoR. the event date is going to be stored into the database, and i just want a reminder sent out 2 days prior to event.

A: you can try this
in your schedule.rb file
every 1.day do
   trigger mailer
end

and in mailer method
def mail_setup
  if Date.today == event_date - 2.days
     mail setup
  else
     do nothing
  end
end

A: You might have figured this alreay out by yourself. Well...anyway: In cases as the described I always use an external crontab job. In a certain interval (in your case e.g. each day) you dial into your application via
rails runner script.rb

or
rails runner -e class-method

The script or the method then scans the db for pending trigger dates and does whatever it should do, e.g. sending emails.
ps: Of course you have to take care of the correct environment for your rails calls.


text:
Q: Node error to install MobileFirst Platform mfpdev-cli Hello I have an error of installing mfpdev-cli.
I run in Node:
npm install -g mfpdev-cli

Also, I tried:
npm install -g --no-optional mfpdev-cli

And I have the same result:
npm ERR! code ENOLOCAL
npm ERR! Could not install from "..\AppData\Roaming\npm\node_modules\mdo-adapter-actions" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     ..\AppData\Roaming\npm-cache\_logs\2017-10-06T19_33_40_852Z-debug.log

Log file:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\admin\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   'mfpdev-cli' ]
2 info using npm@5.4.2
3 info using node@v8.6.0
4 verbose npm-session c592940cb4bd8510
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 200 https://registry.npmjs.org/mfpdev-cli 17ms (from cache)
8 silly pacote tag manifest for mfpdev-cli@latest fetched in 57ms
9 silly install loadIdealTree
10 silly install cloneCurrentTreeToIdealTree
11 silly install loadShrinkwrap
12 silly install loadAllDepsIntoIdealTree
13 silly resolveWithNewModule mfpdev-cli@8.0.2017092810 checking installable status
14 silly pacote trying https://registry.npmjs.org/mfpdev-cli/-/mfpdev-cli-8.0.2017092810.tgz by hash: sha1-xVC4PO9ZSewF6xzlXsWExVTqvsw=
15 silly pacote https://registry.npmjs.org/mfpdev-cli/-/mfpdev-cli-8.0.2017092810.tgz extracted to C:\Users\ADMIN\AppData\Local\Temp\npm-11192-a75b2045\unpack-1eeac08f by content address 11899ms
16 silly addBundled read tarball
17 silly cleanup remove extracted module
18 silly fetchPackageMetaData error for mdo-adapter-actions@file:..\mdo-adapter-actions Could not install from "C:\Users\admin\AppData\Roaming\npm\node_modules\mdo-adapter-actions" as it does not contain a package.json file.
19 verbose stack Error: ENOENT: no such file or directory, open 'C:\Users\admin\AppData\Roaming\npm\node_modules\mdo-adapter-actions\package.json'
20 verbose cwd H:\
21 verbose Windows_NT 10.0.15063
22 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\admin\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "mfpdev-cli"
23 verbose node v8.6.0
24 verbose npm  v5.4.2
25 error code ENOLOCAL
26 error Could not install from "C:\Users\admin\AppData\Roaming\npm\node_modules\mdo-adapter-actions" as it does not contain a package.json file.
27 verbose exit [ 1, true ]

My Node version is 8.6.0, NPM version is 5.4.2 and OS is Windows 10.
I tried to downgrade versions and cleaning cache, but it is the same error all the time.
How to install IMB MobileFirst Platform CLI?
This problem only happens for latest version of mfpdev-cli v8.0.2017090705 I tried different solutions from stackoverflow, and they didn't work for me.

A: You should try this:
npm cache clean
npm set registry https://registry.npmjs.org/
npm set registry http://registry.npmjs.org/

npm install -g mfpdev-cli@latest

A: It seems they noticed these errors since mfpdev-cli's code was updated 5 hours ago (https://www.npmjs.com/package/mfpdev-cli).
I was having the same errors yesterday (even after downgrading npm to 3.10.10 and lower versions and on Windows 10 and Mac Sierra) and it's still throwing some errors in both OS but it's finally working (mfpdev -v 8.0.0-2017101013).

*

*Installed on Windows 10 with Node -v 6.9.3; npm 3.10.10.

*Installed on Mac Sierra with Node -v 6.11.4; npm 3.10.10.

Edit:
I updated npm to its latest version (5.5.1) in both OS and the installation still failed, so a downgrade to the 3.10.10 is needed (as stated on Gaurab Kumar's answer).


text:
Q: C Structure: member order and memory allocation Instead of writing a structure like,
typedef struct {
    uint8 len;          // Command length (cmd ... crc)
    uint8 cmd;          // Command code
    uint8 data_length;  // Data length
    uint8 data[12];     // Data: max 12 Byte
    uint8 crc_h;        // CRC value MSB
    uint8 crc_l;        // CRC value LSB
}CMD_TYPE;

can I write it like this ?
typedef struct { uint8 len, cmd, data_length, data[12], crc_h, crc_l; }CMD_TYPE;

If it is possible then why aren't people grouping similar members?!
what would happen to the memory allocation scheme, also is there any hidden side effects to changing the order of members other than memory loss(due to padding if i am right!).
Pardon me if this seems so silly.

A: You can write both ways, but you'll notice that the first way is more readable than the second one, and since data structures are very important in C it is in practice preferable to define them in a more verbose way.
The way you write your struct declaration (in one line per field, or every fields of the same type on the same line) don't inpact what happens at runtime.
The order of member fields inside struct is very important.
Padding, or the sizeof of your struct, or its alignment depend only of fields and their order (and of the target processor and ABI), not of the way you write them.

A:
why aren't people grouping similar members?!

Structs are what group similar members. Declaring multiple variables per line is only good when they are strongly related, such as:
int width, height;
char *begin, *end;

Or when you need multiple variables declared in a for loop.
Note that separate lines is much easier to read. Humans read well in short, aligned columns (2-dimensional) rather than long lines (1-dimensional).

what would happen to the memory allocation scheme, also is there any hidden side effects to changing the order of members otherthan memory loss(due to padding if i am right!).

Nothing that I know of.

A: The only thing your code works is that you have the same type (unsigned byte).
This is not the case most often + it's always nice to have comments above or at the right of each member.

A: Here you would get to see what the standard says about padding and memory allocation.
![This is directly from ISO C Standard DOC][1][1]: http://i.stack.imgur.com/UzgDY.png


text:
Q: Provide blame for tag wiki content I can't do a "blame" for tag wikis. For example, in https://stackoverflow.com/tags/jquery/info , I can't see what edit added "which represents less than 28% of all browsers in use", and see if a vandal sneakily changed it from "2.8%" to "28%".
As there's 107 revisions I can't see any other way of checking what edit was responsible for content (though an "expand all" option might help).

A: If you are looking for a revision that is older than last sunday (that is when SEDE gets its refresh) you could use the following query ...
select creationdate
     , rev
     , userid as [User Link]
     , comment
     , text
from (
    -- first get all rows for a single post
    -- that reflect an edit
    -- to guarantee the revision nr is correct
    -- as it is dependant on the row_number
    select creationdate
         , row_number() over (order by creationdate asc) as rev
         , userid
         , comment
         , text
    from posthistory
    where postid = ##postid:int?3607053## -- 3607053
    -- this works for wiki, for normal posts we need more magic
    -- because we have title and tag records as well
    and posthistorytypeid in (2, 5) -- initial body, edit body
) as main
where text like '%' + ##searchfor:String?represents less than 2##  + '%'

... to find the occurrences of the offending line of text.
You find the postid in the url of your browser when you click on the history link.
Do notice that the text column of the PostHistory table  contains markdown so if the text you try find has markdown in it you need to use that in your search phrase as well.


text:
Q: received sms and show in textview in android I write program for sending and receiving sms in android and display received content sms in text view. I want to received sms in program, not in inbox messege!!!
I know must use from textview.settext("smsContentEtc") but I cant use and implements it.
I put total code. sms.java for send sms and SmsReceiver.java for received sms.
please help me.
sms.java
public class SMS extends Activity {

        Button btnSendSMS;
        EditText txtPhoneNo;
        EditText txtMessage;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
            txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
            txtMessage = (EditText) findViewById(R.id.txtMessage);
            btnSendSMS.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    String phoneNo = txtPhoneNo.getText().toString();
                    String message = txtMessage.getText().toString();
                    if (phoneNo.length()>0 && message.length()>0)
                        sendSMS(phoneNo, message);
                    else
                        Toast.makeText(getBaseContext(),
                            "Please enter both phone number and message.",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        private void sendSMS(String phoneNumber, String message)
        {
            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

            PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

            //---when the SMS has been sent---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(getBaseContext(), "SMS sent",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(getBaseContext(), "Generic failure",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NO_SERVICE:
                            Toast.makeText(getBaseContext(), "No service",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            Toast.makeText(getBaseContext(), "Null PDU",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            Toast.makeText(getBaseContext(), "Radio off",
                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            }, new IntentFilter(SENT));

            //---when the SMS has been delivered---
            registerReceiver(new BroadcastReceiver(){
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode())
                    {
                        case Activity.RESULT_OK:
                            Toast.makeText(getBaseContext(), "SMS delivered",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case Activity.RESULT_CANCELED:
                            Toast.makeText(getBaseContext(), "SMS not delivered",
                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            }, new IntentFilter(DELIVERED));
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
        }
}

SmsReceiver .java
 public class SmsReceiver extends BroadcastReceiver
    {
        private TextView txtshow;
         @Override
            public void onReceive(Context context, Intent intent)
            {
                //---get the SMS message passed in---
                Bundle bundle = intent.getExtras();
                SmsMessage[] msgs = null;
                String str = "";
                if (bundle != null)
                {
                    //---retrieve the SMS message received---
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];

                    for (int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        str += "SMS from " + msgs[i].getOriginatingAddress();
                        str += " :";
                        str += msgs[i].getMessageBody().toString();
                        str += "\n";

                    }
                    //---display the new SMS message---
                   //Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
                    txtshow.setText("smsContentEtc");
                }
            }
        }

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />

    <EditText
        android:id="@+id/txtPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Message"
        />

    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top" />

    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />

    <TextView
        android:id="@+id/txt_Show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:freezesText="@bool/r"
        android:text="TextView" />

</LinearLayout>
</RelativeLayout>

Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="15" />

    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <receiver android:name=".SmsReceiver">
            <intent-filter >
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

A: You can't use setText or any other method of view's like that

txtshow.setText("smsContentEtc");

In order to modify your text view, first you should use R.findViewById and initialize your view, but since your class doesn't extends from Activity you can't use it. Instead I suggest you to use Shared Preferences
Also if you don't want sms in inbox, you can use AbortBroadcast


text:
Q: Unable to connect to mail server from PHP on windows 10 I am trying to configure my localhost Laravel project to be able to send an email, however, I am getting:
[2022-05-04 22:59:20] local.DEBUG: An error occurred while trying to create a user: adelin.ghanayem@gmail.com Swift_TransportException: Connection could not be established with host smtp.zoho.com :stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed in C:\workspace\project\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php:261
Stack trace:
#0 [internal function]: Swift_Transport_StreamBuffer->{closure}()

PHP version is as below;
php -v
PHP 8.1.5 (cli) (built: Apr 12 2022 17:38:57) (ZTS Visual C++ 2019 x64)
Copyright (c) The PHP Group
Zend Engine v4.1.5, Copyright (c) Zend Technologies
    with Xdebug v3.1.4, Copyright (c) 2002-2022, by Derick Rethans

**Note:
My time on the machine is correct!**
MAIL_MAILER=smtp
MAIL_HOST=mail.server.com
MAIL_PORT=465
MAIL_USERNAME=mail@mail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=SSL
MAIL_FROM_ADDRESS=mail@mail.com
MAIL_FROM_NAME="${APP_NAME}"


text:
Q: How to make Emacs read buffer from stdin on start? With Vim I can easily do
$ echo 123 | vim -

Is it possible to do with Emacs?
$ echo 123 | emacs23
... Emacs starts with a Welcome message

$ echo 123 | emacs23 -
... Emacs starts with an empty *scratch* buffer and "Unknown option"

$ echo 123 | emacs23 --insert -
... "No such file or directory", empty *scratch* buffer

Is it really impossible to read a buffer from a unix pipe?
Edit: As a solution, I wrote a shell wrapper named emacspipe:
#!/bin/sh
TMP=$(mktemp) && cat > $TMP && emacs23 $TMP ; rm $TMP

A: This works:
echo 123 | emacs --insert <(cat)

but, for some reason, only with graphical-mode emacs (Gnome,Konsole,GNU Emacs 23.4.1). The command:
echo 123 | emacs -nw --insert <(cat)

generates an error 'emacs: standard input is not a tty'. The same error appears when tried in raw text console.

A: It's possible to create a simple shell function which works as it is reading from stdin (although in fact it is writing to a temporary file then reading that). Here's the code I'm using:
# The emacs or emacsclient command to use
function _emacsfun
{
    # Replace with `emacs` to not run as server/client
    emacsclient -c -n $@
}

# An emacs 'alias' with the ability to read from stdin
function e
{
    # If the argument is - then write stdin to a tempfile and open the
    # tempfile.
    if [[ $# -ge 1 ]] && [[ "$1" == - ]]; then
        tempfile="$(mktemp emacs-stdin-$USER.XXXXXXX --tmpdir)"
        cat - > "$tempfile"
        _emacsfun --eval "(find-file \"$tempfile\")" \
            --eval '(set-visited-file-name nil)' \
            --eval '(rename-buffer "*stdin*" t))'
    else
        _emacsfun "$@"
    fi
}

You just use the function as an alias for emacs, e.g.
echo "hello world" | e -

or as normal from files
e hello_world.txt

Replacing emacs by emacsclient in the function works as well.

A: Another possibility not mentioned in any of the previous answers is to use /dev/stdin if your chosen Unix variant has it.
Simply trying to open /dev/stdin directly doesn't work, because Emacs does a few checks and then reports Symbolic link that points to nonexistent file. (And if Emacs would have allowed you to load the file, then trying to save it again as /dev/stdin would rarely do what the user expected.)
However combining /dev/stdin with the --insert argument does work:
echo 123 | emacs --insert /dev/stdin

It should be noted that this version only works when using X. If you need a solution which works in a terminal I suggest you look at another answer.

A: You could use process substitution:
$ emacs --insert <(echo 123)

A: offhand, something like:
$ echo 123 > tmp.txt; emacs tmp.txt

or
$ echo 123 > tmp.txt; emacs tmp.txt; rm tmp.txt

is an option. Emacs just doesn't integrate with UNIX the way vim does.

A: Correct, it is impossible to read a buffer from stdin.
The only mention of stdin in the Emacs info pages is this, which says:

In batch mode, Emacs does not display
  the text being edited, and the
  standard terminal interrupt characters
  such as C-z and C-c continue to
  have their normal effect.  The
  functions prin1, princ and print
  output to stdout instead of the echo
  area, while message and error
  messages output to stderr.
  Functions that would normally read
  from the minibuffer take their input
  from stdin instead.

And the read function can read from stdin, but only in batch mode.
So, you can't even work around this by writing custom elisp.

A: You can redirect to a file, then open the file.  e.g.
echo 123 > temp; emacs temp

jweede notes that if you want the temp file to automatically be removed, you can:
echo 123 > temp; emacs temp; rm temp

The Emacsy way to do this is to run the shell command in Emacs.
M-! echo 123 RET

That gives you a buffer named *Shell Command Output* with the results of the command.

A: It is possible, see https://stackoverflow.com/questions/2879746/idomatic-batch-processing-of-text-in-emacs
Here is echo in an emacs script (copied from the above link):
#!/usr/bin/emacs --script
(condition-case nil
    (let (line)
      (while (setq line (read-from-minibuffer ""))
        (princ line)
        (princ "\n")))
  (error nil))

or to read it into a buffer and then print it out all in one go
#!/usr/bin/emacs --script
(with-temp-buffer
  (progn
    (condition-case nil
    (let (line)
      (while (setq line (read-from-minibuffer ""))
        (insert line)
        (insert "\n")))
      (error nil))
    (princ (buffer-string))
    ))

A: The solution which works for me in bash is shown on EmacsWiki:
Add the following function into your .bashrc
e() {
local TMP;
if [[ "$1" == "-" ]]; then
    TMP="$(mktemp /tmp/emacsstdinXXX)";
    cat >"$TMP";
    if ! emacsclient --alternate-editor /usr/bin/false --eval "(let ((b (create-file-buffer \"*stdin*\"))) (switch-to-buffer b) (insert-file-contents \"${TMP}\") (delete-file \"${TMP}\"))"  > /dev/null 2>&1; then
        emacs --eval "(let ((b (create-file-buffer \"*stdin*\"))) (switch-to-buffer b) (insert-file-contents \"${TMP}\") (delete-file \"${TMP}\"))" &
    fi;
else
    emacsclient --alternate-editor "emacs" --no-wait "$@" > /dev/null 2>&1 &
fi;
}


text:
Q: Approval time for in app purchase product For adding in app purchase products, how long does apple normally take to approve one of them? I have like hundreds of in app products and i wonder how long it will take for all to be approved.

A: It usually takes anywhere from 1-2 weeks depending on how busy it is. If you have like hundreds it may take a few months to get them all approved but then again, apple doesn't check everything, just a lot of them so probably 1-3 months.


text:
Q: Terraform: Attaching an unmanaged IAM role Terraform version: 12
We have a legacy, unmanaged by Terraform IAM role that I'd like to reference from an aws_iam_policy_attachment block and I attempted the following:
  resource "aws_iam_policy_attachment" "example-attach" {
  name = "example-attach"

  roles = [
    aws_iam_role.managed-role.name,
    "arn:aws:iam::1234567890:role/unmanaged-role"
  ]

  policy_arn = aws_iam_policy.example-policy.arn
}

Dry-run works fine but when applying TF says:

– ValidationError: The specified value for roleName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-

Is there a way I can just reference the unmanaged role without defining it in TF? Or is there some non-destructive way of declaring it that doesn't change anything to do with the unmanaged role?

A: In your roles, you are providing role ARN, not role name.
Therefore, instead of ARN, you should use its name:
resource "aws_iam_policy_attachment" "example-attach" {

  name = "example-attach"

  roles = [
    aws_iam_role.managed-role.name,
    "unmanaged-role"
  ]

  policy_arn = aws_iam_policy.example-policy.arn
}

You can also use data_source
data "aws_iam_role" "example" {
  name = "unmanaged-role"
}

and the reference it in your resource:
resource "aws_iam_policy_attachment" "example-attach" {

  name = "example-attach"

  roles = [
    aws_iam_role.managed-role.name,
    data.aws_iam_role.example.name
  ]

  policy_arn = aws_iam_policy.example-policy.arn
}


text:
Q: CRC-16 specific example for serial connection While working with the following PDF, there is an example in

Section 4: CRC-16 Code and Example

(page 95 or 91) that shows a serial packet with a CRC16 value of 133 (LSB) and 24 (MSB).
However, I have tried different calculators, for example:

*

*Lammert

*Elaborate calculator

*CRC calc
but I cannot get the CRC16 values that the PDF indicates, regardless of the byte combination I use.
How can I correctly calculate the CRC16 in the example, preferably using one of these calculators? (otherwise, C/C++ code should work).
Thanks.

A: This particular CRC is CRC-16/ARC. crcany generates the code for this CRC, which includes this simple bit-wise routine:
#include <stddef.h>
#include <stdint.h>

uint16_t crc16arc_bit(uint16_t crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0;
    for (size_t i = 0; i < len; i++) {
        crc ^= data[i];
        for (unsigned k = 0; k < 8; k++) {
            crc = crc & 1 ? (crc >> 1) ^ 0xa001 : crc >> 1;
        }
    }
    return crc;
}

The standard interface is to do crc = crc16arc_bit(0, NULL, 0); to get the initial value (zero in this case), and then crc = crc16arc_bit(crc, data, len); with successive portions of the message to compute the CRC.
If you do that on the nine-byte message in the appendix, {1, 2, 1, 0, 17, 3, 'M', 'O', 'C'}, the returned CRC is 0x1885, which has the least significant byte 133 in decimal and most significant byte 24 in decimal.
Faster table-driven routines are also generated by crcany.
If you give 01 02 01 00 11 03 4d 4f 43 as hex to Lammert Bies' calculator, the very first one, called "CRC-16" gives 0x1885.
If you give 0102010011034d4f43 to crccalc.com and hit Calc-CRC16, the second line is CRC-16/ARC, with the result 0x1885.


text:
Q: bpftool: unable to understand lpm_trie keys I am entering the following commands:
$ sudo bpftool map create /sys/fs/bpf/routes type lpm_trie key 6\
 value 1 entries 256 name routes flags 1

$ sudo bpftool map update id 194 key 8 0 0 0 0 10 value 1
$ sudo bpftool map update id 194 key 16 0 0 0 107 10 value 3
$ sudo bpftool map update id 194 key 24 0 0 0 107 10 value 3
Error: update failed: Invalid argument
$

I understood the following from self experimentation:

.. key # # _ _ _ _ value ..

*

*The # are the prefix

*The _ can be anything from 0-255

What I am not able to understand is, that why a prefix of 24 doesn't work?

PS: I couldn't find any documentation, on what is the key structure to be used while updating an lpm_trie in bpf maps

I could find one web page, sharing the man pages of bpftool:

*

*https://www.mankier.com/8/bpftool-map
Another iteration of the issue:


text:
Q: Why do compilations take so long? Why do programming languages take a long to compile? Assumed c++ takes a long time because it must parse and compile a header every time it compiles a file. But I -heard- precompiled headers take as long? I suspect c++ is not the only language that has this problem.

A: Language design does have an effect on compiler performance. C++ compilers are typically slower than C# compilers, which has a lot to do with the design of the language. (This also depends on the compiler implementer, Anders Hejlsberg implemented C# and is one of the best around.)
The simplistic "header file" structure of C++ contributes to its slower performance, although precompiled headers can often help. C++ is a much more complex language than C, and C compilers are therefore typically faster.

A: Compilation does not need to take long: tcc compiles ANSI c fast enough to be useful as an interpreter.
Some thing to think about:

*

*Complexity in the scanning and parsing passes. Presumably requiring long look-aheads will hurt, as will contextual (as opposed to context-free) languages.

*Internal representation. Building and working on a large and featureful AST will take some time. Presumably you should use the simplest internal representation that will support the features you want to implement.

*Optimization. Optimization is fussy. You need to check for a lot of different conditions. You probably want to make multiple passes. All of this is going to take time.

A: They take as long as they take and it usually depends on how much extraneous stuff you inject into your compilation units. I'd like to see you hand-compile them any faster :-)
The first time you compile a file, you should have no headers at all. Then add them as you need them (and check when you're finished whether you still need them).
Other ways of reducing that time is to keep your compilation units small (even to the point of one function per file, in an extreme case) and use a make-like tool to ensure you only build what's needed.
Some compilers (IDE's really) do incremental compilation in the background so that they're (almost) always close to fully-compiled.

A: One C++ specific problem that makes it horribly slow is that, unlike almost any other language, you can't parse it independently of semantic analysis.

A: Compiling is a complicated process which involves quite a few steps:

*

*Scanning/Lexing

*Parsing

*Intermediate code generation

*Possibly Intermediate code optimization

*Target Machine code generation

*Optionally Machine-dependent code optimization

(Leaving aside linking.)
Naturally, this will take some time for longer programs.

A: Precompiled headers are way faster, as has been known at least since 1988.
The usual reason for a C compiler or C++ compiler to take a long time is that it has to #include, preprocess, and then lex gazillions of tokens.
As an exercise you might find out how long it takes just to run cpp over a typical collection of header files---then measure how long it takes to lex the output.
gcc -O uses a very effective but somewhat slow optimization technique developed by Chris Fraser and Jack Davidson.  Most other optimizers can be slow because they involve repeated iteration over fairly large data structures.

A: I think the other answers here have missed some important parts of the situation that slow C++ compilation:

*

*Compilation model that saves .obj/.o files to disk, reads them back, then links them

*Linking in general and bad slow linkers in particular

*Overly complex macro preprocessor

*Arbitrarily complex Turing-complete template system

*Nested and repeated inclusion of source files, even with #pragma once

*User-inflicted fragmentation, splitting code into too many files (even to the point of one function per file, in an extreme case)

*Bloated or low-effort internal data structures in the compiler

*Overbloated standard library, template abuse

By contrast, these don't slow C++ compilation:

*

*Scanning/Lexing

*Parsing

*Intermediate code generation

*Target machine code generation

As an aside, optimization is one of the biggest slowdowns, but it is the only slowdown here that is actually necessary by some measure, and also it is entirely optional.

A: Run Idera RAD Studio (there is a free version).  It comes with C++ and Delphi.  The Delphi code compiles in a tiny fraction of the time that C++ code doing the same thing does.  This is because C++ evolved horribly over the decades, with not much thought to compiler consiquences for it's complex context determined macros and to some degree the so called ".hpp" hell.  Ada has similar issues.  Delphi dialect of Pascal was designed from the ground up to be an efficient language to compile.  So compiler and run takes seconds, instead of minutes, making iterative debugging fast and easy.  Debugging slow to compile languages is a huge time waster, and a pain in the you know what!  BTW Anders also wrote Delphi before M$ stole him!


text:
Q: Method or Data Member not Found when Creating New Table in Access The error is showing in this part of the code:
dbs.Execute "CREATE TABLE " & Accounts.Label8 & "" & "(Date_today
TEXT,Time_In TEXT, Lunch_Out TEXT, Lunch_In TEXT, Time_Out TEXT, Status
TEXT, Notes TEXT, PRIMARY KEY (Date_today));"

This is my whole code:
Dim dbs As Database

Set dbs = OpenDatabase("Y:\Tempus Beta\Dbase.mdb", False, False,
";pwd=akgtrxx21")

dbs.Execute "CREATE TABLE " & Accounts.Label8 & "" & "(Date_today TEXT,
Time_In TEXT, Lunch_Out TEXT, Lunch_In TEXT, Time_Out TEXT, Status TEXT,
Notes TEXT, PRIMARY KEY (Date_today));"

dbs.Close

Is it because its inside a mapped drive Y:? (Though my PC has full access to that drive)

A: Assuming that Accounts is the name of your form, and Label8 is the name of a label on such form, you should access the content of the label using the Caption property, since labels do not have a Value property.
Assuming this code resides within an event handler for another control on your form, your code could become:
dbs.Execute "CREATE TABLE " & Me.Label8.Caption & " (Date_today TEXT, ...

Or, to explicitly reference the form:
dbs.Execute "CREATE TABLE " & Forms("Accounts").Controls("Label8").Caption & " (Date_today TEXT, ...


text:
Q: bash ng command not found mac bash ng command not found mac
ng serve works for me only the time when I just installed
ng serve works for me only the time when I just installed, after that I opened new terminal and after navigating to the angular project directory and try to run 'ng serve' at that time the terminal is showing 'bash ng command not found'

A: Works well for me
1. Link cli to npm: npm link @angular/cli

*Set the location of npm folder: export PATH="$HOME/.npm-global/bin:$PATH"

*Clear cache and re-install cli:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli

*Give alias to ng path : alias ng="/Users/Dharshini/.npm-global/lib/node_modules/@angular/cli/bin/ng"

*Go back to the base user: cd ~

*Change path using vim: sudo vim /etc/paths

*Add ~/.npm-global/bin to the end of the file.
type i to insert
type :wq to save and exit

*restart terminal and type: echo $PATH

*Finally know the version using: ng version

A: For solving this issue
-bash: ng: command not found

you need to set PATH, follow these steps and you'll be good to go:

*

*Set the location for npm Folder, Run any one of them:

export PATH="$HOME/.npm-global/bin:$PATH"
export PATH="$HOME/.npm-packages/bin:$PATH"

*Clear cache and Re-install Angular

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli

*Give an alias to ng Path-
PATH = /Users/Dharshini/.npm-global/lib/node_modules/@angular/cli/bin/ng

alias ng="PATH"

A: My solution:
Node modules resides in the directory /opt/node/bin
Add these two lines to your .bashrc file
NODE_BIN="/opt/node/bin"
export PATH="$PATH:$NODE_BIN"
Save and close .bashrc and run: source .bashrc
....
Currently, both node and npm runs without being referenced in .bashrc, but that is because the executable files for node and npm are located in /usr/local/bin directory which itself is by default on the $PATH. So, instead of adding the 'ng' executable to /usr/local/bin, I exported /opt/node/bin to my path instead, to prevent any other modules in the future from not being found.


text:
Q: How many ways are there to choose a group of $5$ people from $10$ men and $12$ women if at least $2$ are women? Question: There are $10$ men and $12$ women. How many ways are there to choose a group of $5$ people where at least $2$ are women?
The correct answer is $${12 \choose 2} * {10 \choose 3} + {12 \choose 3} * {10 \choose 2} + {12 \choose 4} * {10 \choose 1} + {12 \choose 5} * {10 \choose 0}$$ which is pretty straight-forward and correct.
But say we chose $2$ women first, and chose the rest $3$ from the remaining people. So the combination becomes ${12 \choose 2} * {20 \choose 3}$. But it doesn't match with the first answer. What am I doing wrong in the second process?

A: The problem with your second approach is that you are over counting.
For instance, if the group you pick is one with three women, you would count the same group 3 times.
To see this let the people you pick be $A,B,C,D,E$
where $A,B,C$ are the three women. You could have $A,B$ be the women you first choose and then have $C,D,E$ by the people you choose from the rest. Or A,C could be the first women and $B,D,E$ be the rest. Or $B,C$ be the first women and $A,D,E$ be the rest.
In the first answer this group is correctly only counted once.

A: You are over counting. The thing is every time you choose two women, and then 3 other members. You are also counting the possibility of having say 4 women, 2 of them, counted in the first term and 2 counted in second. You will have counted this case again when vice versa is true, the latter 2 women counted in the first term and first 2 women counted in the second term (and keeping the man same). So you have counted this case twice, there are total of 6 ways to count, as pointed in the comments, and so there will be several other cases counted more than once.

A: You can think of ${12\choose2}{20\choose3}$ as counting the number of ways to choose a $5$-member committee with two co-leaders, both of whom must be women.  The fact that you are distinguishing two members of each committee means that your count will be larger than simply counting (leaderless) committees, because committees with more than two women have more than one way to have co-leaders.


text:
Q: add to TAR and split archive of 147k files in a directory I have to migrate a website where are 147.000 images files in a single folder. I try to compress with gzip / tar but exited without any error message, and the archive file is 0 byte long.
$ tar cvf - web/uploads/documents/*.* | split -b 1024m - documents.tgz.

bash: /usr/bin/tar: Argument list too long

I think it's because of too many files I try to add at once. Now I'm looking for a solution to put files into seperated archive, each one with the starting letter of files (a.tar < abacus.jpeg, admire.png, amateur.gif, etc)
What command I have to use to do that?
Thank you in advance

A: Below I'm answering the 147k part of the original question.
I'm assuming that if web/uploads/documents/*.* is your list of 147k files, then the tar option -T is what you need. Below is from the tar manpage
   -T, --files-from=FILE
          get names to extract or create from FILE

As with other options in tar, you can use - inplace of stdin/out as needed. So in this case using -T - will get tar to read the list of files from stdin.
If you don't give ls any wildcards, you can just pipe the output into tarlike this
ls web/uploads/documents | tar cvf - -T - | split -b 1024m - documents.tgz.

A: First problem: if you want to include all the files from the directory into the .tgz archive, specifying the directory instead of files should work (unless there are any file/directory that doesn't match on the *.* blob and that you're trying to leave out of the archive).
Have you tryed this?:
tar cvf - web/uploads/documents | split -b 1024m - documents.tgz

Second problem: from @pmqs's answer, you can get a *.tgz archive for files starting by letters by doing something like:
for letter in {a..z}; do
  find web/uploads/documents -iname ${letter}\* | tar -T - -czf ${letter}-documents.tgz
done

This assumes that your file names start all with a lowercase letter from a to z, and will generate archives named a-documents.tgz, b-documents.tgz, etc.


text:
Q: bash script to access multiple mysql databases I all,
I have a series of MYSQL databases with different users and passwords, nevertheless the DB structure is the same for all databases.
I can't create a user with the same username and password to all of them and I need to quickly perform operations on all of them.
I was thinking about a bash script to run via cron.
Any suggestion? I was thinking to something like this but it is not working :(
#!/bin/bash
uconn=(
            'mysql -u user_db1         --password=pass_db1      db1      '
            'mysql -u user_db2         --password=pass_db2      db2      '

             )

for f in "${uconn[@]}"
do
    exec ${f}
    echo `mysql show tables`
    echo `mysql exit`
done
exit

A: Why not use the documented way?
do
  ${f} <<EOF
show tables
\\q
EOF
done

A: Just pasting the full code taking into consideration @Ansgar Wiechers:
#!/bin/bash
uconn=(
            'mysql -u user_db1 --password=pass_db1  db1'
            'mysql -u user_db2 --password=pass_db2  db2'

             )

for f in "${uconn[@]}"
    do
      ${f} <<EOF
    show tables
    \\q
    EOF
    done
exit

To execute the code from the local machine to the remote one this works for me:
ssh ssh_user@mydomain.com 'bash -s' < /local/path/to/multiple_db_connections.sh

where the content of multiple_db_connections.sh is the code above


text:
Q: JavaScript: сортировка объекта по определенному порадку ключей Есть объект: var data =  {surname: "Ivanov", name: "Pavel", profile: "12", additional: "18 y.o."};
Как отсортировать объект таким образом, чтобы не зависимо от количества ключей и значений, на первом месте в объекте стоял ключ name, затем surname, потом additional и т.д.
Т.е. чтобы порядок в объекте всегда был таким:
var data =  {name: "Pavel", surname: "Ivanov", additional: "18 y.o.", profile: "12"};

Спасибо!


text:
Q: Jubula Automated Function Testing? I am new to Jubula.Struggling hard to understand the flow of Jubula.I have installed the standalone application of Jubula(Version:8) in windows.I am finding tutorials to test java RCP application but I need to test a Website.Is it possible to test web sites using Jubula?

A: There isn't a tutorial for testing a website at the moment. However, once you've understood how tests are created in general, the steps are the same for testing a web application.
The one main difference is that the object mapping is performed via click instead of via key combination. Relevant documentation is here and in the reset of the user manual and in the reference manual:

*

*http://help.eclipse.org/mars/topic/org.eclipse.jubula.client.ua.help/content/html/userManual/toolkit/webAUT/webaut.html?cp=45_3_5
I'm assuming that you've found the "cheat sheets", which take you through the steps and workflows of working with Jubula? If not, they are under "Help/Cheat Sheets" in the application.
The Jubula forum is also a good place to ask questions:
http://www.eclipse.org/forums/index.php?t=thread&frm_id=208


text:
Q: (Overloading) - Sobrecargar Operadores en Python Como puedo sobrecargar los operadores (+, -, *, /, ... , //) sobre un objeto en python.
Ejemplo:
a = Vector(3, 5)
b = Vector(2, 7)
print(a + b)   # Output: <Vector (5.000000, 12.000000)>
print(b - a)   # Output: <Vector (-1.000000, 2.000000)>
print(b * 1.3) # Output: <Vector (2.600000, 9.100000)>
print(a // 17) # Output: <Vector (0.000000, 0.000000)>
print(a / 17)  # Output: <Vector (0.176471, 0.294118)>

Donde Vector es la clase siguiente:
class Vector(object):
   def __init__(self, x, y):
      self.x = x
      self.y = y

A: Todo en Python es un objeto. Cada objeto tiene algunos métodos internos especiales que utiliza para interactuar con otros objetos. En general, estos métodos siguen la convención de nomenclatura __action__. En conjunto, esto se denomina modelo de datos de Python.
Puede sobrecargar cualquiera de estos métodos. Esto se usa comúnmente en la sobrecarga del operador en Python. A continuación se muestra un ejemplo de sobrecarga del operador utilizando el modelo de datos de Python. La clase Vector crea un vector simple de dos variables. Añadiremos el soporte apropiado para las operaciones matemáticas de dos vectores utilizando la sobrecarga del operador.
class Vector(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, v):
        # Sumar dos Vectores
        return Vector(self.x + v.x, self.y + v.y)

    def __sub__(self, v):
        # Restar dos Vectores
        return Vector(self.x - v.x, self.y - v.y)

    def __mul__(self, s):
        # Multiplicar un Vectores por un escalar
        return Vector(self.x * s, self.y * s)

    def __div__(self, s):
        # Dividir un vector por un escalar
        float_s = float(s)
        return Vector(self.x / float_s, self.y / float_s)

    def __floordiv__(self, s):
        # Parte entera de la divicion de un vector sobre un escalar
        return Vector(self.x // s, self.y // s)

    def __repr__(self):
        # Imprima una representación amistosa de la clase Vector. De lo contrario, sería
        # <__main__.Vector instance at 0x01DDDDC8>.
        return '<Vector (%f, %f)>' % (self.x, self.y, )

a = Vector(3, 5)
b = Vector(2, 7)
print(a + b)   # Output: <Vector (5.000000, 12.000000)>
print(b - a)   # Output: <Vector (-1.000000, 2.000000)>
print(b * 1.3) # Output: <Vector (2.600000, 9.100000)>
print(a // 17) # Output: <Vector (0.000000, 0.000000)>
print(a / 17)  # Output: <Vector (0.176471, 0.294118)>

Tabla de Operadores
A continuación se encuentran los operadores que pueden estar sobrecargados en las clases, junto con las definiciones de método que se requieren, y un ejemplo del operador en uso dentro de una expresión.

Referencia:
Medium - (Overloading) — Sobrecargar Operadores en Python


text:
Q: How to implement a custom OAauth2 authorization with Spring? Looking at the new spring-security-oauth2-authorization-server library, I need to implement a custom authorization server for a resource server. Actually, I intend to manually implement the PRIVATE_KEY_JWT Authentication method that is either not yet implemented or lacking examples. I followed one good example that uses this approach (the authorization server issuing the access token to the resource server). The resource server has a simple configuration that points to my issuer (authorization server) as in the code:
spring:
 security:
   oauth2:
     resourceserver:
       jwt:
         issuer-uri: http://auth-server:9000

but this approach uses client-id and client-secret credentials like:
 @Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
    return http.formLogin(Customizer.withDefaults()).build();
}

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("client_id123")
            .clientSecret("{noop}secret123")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .scope("https://purl.imsglobal.org/spec/lti-ags/scope/score")
            .build();

    return new InMemoryRegisteredClientRepository(registeredClient);
}

I appreciate if anyone could refer me an example of either a PRIVATE_KEY_JWT implementation or a custom authorization implementation that receives a JWT and issues an access token.

A: In application.yml set up the location of the certs, and create a config class RsaKeyProperties to load them:
rsa:
  privateKey: classpath:certs/private.pem
  publicKey: classpath:certs/public.pem

Then in WebSecurityConfig:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
  @Bean
  protected SecurityFilterChain configure(
      BasicAuthFilter basicAuthFilter,
      ActivitiAuthenticationFilter activitiAuthenticationFilter,
      HttpSecurity http) throws Exception {
    return http
        // Disabling CSRF is safe for token-based API's
        .csrf().disable()
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeRequests(auth -> {
          auth.antMatchers(
               "/api/authenticate/**",
               "/api/tenants/**").permitAll();
          auth.antMatchers("/api/**").authenticated();

          // When an exception is thrown, ErrorMvcAutoConfiguration sets stuff up so that /error is called
          // internally using an anonymous user. Without this line, the call to /error fails with a 403 error
          // because anonymous users would not be able to view the page.
          auth.antMatchers("/error").anonymous();
        })
        .build();
  }

  @Bean
  public JwtDecoder jwtDecoder(RsaKeyProperties rsaKeyProperties) {
    return NimbusJwtDecoder.withPublicKey(rsaKeyProperties.publicKey()).build();
  }

  @Bean
  public JwtEncoder jwtEncoder(RsaKeyProperties rsaKeyProperties) {
    JWK jwk = new RSAKey.Builder(rsaKeyProperties.publicKey())
        .privateKey(rsaKeyProperties.privateKey())
        .build();
    JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
    return new NimbusJwtEncoder(jwks);
  }
}

The "SCOPE_" prefix that the identity server library was adding in the JWT didn't work well with spring security as far as I could figure out, so I removed that:
  /**
   * For some reason the JwtGrantedAuthoritiesConverter defaults to adding the prefix "SCOPE_" to all
   * the claims in the token, so we need to provide a JwtGrantedAuthoritiesConverter that doesn't do
   * that and just passes them through.
   */
  @Bean
  public JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
    grantedAuthoritiesConverter.setAuthorityPrefix("");

    JwtAuthenticationConverter authConverter = new JwtAuthenticationConverter();
    authConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
    return authConverter;
  }


text:
Q: drone power distribution board on a perf board I have seen some PCBs dedicated to being a power distribution board but the drone that I have has some connections for an in-frame power distribution board.
only thing is that it may be difficult to make good connections so I was thinking of making my own on a perfboard and strapping it on the frame.
is it possible to make a simple PD board on a perf board? i know the more complex PD boards have voltage regulators and capacitors but how important are those exactly?
from the way that my drone frame implied that the PD board can be on the frame itself tells me that all the power distribution can be done through simple wires. my understanding is that the PD board just allows connections in parallel to be made from the motors to the battery.
so that is something i can set up on a dedicated perf board (and perhaps add regulators and capacitors as needed) but i am not sure if it is a good idea since i haven't seen it very often and 30 amps from the battery may not be suitable for a prototyping/perfboard
edit: this is the frame and motors i am referring to. this is the battery that powers the motors and their ESCs.

A:
is it possible to make a simple PD board on a perf board?

Yes, perf boards on their own are made to do things like this, exactly.

i know the more complex PD boards have voltage regulators and capacitors but how important are those exactly?

These are extremely important (and most likely essential). If voltage regulator and capacitors are not in the board, then what is on the board?
To give a more detailed answer, we'd have to know the specs of what exactly you are trying to do. Current doesn't matter to perf boards because no current flows through perf boards. They are just insulators with holes drilled in them to hold components connected by wires. You'd need the wires and connectors specced for 30 A and the perf board specced for voltage (which they usually are for 100s if not 1000s of volts).


text:
Q: C++ to Python Code (Arduino to Raspberry Pi) - Using Ultrasonic I have a Ultrasonic (HCSR04) connected to a Raspberry PI 2015. I have the code for the Ultrasonic using C++ which I previously did in Arduino but I am having trouble translating it into Python code in order to use it in Raspberry PI. Could someone help me with this?
Here are my code that are written in Arduino C++:
#include <math.h>

const int trigPin = 10;
const int echoPin = 9;
int g = 12; //green led
int r = 13; //red led

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);

  pinMode(g, OUTPUT);
  pinMode(r, OUTPUT);

}

void loop() {
  digitalWrite(trigPin, LOW);  // Clears the trigPin
  delayMicroseconds(2);  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  // Reads the echoPin, returns the ultrasound wave travel time in microsec
  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;  // Calculating the distance

  // Prints the distance on the Serial Monitor
  Serial.print ("Distance(cm): ");
  Serial.println(distance);
  delay(1000);

  if(distance > 10)
  {
    digitalWrite(r, LOW);
    digitalWrite(g, HIGH);
    delay(250);
  }
  else
  {
    digitalWrite(g, LOW);
    digitalWrite(r, HIGH);
    delay(100);
  }
}

A: You don't need this void setup() Linux is take a care of this. Here is Python code:
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)

    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()

    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2

    return distance

if __name__ == '__main__':
    try:
        while True:
            dist = distance()
            print ("Measured Distance = %.1f cm" % dist)
            time.sleep(1)

        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")
        GPIO.cleanup()