text:
Q: jQuery each row items click append data html after 3rd items I have a html code like below,
Each list have a class and a button,
So while the user click the button, it should append a html using json and append after the 3rd items, The details is represent the item details, I had tried using nth-child, but it will make my each 3n+3 append the html, what I want is when the user click the 1,2,3 items it will append in after 3rd, when click on 4,5,6 item, it will append a details html on after 6.
Please ignore the data pulling. This is the way I using
$('.item').eq(i % 3).after(html_details);
Here is my Html

List 1

List 2

List 3

List 4

List 5

List 6

Here is my jQuery
$('.item').each(function(i){

    $(this).find('a').on('click',function(){

      var html_details = detailsTemplate(data[i]);

        console.log(i)

        $('.Details').remove();

        $('.item').eq(i % 3).after(html_details);

        $('.Details').hide();
        $('.Details').slideToggle();

      return false;

    })

How would I do that?

A: Your logic can be this:
$('.item').eq(i + 3 - (i % 3) - 1).after(html_details);

Here is some explanations. 3 - (i % 3) calculates how many items needed to skip ahead. Then you add up this number to current index i to get the item to append content after. I also added - 1 in order to be able to use after instead of before, so it also works with the last item.
Check the demo below.

$('.item').each(function (i) {
    $(this).find('a').on('click', function () {
        var html_details = detailsTemplate(data[i]);
        console.log(i + 3 - (i % 3) - 1)
        $('.Details').remove();
        $('.item').eq(i + 3 - (i % 3) - 1).after(html_details);
        $('.Details').hide();
        $('.Details').slideToggle();

        return false;
    });
});

var data = [0, 1, 2, 3, 4, 5, 6];
function detailsTemplate(d) {
    return '
' + (d + 1) + '
';
}

List 1 link

List 2 link

List 3 link

List 4 link

List 5 link

List 6 link

A: you can use for loop rather than each for indexing. In your case
   for(var i=0;i<$('.item').length;i++)
    {
    $(this).find('a').on('click',function(){

          var html_details = detailsTemplate(data[i]);
                console.log(i)

            $('.Details').remove();
             if(i%3==0)
             {
                $('.item')[i].after(html_details);
              }
            $('.Details').hide();
            $('.Details').slideToggle();

        }

if you use .each() then you have to introduce count inside it and check count value

A: You can use:

List 1

List 2

List 3

List 4

List 5

List 6

and:
$('.item').each(function(i) {
    $(this).find('a').on('click',function() {
        var html_details = '
DETAILS
'; //detailsTemplate(data[i]);

        $('.Details').remove();

        var index = (Math.floor(i / 3) * 3) + 2;

        $('.item').eq(index).after(html_details);

        $('.Details').hide();
        $('.Details').slideToggle();

        return false;
    })
})

Here is the corresponding jsfiddle.

A: Here is my answer.
But the way I use a bit noob.
So I will change it more clean.
var details            = $('.details').html();
var detailsTemplate    = Handlebars.compile(details);
var detailsPlaceholder = $(this);

  $('.item').each(function(i){

    $(this).find('a').on('click',function(){

      $('.details').remove();

      var html_details = detailsTemplate(data[i]);
      var itemIndex = $(this).closest('.item').index()
      var itemWidth = $('.item').outerWidth(true)

      var position = $(this).closest('.item').offset().left

      tiles3(i,itemIndex);

      function tiles3(i,itemIndex){

          if(i%3 == 0){

              var left =  $('.item').length -  itemIndex;

              if(left == 1){

                $('.item').eq(i).after(html_details)

              } else if(left == 2) {

                $('.item').eq( (i%3) + i + 1 ).after(html_details)

              } else {

                $('.item').eq( (i%3) + i + 2 ).after(html_details)

              }

          } else if(i%3 == 1){

              var left =  $('.item').length -  itemIndex;

              if(left == 1){

                $('.item').eq(i).after(html_details)

              } else {

                $('.item').eq( (i%3) + i ).after(html_details)

              }

          } else {

              $('.item').eq( i ).after(html_details)

          }
      }

      return false;

    })

  })
}


text:
Q: Is there a name for, and some significance of, $\mathbb E e^{X^T \Omega X}$? Let $X \in \mathbb R^r$ be a random vector. The moment generating function (MGF) $m(t) = \mathbb E e^{X^Tt}$ is ubiquitous in statistics and probability.
In my research, I've had to deal with the scalar-valued matrix function $M(\Omega) = \mathbb E e^{X^T\Omega X}$. I'm interested in knowing whether this function has a name, and if it has some significance more generally?
The only thing I could come up with myself was that, since $\mathrm{vec(X^T\Omega X)} = (X^T \otimes X^T)\mathrm{vec}(\Omega)$, it can be thought of as the MGF for $X \otimes X$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JDeveloper alternative for eclipse shortcuts I've been using eclipse for about 10 years now, and today I will be (forced to) use JDeveloper for the first time.
Being a big fan of the eclipse shortcuts, I would like to know some JDeveloper alternatives for my favorite shortcuts:

*

*Ctrl-3 (Quick access)

*Ctrl-Shift-1 (or Ctrl-1, depending on your keyboard) (Quick Fix)

*Ctrl-Shift-L (Show the shortcuts :-))

*Shift-Enter (Add a new line below the current one)

*Alt-↓ (Move line(s))

*Ctrl-Alt-↓ (Copy line(s))

Any other shortcuts in JDeveloper I should know about? I have found this link, but the list is way too short.

A: I once battled JDeveloper for two years and somehow lived to tell about it.  If you're using 11g, here is a trick you can use to load the Eclipse shortcut scheme.  I highly recommend doing this as there's really no value in learning the native key bindings.
A second piece of advice, do whatever it takes to get off whatever project you're required to use JDeveloper for. It is an ancient, buggy IDE designed to cater to an obscure, buggy framework.  You will quickly find yourself handcuffed by JDeveloper and ADF, it is in no way in the same league as Eclipse/Netbeans/IntelliJ.  You will hate it. You have been warned.

A: Here is the official link for JDeveloper shortcuts:
http://download.oracle.com/docs/cd/E16162_01/user.1112/e17455/working_jdev.htm#OJDUG159
Hope that helps ;)


text:
Q: Ruby: Create a symbol searching method So this is supposed to be a method that tells you if there is a + symbol before AND after every letter (a-z). Can't figure out why it always returns false. An example of when it should return true is if the input is +d+. It should return false however if the input was +d+d
def SimpleSymbols(str)
  idx = 0
  while idx < str.length
    if str[idx].ord > 96 && str[idx].ord < 123
      return false if str[idx - 1] != "+" || str[idx + 1] != "+"
    end

    idx += 1
  end
  return true
end

SimpleSymbols(STDIN.gets)

A: This returns true for me.  But I'm wondering if you're getting bit by a line termination issue?  Since gets() keeps the line termination, what do these two lines return in your environment:
SimpleSymbols("+d+d")

and
SimpleSymbols("+d+d\n")

?  That might provide a pointer to your problem.

A: When you start the loop and idx is set to 0, the "str[idx - 1]" will equal -1. Setting the statement to check the last character not the first.
return false if str[idx - 1] != "+" || str[idx + 1] != "+"
So "f++d+" will pass as TRUE while it's actually false.
GL


text:
Q: How to check if a point is snapped to a line in QGIS I have two vector classes, sg_point and sg_line. Any sg_point HAS to be snapped to a sg_line. I should not find errors if I use snapping correctly, but in case there are errors how do I check in QGIS?
I have tried select by locaction, but no matter what option I use, either I get all points (useless) or no points (also useless). I cannot get either only the points that are snapped nor only the points that are not snapped to a sg_line instance.
What am I doing wrong?
I am using Pisa 2.10.1
UPDATE -
I have tested many configurations. It seems to me that select by location only works when the snapped point is not a vertice. When it is snapped to a segment, it is not selected. Is this working as expected, or is this a bug?


text:
Q: Java - How to store an integer objects value into an integer array? I have an integer, lottoNum generated from the java utility Random. I need to store the integer value of int lottoNum in an integer array called sumArray, so I can iterate through the array to add the value of each number. If lottoNum = 123456, the integer array should be sumArray[] = {1, 2, 3, 4, 5, 6}; I'm not sure how to do this and hope I can get some help.
This is my code for the int lottoNum
// generate sets of random numbers between 1-9
randNum = genNumbers.nextInt(10);
// store the numbers into lottoNum
lottoNum = (lottoNum * 10) + randNum;

lottoNum gets passed into another class where the math is supposed to be performed, then returned as sum.
This is my code to iterate through the array to add the numbers up
public int doMath(lottoNum) {
    int sumArray[] = {};
    int sum = 0;
    for (int i : sumArray)
    sum += i;
    return sum;
}

How (or can I) place the value of lottoNum into the {} of the array? I was reading something about splitting the numbers in lottoNum, but I'm completely lost on this.
I also found this code to get separate digits of an integer, but an not sure how to put the output into the array.
int number; // = some int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

Help is greatly appreciated.

A: The result will be in arr, and will be in the reversed order of the digits in the original number. Say number is 123, and the result array will be {3, 2, 1}.
int number; // = some int

List<Integer> arrList = new ArrayList<>();

while (number > 0) {
    // To keep the same order, use arrList.add(0, number % 10);
    arrList.add(number % 10);
    number = number / 10;
}

Integer[] arr = new Integer[arrList.size()];
arrList.toArray(arr);

or you can convert the number to string and then convert each character to a digit;
int number; // some number
char[] numChars = Integer.toString(number).toCharArray();
int arr[] = new int[numChars.length];

for (int i = 0; i < numChars.length; ++i) {
    arr[i] = numChars[i] - '0';
}


text:
Q: Handling objects of different classes in a derived List class I have several classes (A, B, C, ...) that all use a List<AnotherClass> to store references to 'other' objects. But 'other' is different for each of the classes A, B, C.
So
Class A contains List<Class_X>
Class B contains List<Class_Y>
Class C contains List<Class_Z>
Instead of implementing Add / Delete / Search (etc) functions in A, B, C it seems logical to me to create a class ListRef<T> from List<T>
public class ListRef<T>: List<T>
{
    protected ListRef<T> ListOfObjects = null;
    protected string name = null;

    public ListRef<T>
    {
        ListOfObjects = new ListRef<T>();
    }
}

Using the code above (is this the right code for what I want?) I don't know how I can supply the right class (Class_X, Class_Y, Class_Z) replacing/specifying <T> in the constructor of each class (A, B, C) that will use ListRef.
In the constructor of class A I would like to write something like:
public A() : base<Class_X>
{
}

How can I specify from WITHIN class A what kind of objects need to be stored in ListOfObjects?
I prefer NOT to write
public A()
{
    ListOfObjects = new ListRef<Class_X();
}

as I would like to have ListOfObjects declared private instead of protected

Inside Listref I JUST want to be able to Add, Delete, Search objects. So I'm not actually using those classes (Class_X, Class_Y, Class_Z).
currently I have
public class A
{
     private List<Class_X> ListOfObjects = null;
     A()
     {
         ListOfObjects = new List<Class_X>();
     }

     public void Add(string Name)
     {
        Class_X Object = new Class_X(Name);
        ListOfObjects.Add(Object);
     }
     public void Delete(Class_X Object)
     {
        ListOfObjects.Remove(Object);
     }
}

and the same kind of code for class B (using Class_Y)   and for class C (using class_Z).
To me it seems logical to use ONE class  ListRef to perform the Add and Delete operations and maintain the list for all classes I use.
(of course the real code is more complicated)

A: Here is how I would recommend doing it...
public class ABC_Base<TChild>
{
    public IEnumberable<TChild> Children { get; set; }

    public void AddChild(TChild item)
    {
    }

    public void RemoveChild(TChild item)
    {
    }

    //etc
}

public class A : ABC_Base<X> // X is the type for your child
{

}

//Used like so...
A myA = new A();

myA.AddChild(new X());

// or if you are wanting to specify when created then this...

public class A<TChild> : ABC_Base<TChild>
{
}

//Used like so...
A myA = new A<X>();
A myOtherA = new A<Y>();

myA.Addchild(new X());
myOtherA.AddChild(new Y());

A: If I understand you question correctly, it sounds like what you want to do is create a group of classes A, B, C, etc.. that each manage a collection of some other type (X, Y, Z) - but you don't want to duplicate some of the list management logic across A, B, and C.
There are two different ways to achieve this.
First, the inheritance approach: you could give A, B, and C a common generic base class that is parameterized on the type of the item each will manage. Here's a code example:
public abstract class ABCBase<T>
{
   protected IList<T> m_List = new List<T>();

   // methods that manage the collection
   // I chose to make the virtual so that derived
   // classes could alter then behavior - may not be needed
   public virtual void Add( T item )    { ... }
   public virtual void Remove( T item ) { ... }
   public virtual int  Find( T item )   { ... }
}

public class A : ABCBase<X> { ... }

public class B : ABCBase<Y> { ... }

public class C : ABCBase<Z> { ... }

Second, is the composition approach: create a manager class for your colleciton that implements the operations on the child list, and aggregate that in each of A, B, and C:
public class ListManager<T>
{
   private IList<T> m_List = new List<T>();

   public void Add( T item )    { ... }
   public void Remove( T item ) { ... }
   public int  Find( T item )   { ... }
}

public class A
{
   public ListManager<X> ListOfX { get; protected set; }

   public A() { ListOfX = new ListManager<X>(); }
}

public class B
{
   public ListManager<Y> ListOfX { get; protected set; }

   public B() { ListOfY = new ListManager<Y>(); }
}

public class C
{
   public ListManager<Z> ListOfX { get; protected set; }

   public C() { ListOfX = new ListManager<Z>(); }
}

You could also choose to mix both of these approaches - creating a list management class but also creating base class (or interface) for A, B, C - so that each exposes a consistent property ChildList (or some such) that consumers could use without always having to know the type actual types A, B, C.

A: How about
public interface ISomeOtherClass
{
}

public class Class_X : ISomeOtherClass
{
}

public class Class_Y : ISomeOtherClass
{
}

public class BaseClass<T> where T : ISomeOtherClass
{
   public ListRef<T> OtherObjects { get; set; }
}

public class A : BaseClass<Class_x>
{
}

public class B : BaseClass<Class_Y>
{
}

A: I hope I am correctly understanding your problem.  Here is how I would do it:
interface ILetter<T>
{
    IList<T> OtherObjects { get; }
}

class A : ILetter<Class_X>
{
    public IList<Class_X> OtherObjects
    {
        get { /* ... */ }
    }
}

class B : ILetter<Class_Y>
{
    public IList<Class_X> OtherObjects
    {
        get { /* ... */ }
    }
}

// etc...

With this interface you can be sure that each type has a public IList<T> property that you can use for any operations you wish.


text:
Q: iOS app SSL .p12 Authentication - bad certificate error (-9825) Updates
Edit 2/6/14:
I created a local Apache Tomcat server to test SSL w/ certificate authentication.  I was successful! Everything works as expected, using both of my approaches below. (MKNetworkKit, and custom code).  While this does tell me my code is working, my original issue is still not solved.  I updated the title of the question to more specifically reflect the issue.  Does anyone know if SAP Portal needs special settings to accept certificates from an iOS app?  Remember, I was able to successfully authenticate using Safari mobile after importing the CA and .p12 into the shared keychain, I was only unsuccessful in code (which I now know the code works, just not with the portal).

I am creating a very simple iOS7 Cordova 3.2 application with a custom plugin to get data from an SSL web service by providing only a .p12 certificate for authentication (no basic auth or other user credentials needed).  I am performing all tests on a physical iPad (no simulator).  The web service lives on a development SAP NetWeaver portal box using a self signed certificate.  For now, I imported the server's CA into the iOS keychain to avoid certificate trust errors.  For testing purposes, my .p12 certificate is bundled locally inside the app, in the root of the mainBundle.
When trying to connect to the web service I get the follow error in the console:
CFNetwork SSLHandshake failed (-9825)
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9825)
Error Domain=NSURLErrorDomain Code=-1205 "The server "myhostremoved.com" did not accept the certificate." UserInfo=0x14e99000 {NSErrorFailingURLStringKey=https://myhostremoved.com/sslwebservice/, NSErrorFailingURLKey=https://myhostremoved.com/sslwebservice/, NSLocalizedDescription=The server "myhostremoved.com" did not accept the certificate., NSUnderlyingError=0x14d9b1d0 "The server "myhostremoved.com" did not accept the certificate.", NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x14d94720>}

According to Apple's documentation site, the -9825 error referes to a bad certificate.

There are many questions on SO related to what I am trying to do, but none specifically pertaining to the error I am seeing.  I approached the development of the code in two different ways.

First I tried to use code already on SO, adapting it to my use case.  See code below:
- (void)startConnection:(CDVInvokedUrlCommand*)command {
    NSDictionary *options = [command.arguments objectAtIndex:0];
    NSURL *serverURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [options objectForKey:@"host"]]];//hostname provided by Cordova plugin, but could just as easily be hardcoded here
    NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:serverURL];
    NSURLConnection *connection = nil;
    connection = [[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        // gets a certificate from local resources
        NSString *thePath = [[NSBundle mainBundle] pathForResource:@"mycert" ofType:@"p12"];
        NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
        CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;

        SecIdentityRef identity;
        // extract the ideneity from the certificate
        [self extractIdentity :inPKCS12Data :&identity];

        SecCertificateRef certificate = NULL;
        SecIdentityCopyCertificate (identity, &certificate);

        const void *certs[] = {certificate};
        CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL);
        // create a credential from the certificate and ideneity, then reply to the challenge with the credential
        NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];

        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];

}

- (OSStatus)extractIdentity:(CFDataRef)inP12Data :(SecIdentityRef*)identity {
    OSStatus securityError = errSecSuccess;

    CFStringRef password = CFSTR("MyCertPassw0rd");
    const void *keys[] = { kSecImportExportPassphrase };
    const void *values[] = { password };

    CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import(inP12Data, options, &items);

    if (securityError == 0) {
        CFDictionaryRef ident = CFArrayGetValueAtIndex(items,0);
        const void *tempIdentity = NULL;
        tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity);
        *identity = (SecIdentityRef)tempIdentity;

    }

    if (options) {
        CFRelease(options);
    }

    return securityError;
}

On my second approach, I tried to use the MKNetworkKit library, which abstracts away alot of the code needed to interface with the certificate.  All you need to do is provide the path to the certificate and the password.  Again, I get the same error as above.  This code is below.
- (void)startConnection:(CDVInvokedUrlCommand*)command {
    NSDictionary *options = [command.arguments objectAtIndex:0];
    NSURL *serverURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [options objectForKey:@"host"]]];//hostname provided by Cordova plugin, but could just as easily be hardcoded here

    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:serverURL customHeaderFields:nil];
    MKNetworkOperation *op = [engine operationWithPath:nil params:nil httpMethod:@"GET" ssl:YES];

    NSString *thePath = [[NSBundle mainBundle] pathForResource:@"mycert" ofType:@"p12"];
    [op setShouldContinueWithInvalidCertificate:YES];
    op.clientCertificate = thePath;
    op.clientCertificatePassword = @"MyCertPassw0rd";

    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
    }];

    [engine enqueueOperation:op];

}

I get the same error using both approaches.  Any ideas?
Known information

*

*I know that the app is finding .p12 certificate because when I fudge the path to the .p12 cert, I receive an error saying it cannot find the certificate which I don't normally see otherwise.

*I know the password I am providing for the certificate file is correct because when I fudge the password, I receive an error regarding the password I don't normally see otherwise.

*I don't think certificate trust is an issue because if I remove my server's CA from the iOS keychain, I get an error in the console specifically stating the server cannot be trusted.  After adding the CA back, this error no longer occurs, but I get same error as above (-9825)

Others tests
When providing basic auth in code (bypassing certificate authentication), everything works as expected and I receive no errors.
I have also tried all the same steps above, but using a .pfx file instead of my .p12 certificate, same errors.
The SSL service works in mobile Safari.  I imported the .p12 certificate into my keychain via the iPhone Configuration utility, and tested the web service via mobile safari. Everything works as expected, no errors occur (no trust errors either), and I receive the expected output.
I am also able to successfully test the web service on my desktop using the rest-client utility
TL;DR
I am trying to authenticate to an SSL web service using only a .p12 certificate in objective-c.  I know the server and web service both work with the cert for auth, but I keep getting errors when I try to establish the connection in objective-c, so something must be wrong in my code. Please help!

A: I finally was able to resolve this problem.  I found the answer here
http://oso.com.pl/?p=207&lang=en
It looks like the certificate was being sent twice, causing an error on the server.
Incase the above link dies, I found the same solution already on SO (but for a different question and error).
When using Client Certificate Authentication, why do I keep getting NSURLErrorDomain Code=-1206?
Ultimately, changing this:
    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistenceNone];

to this:
    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:nil persistence:NSURLCredentialPersistenceNone];

solved my issue.  It would be nice if anyone could offer more insight into this issue.

A: In some cases handshake may fail because server also asks intermediate and root certificates.
To fix it do the following:
Authentication challenge part:
    OSStatus status = extractIdentityAndTrust(inP12data, &myIdentity, &myTrust, password);

    SecCertificateRef myCertificate;
    SecIdentityCopyCertificate(myIdentity, &myCertificate);

    CFIndex count = SecTrustGetCertificateCount(myTrust);

    NSMutableArray* myCertificates = [NSMutableArray arrayWithCapacity:count];
    if (count > 1) {
        for (int i = 1; i < count; ++i) {
            [myCertificates addObject:(__bridge id)SecTrustGetCertificateAtIndex(myTrust, i)];
        }
    }

    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:myCertificates persistence: NSURLCredentialPersistenceForSession];

Extracting method
OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data,
                             SecIdentityRef *outIdentity,
                             SecTrustRef *outTrust,
                             CFStringRef keyPassword) {

OSStatus securityError = errSecSuccess;

const void *keys[] =   { kSecImportExportPassphrase };
const void *values[] = { keyPassword };
CFDictionaryRef optionsDictionary = NULL;

/* Create a dictionary containing the passphrase if one
 was specified.  Otherwise, create an empty dictionary. */
optionsDictionary = CFDictionaryCreate(
                                       NULL, keys,
                                       values, (keyPassword ? 1 : 0),
                                       NULL, NULL);

CFArrayRef items = NULL;
securityError = SecPKCS12Import(inPKCS12Data,
                                optionsDictionary,
                                &items);

if (securityError == 0) {
    CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
    const void *tempIdentity = NULL;
    tempIdentity = CFDictionaryGetValue (myIdentityAndTrust,
                                         kSecImportItemIdentity);
    CFRetain(tempIdentity);
    *outIdentity = (SecIdentityRef)tempIdentity;
    const void *tempTrust = NULL;
    tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);

    CFRetain(tempTrust);
    *outTrust = (SecTrustRef)tempTrust;
}

if (optionsDictionary)
    CFRelease(optionsDictionary);

if (items)
    CFRelease(items);

return securityError;  }

Please note that loop from 1 (not 0) is not a mistake. First cert is already added to "myIdentify", so only other certs should be passed as certificates, otherwise most likely you'll receive an error during handshake because of duplicating.


text:
Q: How to create complex shortcut keys for windows application I know how to implement Ctrl+A or Ctrl+k shortcut in Windows form. But as this application as lots of Module, I want to create Complex/Fancy shortcuts like Ctrl+C,A or Ctrl+C,Alt+A which opens up Specific one module. Is it possible to do? if so, How can I do it?
I tried to google, but couldn't able to do it. I found Ctrl+C,A alike shortcuts in Visual Studio, e.g. Ctrl+K, S. When Pressing Ctrl+K, status bar is saying : "Ctrl+K was pressed, waiting for second key of chord.." and then pressing S, it's showing "The key combination Ctrl+K, S is bound to....."
Is it possible to do for normal windows application? if not, what other method I can use?


text:
Q: why i get notice:undefined constant PHPWEATHER_BASE_DIR I want to make use of project PHPWeather 2.2.2 but it gives me many errors
In line 1 I got an error message
Use of undefined constant PHPWEATHER_BASE_DIR - assumed 'PHPWEATHER_BASE_DIR' in C:\wamp\www\phpweather-2.2.2\data_retrieval.php on line 1

Here is a code
require_once(PHPWEATHER_BASE_DIR . '/db_layer.php');

class data_retrieval extends db_layer {
  var $metar;
  var $metar_time;
  var $metar_arch;
  var $taf;
  var $icao_data;
  var $time_from;
  var $time_to;

  function data_retrieval($input = array()) {

    /* We start by calling the parent constructor. */
    $this->db_layer($input);

    /* Then we set the station. */
    $this->set_icao($this->properties['icao']);

    $this->metar = false;
    $this->metar_time = false;
    $this->metar_arch = false;
    $this->time_from = false;
    $this->time_to = false;

  }
}

A: try adding this
define('PHPWEATHER_BASE_DIR', dirname(__FILE__) . '/..');

before
require_once(PHPWEATHER_BASE_DIR . '/db_layer.php');

Please note that this is just an estimation you need to specify the proper location in place of '/..' where your db_layer.php exists from the root of your project


text:
Q: How to find number of lines of a Large CSV file without reading it - using R? It is required to find the number of lines of a pretty big CSV file (about 100 GB) without reading it completely -- since it doesn't fit inside the RAM. What is the MOST OPTIMIZED way to achieve this in R ?
Edit:
I have already tried out the following
reading a text file in R line by line
Read Large File line by line in R without header
But seems to be pretty slow - for just finding number of rows ...


text:
Q: Why does v-model mutate Vuex state instead of componets's local data? I make my first Vue project, everthing was OK, so I added Vuex (It wouldn't be superfluous in the future and I tried it for the sake of interest), and everything still was OK, untill I enabled strict mode. It turns out, component(s) mutate(s) state of storage outside mutation, however I haven't wanted it and have created a local copy of nessesary object in a component with data().
My intention was to create a local object in the parent component, then pass its properties to child components with v-model (I know it's an event-driven syntactic sugar for v-bind and v-on:input) and when local object gets updated (inside children by virtue of v-model), a method of parent component dispatches action to store. Instead of it, I get an error message due to outside mutating, moreover it happens only at the second and subsequent input events.
Also, it works if I replace these lines in ProdutRow component watcher:
item: {
                handler(value) {
                    this.$store.dispatch('updateProduct', {
                        product: value,
                        index: this.index,
                    });
                },
                deep: true,
            }

with: product: {...value}, or Object.assign({}, value), but the same code in the store's action doesn't: it throws the same error.
Does not data() create a copy of the specified prop? If it does, why Object.assign not working in store?
Code:
store.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    import {ADD_PRODUCT, UPDATE_PRODUCT, DELETE_PRODUCT, UPDATE_FORM, UPDATE_PREPAYMENT_IN_PERCENT} from './mutation-types';
    import _ from 'lodash';

    Vue.use(Vuex);

    let id = 1;
    const product = {
        order: id++,
        name: '',
        size: '',
        content: '',
        price: 0,
        number: 1,
        discount: '',
        guarantee: 0,
        promotion: 0,
        location: '',
        sum: 0,
    };
    export default new Vuex.Store({
        strict: true,
        state: {
            products: [
                Object.assign({}, product),
            ],
            form: {
                prepaymentInPercent: 100,
            }

        },
        getters: {
            total(state) {
                return state.products.reduce(function (acc, cur, index, array) {
                    return array.length > 1 ? acc + cur.sum : cur.sum;
                }, 0);
            },
            rest(state, getters) {
                return getters.total - getters.prepaymentInRub;
            },
            prepaymentInRub(state, getters) {
                return getters.total * state.form.prepaymentInPercent / 100;
            }
        },
        mutations: {
            [ADD_PRODUCT](state, product) {
                state.products.push(product);
            },
            [UPDATE_PRODUCT](state, {product, index}) {
                state.products.splice(index, 1, product);
            },
            [DELETE_PRODUCT](state, index) {
                state.products.splice(index, 1);
            },
            [UPDATE_FORM](state, form) {
                state.form = form;
            },
            [UPDATE_PREPAYMENT_IN_PERCENT](state, percent) {
                state.form.prepaymentInPercent = percent;
            }

        },
        actions: {
            addProduct({commit}) {
                let newProduct = Object.assign({}, product);
                newProduct.order = id++;
                commit(ADD_PRODUCT, newProduct);
            },
            updateProduct: _.debounce(function ({commit}, product) {
                commit(UPDATE_PRODUCT, product);
            }, 1),
            deleteProduct({commit, state}, index) {
                state.products.length > 1 && commit(DELETE_PRODUCT, index)
            },
            updatePrepaymentInPercentByRub({commit, getters}, rubles) {
                let percent = Math.round(rubles / getters.total * 100);
                commit(UPDATE_PREPAYMENT_IN_PERCENT, percent);
            }
        },
    });

ProductTable.vue
    <template>

          +
          Номер
          Название
          Размер
          Наполнение
          Цена
          Количество
          Скидка
          Акция
          Сумма
          Гарантия
          Заказ
          JSON

        <template v-for="(product, index) in products">
          <ProductRow
                  :initialItem="product"
                  :key="product.order"
                  :index="index"
          />
        </template>

          {{total}}
          {{json}}

    </template>

ProductRow
<template>

        {{indexFrom1}}
        <Editable v-model="item.name"/>
        <Editable v-model="item.size"/>
        <Editable v-model="item.content"/>
        <Editable v-model.number="item.price"/>
        <Editable v-model.number="item.number"/>
        <Editable v-model="item.discount"/>

            <select v-model="item.promotion">
                <option selected="" value="0">Нет</option>
                <optgroup label="Новоселы">
                    <option data-text="Нов." value="5">Новоселы -5%</option>
                    <option data-text="Нов." value="10">Новоселы -10%</option>
                    <option data-text="Нов." value="15">Новоселы -15%</option>
                </optgroup>
            </select>

        {{sum}}
        <Editable v-model.number="item.guarantee"/>

            <select v-model="item.location">
                <option selected value="">Услуги</option>
                <option value="СКЛАД">Склад</option>
                <option value="ЗАКАЗ">Заказ</option>
            </select>

            Удалить

</template>

A: No, data() does not create a copy of the item object so in this code you are passing the object by reference.
data() {
   return {
        item: this.initialItem
    };
}

This means that the product object from your store is the same exact object as this.item in your ProductRow component. So when you attach a v-model to the inputs you are directly changing the product object in your store.
Cloning the product object using Object.assign() in your store will not work. You have to do the cloning in the ProductRow component.
data() {
   return {
      item: Object.assign({}, this.initialItem)
   };
}

This will create a copy so that you will not be directly modifying the product in the store.


text:
Q: jQuery и сайт на Opencart
На одной кнопке 2 события навешаны при клике, при чем они одинаковые. Как мне найти первой событие что "главная страница:450" и отредактировать?
в индекс.php нету ничего

A: Если используешь Chrome, то

*

*F12

*Elements - справа будет Event Listeners

*Находишь свое событие (click, blur etc)

*Находишь свой элемент и по строчке определяешь событие


text:
Q: Not all of my child processes running the end of my for loop I have a project where I need to create N child processes and to do an election between them. So I've made so far a function to generate the random number (for the election, they have to compare the number they were attributed then the lower number is elected). Then, I'm stuck to make them communicate with pipes to compare the number. My problem is that only my first child process run the end of this for loop I really don't understand why. Here's all of my code so far :
void comparerIdElection(int (*pipes)[2], int numProc)
{

for (int i = 0; i < NBPROC; ++i)
    {
    if (numProc!=i)
    {
        close(pipes[i][0]);
        printf("je suis %d et je ferme la pipe [%d][0]\n",getpid(),i );
    }else printf("je suis %d et je laisse la pipe [%d][0] \n",getpid(),i );
    if (numProc +1 != i)
    {
        close(pipes[i][1]);
        printf("je suis %d et je ferme la pipe [%d][1]\n",getpid(),i );
    }else printf("je suis %d et je laisse la pipe [%d][1] \n",getpid(),i );
}

//Generate a random number for my child process
int GenererIdElection ()
{
    srand(time(NULL)^getpid()<<16);
    return rand()%NBPROC;
}

   int main(int argc, char const *argv[])
{
    int N = NBPROC, idElection, numProc= -1;
    int pere = getpid();
/*Creation du nombre de pipe adequat */
    int pipes[N][2];
    int pids[N];
/* Indique l'etat du processus C = Candidat, B =B battu , E = Elu*/
    char etat ;
    printf("le nombre de processus que je crée est : %d\n", N);

// Creation d'un nombre de N processus fils par le même pere
    for (int i = 0; i < N; ++i)
    {
            if(getpid()==pere){
                fork() ;
                numProc ++ ;
            }
    }

    if (getpid() != pere)
    {
        pids[numProc] = getpid();
        etat = 'C';
        while(etat == 67)
        {
            idElection = GenererIdElection();
            printf("je suis %d et j'ai eu %d, mon num proc est %d \n",getpid(), idElection, numProc);
            comparerIdElection(pipes, numProc);
            printf("hop\n");
            etat ='B';

        }

    }

    if (getpid()==pere)
    {
    /*On attend la fin de chaque processus
     pour mettre un terme au processu pere*/
        for (int i = 0; i < N; ++i)
        {
            wait(&pids[i]);
        }
    }
    exit(0);
}

And here is what happens once executed (I translated all of printf) :
[terminal][1]
Edit : As I can't post image due to a lack of reputation I copy/pasta :
I'm 1854 i got 1, my numproc is : 0
I'm 1854 i don't close pipe [0][0]
I'm 1854 i close [0][1]
I'm 1854 i close pipe [1][0]
I'm 1854 i don't close pipe [1][1]
I'm 1854 i close pipe [2][0]
I'm 1854 i close [2][1]
hop
I'm 1855 i got 1, my numproc is : 1
I'm 1855 i close pipe [0][0]
I'm 1855 i close [0][1]
I'm 1855 i don't close pipe [1][0]
I'm 1856 i got 1, my numproc is : 2
I'm 1856 i close pipe [0][0]
I'm 1856 i close [0][1]
I'm 1856 i close pipe [1][0]
NB : NBPROC = 3 in this case, but no matter the Number of value it does not work except for the very first child processes.

A: I seem to have a plausible explanation for the behavior of your program. As I've already pointed out in the comments, there is an obvious flaw in the program that the int pipes[N][2]; weren't set up which would end up in the close() APIs actually just leading to EBADF being returned and probably not achieving what had been intended.
As for your program's behavior, that can be explained by inspecting the actual values being populated in the array int pipes[N][2];. Since the values aren't being set explicitly in the original question, the values are essentially undefined but...
Let's try setting them to something more sane values using:
int pipeVal = INT32_MIN;
if(argc == 2) {
    pipeVal = atoi(argv[1]);
}
for(int i = 0; i < N; ++i) {
    if(pipeVal != INT32_MIN) {
        pipes[i][0] =  pipes[i][1] = pipeVal;
    }
    printf("%d: Pipe pair %d-%d\n",getpid(), pipes[i][0], pipes[i][1]);
}

Passing in 0 yields the output:
61962: Number of process is : 3
61962: Pipe pair 0-0
61962: Pipe pair 0-0
61962: Pipe pair 0-0
61963: Election Id 0, numProc 0
61963: Exiting while-loop
61964: Election Id 0, numProc 1
61964: Exiting while-loop
61965: Election Id 0, numProc 2
61965: Exiting while-loop

This seems to align with what's expected: fork 3 processes which just exit eventually. Let's try with the value of 1
62033: Number of process is : 3
62033: Pipe pair 1-1
62033: Pipe pair 1-1
62033: Pipe pair 1-1
62034: Election Id 0, numProc 0
62035: Election Id 2, numProc 1
62036: Election Id 0, numProc 2

Now this appears to be weird since none of the processes actually exit out of the while loop, yet the main program terminates successfully. To actually check the exit status of the child programs, I added the following code:
if (getpid()==pere)
{
/*On attend la fin de chaque processus
 pour mettre un terme au processu pere*/
    for (int i = 0; i < N; ++i)
    {
        errno = 0;
        int stat_val;
        wait(&stat_val);
        #if DBG == 1
        printf("%d: WIFEXITED(%d),WEXITSTATUS(%d),WIFSIGNALED(%d),WTERMSIG(%d),WIFSTOPPED(%d),WSTOPSIG(%d),WIFCONTINUED(%d)\n", getpid(), WIFEXITED(stat_val),WEXITSTATUS(stat_val),WIFSIGNALED(stat_val),WTERMSIG(stat_val),WIFSTOPPED(stat_val),WSTOPSIG(stat_val),WIFCONTINUED(stat_val));
        #endif
    }
}

Here's the output on passing in 1 as the argument:
62215: WIFEXITED(1),WEXITSTATUS(0),WIFSIGNALED(0),WTERMSIG(0),WIFSTOPPED(0),WSTOPSIG(0),WIFCONTINUED(0)
62215: WIFEXITED(1),WEXITSTATUS(0),WIFSIGNALED(0),WTERMSIG(0),WIFSTOPPED(0),WSTOPSIG(0),WIFCONTINUED(0)
62215: WIFEXITED(1),WEXITSTATUS(0),WIFSIGNALED(0),WTERMSIG(0),WIFSTOPPED(0),WSTOPSIG(0),WIFCONTINUED(0)

This output indicates that  all the processes exited normally without being stopped abnormally by any signal whatsoever.
The clue is in the actual fds these processes are trying to close. In Linux (at least) a process once created has 3 file descriptors 0 for stdin, 1 for stdout, and 2 for stderr. When 0 is passed as an argument to the program, the processes just end up closing stdin (close(0)) which isn't being used anyway, hence no issues, and they exit comparerIdElection() and the while-loop subsequently. When 1 is passed in as a parameter to the program, the processes end up closing stdout (close(1)), hence whatever is supposed to be written to the output is not seen on the console anymore, yet they still do exit  comparerIdElection() and the while-loop subsequently and thus the WIFEXITED(1) from each process.
Now coming to the actual program shared, what are the actual values that end up getting populated is unspecified, but if even one of the N*2 fds in the array is set to 1, the behavior as above (passing in 1) shall be exhibited i.e. even though the printfs won't be written to the console, the processes do actually exit the while-loop and the main parent process is successfully able to wait for the processes. On my PC (and I suspect on yours too), the actual value of at least one of those array elements is always set to 1.
Values of pipe fd pairs on my Mac:
61120: Pipe pair -296602944-32766
61120: Pipe pair 23978080-1
61120: Pipe pair 64-0

Their values on TryItOnline:
25090: Pipe pair 0-0
25090: Pipe pair 68079952-32708
25090: Pipe pair 1-0

Their values on OnlineGDB (need to add the compiler flag -DNBPROC=3):
5612: Pipe pair 1505064448-32611
5612: Pipe pair 1507242440-32611
5612: Pipe pair 1-0

This analysis should hold irrespective of the value of NBPROC since till there's 1 amongst the pipe fds, that process will end up closing its own stdout and exhibit similar behavior.
Here's the complete program with some instrumentation that can be enabled by passing in DBG=1 and some PID-tagging to figure out which process is the log from :
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>

void comparerIdElection(int (*pipes)[2], int numProc)
{
    for (int i = 0; i < NBPROC; ++i)
    {
        if (numProc!=i)
        {
            #if DBG == 1
            printf("%d: Before close  pipe [%d][0](%d)\n",getpid(),i , pipes[i][0]);
            #endif
            errno = 0;
            close(pipes[i][0]);
            #if DBG
            printf("%d: closed  pipe [%d][0](%d) %s\n",getpid(),i, pipes[i][0], strerror(errno));
            #endif
        } else  {
            #if DBG == 1
            printf("%d: no action on pipe [%d][0](%d) \n",getpid(),i, pipes[i][0] );
            #endif
        }
        if (numProc +1 != i)
        {
            #if DBG == 1
            printf("%d: Before close  pipe [%d][1](%d)\n",getpid(),i, pipes[i][1] );
            #endif
            errno = 0;
            close(pipes[i][1]);
            #if DBG == 1
            printf("%d: close pipe [%d][1](%d) %s\n",getpid(),i, pipes[i][1], strerror(errno) );
            #endif
        } else {
            #if DBG == 1
            printf("%d: no action pipe [%d][1](%d) \n",getpid(),i, pipes[i][1] );
            #endif
        }
    }
}

//Generate a random number for my child process
int GenererIdElection ()
{
    srand(time(NULL)^getpid()<<16);
    return rand()%NBPROC;
}

int main(int argc, char const *argv[])
{
    int N = NBPROC, idElection, numProc= -1;
    int pere = getpid();
    int pipes[N][2];
    int pids[N];
    char etat ;
    printf("%d: Number of process is : %d\n", getpid(), N);
    int pipeVal = INT32_MIN;
    if(argc == 2) {
        pipeVal = atoi(argv[1]);
    }
    for(int i = 0; i < N; ++i) {
        if(pipeVal != INT32_MIN) {
            pipes[i][0] =  pipes[i][1] = pipeVal;
        }
        printf("%d: Pipe pair %d-%d\n",getpid(), pipes[i][0], pipes[i][1]);
    }

    for (int i = 0; i < N; ++i)
    {
        if(getpid()==pere){
            pid_t pid = fork() ;
            numProc++;
            if(pid == 0) {
                // sleep(10);
                #if DBG == 1
                printf("%d: After fork in the child got fork-pid %d\n", getpid(), pid);
                #endif
            } else {
                pids[numProc] = pid;
                #if DBG == 1
                printf("%d: After fork in the parent got fork-pid %d numProc %d pids[%d] = %d\n",
                    getpid(), pid, numProc, numProc, pids[numProc]);
                #endif
            }
        }
    }

    if (getpid() != pere)
    {
        etat = 'C';
        while(etat == 67)
        {
            idElection = GenererIdElection();
            printf("%d: Election Id %d, numProc %d \n",getpid(), idElection, numProc);
            comparerIdElection(pipes, numProc);
            etat ='B';
        }
        printf("%d: Exiting while-loop\n", getpid());
    }

    if (getpid()==pere)
    {
    /*On attend la fin de chaque processus
     pour mettre un terme au processu pere*/
        for (int i = 0; i < N; ++i)
        {
            errno = 0;
            int stat_val;
            wait(&stat_val);
            #if DBG == 1
            printf("%d: WIFEXITED(%d),WEXITSTATUS(%d),WIFSIGNALED(%d),WTERMSIG(%d),WIFSTOPPED(%d),WSTOPSIG(%d),WIFCONTINUED(%d)\n", getpid(), WIFEXITED(stat_val),WEXITSTATUS(stat_val),WIFSIGNALED(stat_val),WTERMSIG(stat_val),WIFSTOPPED(stat_val),WSTOPSIG(stat_val),WIFCONTINUED(stat_val));
            #endif
        }
    }
    printf("%d: Exiting process\n", getpid());
    exit(EXIT_SUCCESS);
}


text:
Q: Search box within list-inline I have the following page:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

CAMPAIGNS

Sort By

        <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
          Date

        </button>

Date

            <button class="btn btn-default" type="button"></button>

          <input type="text" class="form-control" placeholder="Search">

https://jsfiddle.net/aze5uh2h/
When you open the page, you see that the search box is below the Sort By Date. How can I get it to be on the same line?

A:

CAMPAIGNS

        <button class="btn btn-default" type="button"></button>

      <input type="text" class="form-control" placeholder="Search">

Sort By

    <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
      Date

    </button>

Date

Bootply

A: You should probably read the bootstrap docs to get a better understanding of bootstrap's markup. The following should get you what you're after. https://jsfiddle.net/vsetpLn0/

CAMPAIGNS

        Sort By

          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Date
          </button>

Action

Another action

Something else here

Separated link

          <input type="text" class="form-control" placeholder="Search">

A: When I comment out the "
" tag around the search box, the elements fall into a single line. So, if you delete that tag, you should get what you want.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

CAMPAIGNS

Sort By

        <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
          Date

        </button>

Date

            <button class="btn btn-default" type="button"></button>

          <input type="text" class="form-control" placeholder="Search">

A: ul.list-inline li:nth-child(3) {
  display: inline;
}

Better late than never.


text:
Q: URL patterns (Django Programming) I'm trying to generate a regex for just numbers. But for some reason the pattern doesn't seem to match. My code is:
url('^[\d\-]+/$', views.room, name='room'),

The request has to go to this expression. The HTML href for the above is:
<href="/polls/layout/103/>

A: I'm assuming polls/ is caught upstream in the project urls.py and you're editing the app urls.py.  You need to catch 'layout/' as well as '103'.
url('^layout/[0-9]+/$', views.room, name='room'),

If you need to capture the '103' for further processing within the view (likely), you might want to try something like:
url('^layout/(?P<room_number>[0-9]+)/$', views.room, name='room'),

where 'room_number' is an arg to the room class in your app's views.py.


text:
Q: A rock, paper, scissors tournament is encoded as a bracketed array of games Hi I need to create a rock, paper, scissors tournament that is encoded as a bracketed array of games -that is, each element can be considered its own tournament.  I need to work with something like this:

Under this scenario, Dave would beat Armando (S>P), Richard would beat Michael (R>S), and then Dave and Richard would play (Richard wins since R>S); similarly, Allen would beat Omer,Robert would beat John, and Allen and Robert would play (Allen wins since S>P);and finally Richard would beat Allen since R>S, that is, continue until there is only a single winner. I am wondering what would be the best option to create the algorithm using a 2d array or a list. Any comments or example on how to create it would be really appreciate.
Thanks in advance.


text:
Q: Android XML: Vertical Seekbar in Android with match parent layout isn't working properly I have seen a different post related to this topic already before posting this question so I can definitely say that this question is not a duplicate. I have a different problem which I couldn't fix or find a solution to it.
Problem: I have created a Vertical Seekbar using new <SeekBar> </SeekBar> view. It does look fine when I see the preview in Android Studio but on the device, the SeekBar doesn't fill the height of the screen. I have rotated the SeekBar view with 90deg and try to set the height:match_parent and width:wrap_content but it isn't working at all as I expected. So I set the height to some hard-coded value and it looked fine. The only problem is, I will have to check the height of the view in which it is getting populated and set the height of the SeekBar problematically, which I want to avoid.
slider.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/slider"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/roundcorner"
    android:backgroundTint="@color/design_default_color_primary"
    android:gravity="center"
    android:layout_gravity="center"
    android:elevation="5dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:textColor="#fff"
        android:text="@string/RangeValue"
        android:paddingTop="16dp"
        android:paddingBottom="16dp"/>
    <FrameLayout
        android:layout_weight="1"
        android:background="#fff"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <SeekBar
            android:id="@+id/seeker"
            android:layout_width="wrap_content" <!-- Set this to 400dp and it looks fine -->
            android:layout_height="match_parent"
            android:rotation="270"
            android:layout_gravity="center"/>
    </FrameLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_round_done_24px"
        android:layout_gravity="center"
        android:padding="16dp"  />

</LinearLayout>

Update
Thank you Reaz for your answer

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <include
                layout="@layout/maingrid"
                android:background="@color/colorAccent"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
            <LinearLayout
                android:background="@android:color/transparent"
                android:layout_centerInParent="true"
                android:id="@+id/radarCanvas"
                android:layout_width="300dp"
                android:layout_height="300dp"
                android:orientation="vertical">
            </LinearLayout>
            <include
                android:layout_alignParentBottom="true"
                layout="@layout/biosignals"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

             <!--- this is where i am including slider layout -->
             <include
                android:layout_alignParentRight="true"
                layout="@layout/slider"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_margin="24dp" />

        </RelativeLayout>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

A: You are setting weight inside the Framelayout when the orientation is vertical and at the same time the height of FrameLayout is  set to match_parent. If you are setting like this there will be no effect of the weight. Try setting the height to 0dp it will work for sure.
<FrameLayout
    android:layout_weight="1"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="0dp">

    <SeekBar
        android:id="@+id/seeker"
        android:layout_width="wrap_content" // set this to 400dp and it looks fine
        android:layout_height="match_parent"
        android:rotation="270"
        android:layout_gravity="center"/>

</FrameLayout>

This is my result

A: You need to get rid of your FrameLayout which is limiting the width of the SeekBar. I tried to implement the layout like the following and I think it should fit in your case as well.
Another important thing you should notice that, because of your rotation, the width and height are interchanged in the view for your SeekBar. Hence I made the layout_width="match_parent". Hope that helps!
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/slider"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:elevation="5dp">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:padding="16dp"
        android:text="100"
        android:textAlignment="center" />

    <SeekBar
        android:id="@+id/seeker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:rotation="270" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:padding="16dp"
        android:src="@android:drawable/star_on" />

</RelativeLayout>

Here is the result that I have got.

A: <RelativeLayout
    android:layout_width="400dp"
    android:layout_height="200dp"
    android:layout_gravity="center">
    <SeekBar
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:maxHeight="4dp"
        android:minHeight="4dp"
        android:progress="50"
        android:progressDrawable="@drawable/custom_seek_bar"
        android:rotation="270"
        android:thumb="@drawable/seekbar_thumb" />
</RelativeLayout>
Use this code, you will get desired result


text:
Q: Octals in regex: shouldn't this produce a warning? This program runs fine on perl 5.18.1:
use strict;
use warnings;
use 5.010; # <--THIS

my $test = "Now\012is\012the\012time\012";
print $test;
$test =~ s/\o{12}//g;
print $test;

According to perlrebackslash ("Octal Escapes" section), the \o{12} syntax was introduced in 5.14. . .

A: use 5.010 just means you nead at least 5.10 to run the script. It doesn't turn off the new features introduced in 5.12, 5.14 etc. See use.

A: There was no backwards compatibility to introducing \o{12}, so you don't need to activate that feature. It is available as long as you have a sufficiently high version of Perl.
The program's installer can insure you have a sufficiently high version of Perl, or you can add use 5.014;, but neither are necessary.


text:
Q: is it possible to append and save a css file using javascript/meteor? I need to dynamically append css elements to a css file using values selected from a db.
Is there a way to do this using javascript or some other library.
I've looked on atmospherejs.com but didn't see anything that looked like it could do it.
I'm currently doing this using php/mysql but if I can use meteor and js that would be better.
Any ideas?

A: Take a look at this article: http://davidwalsh.name/add-rules-stylesheets
the file will need to get built on every page load, however.  The problem with adding styles via script is that they get parsed REALLY late in the page build process, it will be a way better user experience for you to build a custom.php (or something) file and give that to every page - which it sounds like you're doing already.
That will ensure it processes the styles before the scripts, avoiding a momentary style 'flash' where your script finishes executing and adds the new rules.


text:
Q: how to change color of the scrollview max stretch indicator i m creating an application in which there is a horizontal scrollview when the user scrolls the he scrollview to max length then there comes an curve like structure which can be seen in the screenshot which indicates that you have reached the max length. How can i change the color of that curve as it is blue in this application which is not looking good

A: Try this
android:scrollbarThumbVertical="#FF94CC"

A: You can use android:colorEdgeEffect for change edge color of ScrollView, RecyclerView etc.
<style name="HorizontalScrollViewStyle">
        <item name="android:colorEdgeEffect">@android:color/holo_green_dark</item>
</style>

Use this theme in your HorizontalScrollView :
  <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="none"
        android:theme="@style/HorizontalScrollViewStyle">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center">
                     ......
            </LinearLayout>
    </HorizontalScrollView>

NOTE - android:colorEdgeEffect is only available for API 21 and above.


text:
Q: Resources not loading after building the app to jar My app works perfectly in the IDE, but when I build it to a jar the resources are not loaded at all. I tried using
this.getClass().getClassLoader().getResourceAsStream("path")

that didn't work as well.
my project structure looks like this:

I'm using Eclipse IDE,and I want to load the following:
1 - shared MP3 file (current.mp3)
2 - icon for swing (icon.jpg)
these 2 files located in resources folder.
i added resources as a source folder.
Image icon = Toolkit.getDefaultToolkit().getImage("resources/icon.jpg");
player = new Player(new FileInputStream("resources/current.mp3"));
OutputStream outstream = new FileOutputStream(new File("resources/current.mp3"));


text:
Q: Spring: How to make a service conditional on the availability of a PlatformTransactionManager bean? I have a FooService that I would like to be available only when a PlatformTransactionManager is available.
If I define my service like this and no PlatformTransactionManager is available, then my application will fail to start:
@Service
public class FooService {
  public FooService(final PlatformTransactionManager txManager) { ... }
  ...
}

I wanted to use ConditionalOnBean, which should only annotate auto configuration classes. I refactored my code like this:
@Configuration
public class FooAutoConfiguration {
  @Bean
  @ConditionalOnBean(PlatformTransactionManager.class)
  public FooService fooService(final PlatformTransactionManager txManager) {
    return new FooService(txManager);
  }
}

public class FooService {
  public FooService(final BarBean bar) { ... }
  ...
}

I wrote the following test for FooService:
@ExtendWith(SpringExtension.class)
@Import(FooAutoConfiguration.class)
public class FooServiceTest {
  @Autowired
  private FooService fooService;

  @Test
  public void test() {
    System.out.println("fooService = " + fooService);
  }
}

But I get the following exception when I try to run it:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.acme.FooServiceTest': Unsatisfied dependency expressed through field 'fooService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.FooService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
(...)

However, I know that a PlatformTransactionManager bean is available, because the test runs fine when I @Autowire a PlatformTransactionManager in my test instead of a FooService.
Interestingly, I also tried to replace PlatformTransactionManager with WebClient.Builder, and everything ends up working as it should. What is so special about PlatformTransactionManager?
How can I write FooService so that it will work when a PlatformTransactionManager bean is available, and not prevent applications where no such bean is available from starting?

A: Add @AutoConfigureOrder annotation to ensure that your auto-configuration class is processed after the transaction manager bean is registered by Spring Boot:
@Configuration
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
public class FooAutoConfiguration {

}


text:
Q: If $X \sim {\rm Bernoulli}(p)$, what is the distribution of $Y=aX-b$? Let $X \sim {\rm Bernoulli}(p)$ and $Y=aX-b$. I want to find the distribution of $Y$.
I am assigned a homework problem with specific $a$ and $b$. My textbook covers methods for solving this, given that x is continuously distributed. However, $X$ is discretely distributed.
I'm not looking to be shown exactly how to do this. I am just unsure of where to start, as this is not covered in our text.
Any help you could provide to me would be greatly appreciated.


text:
Q: set Delegate for a modal transition How do i set the delegate for a modal transition?
Currently I have something like:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [segue.destinationViewController setDelegate:self];
}

- (void)nextViewController:(NextViewController *)sender setSomething(NSString *)something
{
    NSLog(@"Something happened in nextviewcontroller");
}

This works if the transition is a push, but when it is a modal (arrow goes to a navigation controller) nothing happens.
Why is this and what is a work around?

A: are u using storyboard? if not, you should add navigation controller on the app delegate and pushviewcontroller will work

A: In prepareForSegue I needed to set the delegate to the topView of the navigation controller.
like this:
ExampleViewController *evc;
evc = (ExampleViewController *)[segue.destinationViewController topViewController];
[evc setDelegate:self];


text:
Q: changing column data with "lastname, firstname" to "firstname lastname" in python pandas dataframe I have python pandas dataframe, served up by power bi data source transformation support for execution of python script, where one of the columns consists of lastname, firstname and I need it to consist of firstname lastname.
I've tried the following split, reversed, join approach which works on a standalone string argument but generates AttributeError: 'Series' object has no attribute 'split' when I try it on column data in a pandas dataframe.
name = 'LastName, FirstName'
' '.join(reversed(name.split(', ')))
# output = 'FirstName LastName'

import pandas as pd
df = pd.DataFrame({'full_name': ['doe, john', 'smith, kate', 'jones, susan', 'edwards, jack' ],
                   'num_legs': [2, 4, 8, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, 2, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])
df
df['full_name'] = ' '.join(reversed(df['full_name'].split(', ')))
# output = AttributeError: 'Series' object has no attribute 'split'

Searching SO i see hits for doing this something of this nature in an excel column and in a R list but nothing i have been able to find yet for column in a python pandas dataframe.

A: In your case we can do split with map PS : ::-1 here is reversed the order
df.full_name=df.full_name.str.split(', ').map(lambda x : ' '.join(x[::-1]))
df.full_name
falcon        john doe
dog         kate smith
spider     susan jones
fish      jack edwards
Name: full_name, dtype: object

A: A combination of pandas' string methods could help here : for speed, I would suggest running a list comprehension within python itself. The string methods in Pandas are provided primarily for convenience/simplicity.
df['full_name'] = df.full_name.str.split(",").str[::-1].str.join(",")

          full_name     num_legs    num_wings   num_specimen_seen
falcon     john,doe         2           2             10
dog        kate,smith       4           0             2
spider     susan,jones      8           0             1
fish       jack,edwards     0           0             8

A: The error is because the variable's type type(df['full_name']) is <class 'pandas.core.series.Series'>. Convert it to list and then operate:
import pandas as pd
df = pd.DataFrame({'full_name': ['doe, john', 'smith, kate', 'jones, susan', 'edwards, jack' ],
        'num_legs': [2, 4, 8, 0],
        'num_wings': [2, 0, 0, 0],
        'num_specimen_seen': [10, 2, 1, 8]},
        index=['falcon', 'dog', 'spider', 'fish'])

print(map(lambda x: x.split(',')[::-1], df['full_name'].tolist()))


text:
Q: Two Instances' Attributes Refer to the Same Memroy Location in Python 3 How can this be possible in Python 3? k1 and k2's a attributes refer to the same memory location in IPython console
class K():

    def __init__(self, a):
        self.a = a

k1 = K(4)
k2 = K(4)

hex(id(k1)) # 0x10d77b668
hex(id(k2)) # 0x10d77b6a0

hex(id(k1.a)) # 0x10d41caa0
hex(id(k2.a)) # 0x10d41cac0

id(k1.a) == id(k2.a) # True

I am mostly concerned about the object reference issue going on here rather than the 'is' operator test, which I believe is not the problem I am trying to solve. Because, both k1.a and k2.a would pass the is test because the two references refer to the same object. But what I would like to know is, why that happens.


text:
Q: Any way to set up Cmd-Tab to cycle among apps and Chrome browser tabs on OS X? On my Mac, I commonly use a mix of native apps (like Excel) and webapps (like Google Docs) in Chrome. Is there any way to get Cmd-Tab to cycle through the apps and webapps one at a time, instead of treating Chrome as a single app?

A: After a long search, I found HyperSwitch which lets me alt-tab between chrome windows. This works for chrome apps or separate chrome windows.

A: There isn't any easy way I can think of, but you can create a site-specific browser for certain web apps, using Fluid.

Web applications like Gmail, Facebook, Campfire and Pandora are becoming more and more like desktop applications every day. Running each of these web apps in a separate tab in your browser can be a real pain.
Fluid lets you create a Real Mac App (or "Fluid App") out of any website or web application, effectively turning your favorite web apps into OS X desktop apps.

In essence, you'll get a separate application for each of your web apps.


text:
Q: High precision thread synchronization I have several objects of some class in which I run network data exchange. I need to start the network operations in threads as accurately as possible.This is in units of microseconds. By the time the work starts, the threads are already created and running. For synchronization i use static atomic variable. Objects created in main thread and then in other threads starts function on_start() of these objects.
class NetSender {
public:
  static std::atomic_flag start;
  static std::atomic<uint8_t> net_sender_count;
  void on_start(){
    //... do some work
    net_sender_count++;
    //waiting start of other
    while(start.test_and_set())
        ;
    m_start_message = std::chrono::system_clock::now();
    //do very important job here
  }
}

and somewhere in main() function
std::vector<NetSender*> senders[how_much_we_need];
//create senders items

std::vector<std::thread> senderthreads[how_much_we_need];
// for senders
senderthreads.at(i) = new std::thread(
                &NetSender::on_start,senders.at(i));
while(senders[1]->net_sender_count < how_much_we_need)
     ; //whait starting of all threads

senders[1]->start.clear();    //start job

(maybe there are some typos in my example but i hope the idea is pretty visible)
After that i compare m_start_message values and difference is from 10 microseconds to 100 milliseconds. Is there a way to reduce this difference to microseconds? Or may be there is some logical mistake(s).

A: You want a conditional variable and a mutex combo.
Something like the following:
class NetSender
{
    static std::condition_variable _cvThreads; // threads signal this cv when ready
    static std::condition_variable _cvMain;    // main signals this cv after setting start condition
    static std::mutex _mutex;
    static bool _isStarted;
    static int net_sender_count;
    static int how_much_we_need;

    void on_start()
    {
        { // enter lock
            std::lock_guard<std::mutex> lck(_mutex);
            net_sender_count++;
        } // exit lock

        _cvThreads.notify_all();  // notify main thread that this worker thread is ready

        // wait for main thread to signal start
        { // enter lock
            std::lock_guard<std::mutex> lck(_mutex);

            while (_isStarted == false)
            {
                _cvMain.wait(lck); // atomically release mutex, wait for notify, then lock and continue
            }

        } // exit lock

        m_start_message = std::chrono::system_clock::now();
        //do very important job here
    }

Then in your main thread
NetSender::_isStarted = false;

senderthreads.at(i) = new std::thread(&NetSender::on_start,senders.at(i));

// wait for all threads to get ready
{
    std::lock_guard<std::mutex> lck(NetSender::_mutex);
    while (NetSender::net_sender_count < NetSender::how_many_we_need)
    {
         NetSender::_cvThreads.wait();
    }
    NetSender::_isStarted = true;
}

NetSender::_cvMain.notify_all(); // signal all threads to start

A: A few hints to get this working:
1) You might want to use a thread pool if you're going to be executing this several times.
2) You might not want to use wait/notify as this will introduce latency when descheduling/scheduling the threads. It might be better just to spin if the wait time is sufficiently short.
3) What you're looking for is a thread barrier. There are many known algorithms out there and you probably want to take advantage of them. If this is a one-time execution, a countdown latch might be favorable. Otherwise, barriers such as sense-reversing barriers can be reused. If necessary, use tree barriers to minimize the coherence traffic between cores.
A simple implementation might look  something like this (psuedocode, sorry, it's been a while since I've written C++):
void main() {

  // Create a barrier sufficient for syncing worker threads + main thread
  MyBarrier * b = new MyBarrier(num_threads + 1);

  std::thread threads[num_threads];

  for (int i = 0; i < num_threads; i++) {
    threads[i] = thread(onStart, &senders[i], b);
  }

  someWork();

  barrier->wait();

  ...
}

void onStart(NetSender *sender, MyBarrier * b) {

  doSomeWork();

  b->wait();

  doSomeMoreWork();
}

class MyBarrier {

private:

  std::atomic<int> count;

public:

  MyBarrier(int countdown) {
    std::atomic_init(&count, countdown);
  }

  void wait() {

    count.fetch_sub(1);

    while (count.get() > 0) {
      // spin
    }
  }
}


text:
Q: How to send Bcc in Python Google API? I'm using the code described in:
Sending email via gmail & python
to send e-mails. Everything works great. Now I'd like to add a Bcc (one or more) and I don't know how.

*

*If I add: message['Bcc'] = 'mail@mail.com' it works but the senders see the Bcc, and I don't want that.

*I know that using SMTP you can:
    smtp = smtplib.SMTP('smtp.gmail.com', 587)
    smtp.sendmail(user, [to] + bcc, message.as_string())

but I don't want to do it that way.
How can I add Bcc without the sender knowing about it, using google google_auth_oauthlib?
This is the code I'm using
import httplib2
import os
import oauth2client
from oauth2client import client, tools, file
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    if attachmentFile:
        message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    else:
        message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
    result = SendMessageInternal(service, "me", message1)
    return result

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print('Message Id: %s' % message['id'])
        return message
    except errors.HttpError as error:
        print('An error occurred: %s' % error)
        return "Error"
    return "OK"

def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = to
    msg.attach(MIMEText(msgPlain, 'plain'))
    msg.attach(MIMEText(msgHtml, 'html'))
    return {'raw': base64.urlsafe_b64encode(msg.as_string())}

def createMessageWithAttachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      msgHtml: Html message to be sent
      msgPlain: Alternative plain text message for older email clients
      attachmentFile: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    messageA = MIMEMultipart('alternative')
    messageR = MIMEMultipart('related')

    messageR.attach(MIMEText(msgHtml, 'html'))
    messageA.attach(MIMEText(msgPlain, 'plain'))
    messageA.attach(messageR)

    message.attach(messageA)

    print("create_message_with_attachment: file: %s" % attachmentFile)
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def main():
    to = "to@address.com"
    sender = "from@address.com"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    SendMessage(sender, to, subject, msgHtml, msgPlain)
    # Send message with attachment:
    SendMessage(sender, to, subject, msgHtml, msgPlain, '/path/to/file.pdf')

if __name__ == '__main__':
    main()


text:
Q: Shell script to parse ip:port from a text file I get daily a text file with ip:port, one per line, example:
11.22.33.44:80
22.33.44.55:8080
33.44.55.66:7777

I would like to parse the first ip and port in two different variables, then write them into another file, wait exceution of a program that use these variables, loop this cycle to pass all the ip:port to the file and execute program.
How can I do that?
thank you

A: A pure bash solution:
while IFS=: read ip port; do
    echo $ip $port
done < in.txt

This has the advantage of allowing you to set variables inside the while loop that remain available after the loop completes.

A: cat in.txt | sed -e "s/:/ /" | while read ip port
do
  echo $ip $port # or do something with it
done


text:
Q: Como ejecutar store procedure en mysql desde laravel Hola muy buenas a toda la comunidad. El motivo de mi pregunta es cómo puedo llamar un procedimiento almacenado en mysql desde laravel.
Código de store procedure.
CREATE DEFINER=`root`@`localhost` PROCEDURE `votar`(IN identificador INT)
BEGIN
DECLARE total int;
DECLARE incremento int;

SELECT voto INTO total
FROM candidatas WHERE id = identificador;
IF total >= 0 THEN
    SET incremento = total+1;
    UPDATE candidatas SET voto = incremento
    WHERE id = identificador;
END IF;
END

Intento llamarlo desde el controlador de esta forma.
public function update($id)
{

        if(isset($request['id']))
        {
        //llamando al store procedure
        $id = Input::get('id');
        return DB::select('call votar(?)',array($id));

        }
        return 'votaste';

}

En la vista tengo esto:
@foreach ($candidatas as $candidata)

                 foto }}" class="card-img-top rounded-circle mx-auto d-block" alt="">

{{ $candidata -> nombre }}

{{ $candidata -> descripcion }}

                    <form action="post" action="/candidata">
                        @method('PUT')
                        @csrf
                        <input type="hidden" name="voto" value="{{ $candidata -> id }}">
                        <button class="btn btn-danger" type="submit">Votar</button>
                    </form>

    @endforeach

Pero me sale un error 404 y si verifico la tabla no se guardado ningún cambio.
Lo que quiero hacer es que los registros se visualicen en tarjetas de bootstrap. Y que al dar clic en el botón Votar se ejecute un store procedure que tengo en mysql. Supuestamente (digo supuestamente porque no se envía nada) le estoy enviando el id como parámetro al store procedure. Eso mismo hice desde vb.net y funciona.


text:
Q: MATLAB Matrix Preallocation Slower Than Dynamic Matrix Expansion In each iteration of a loop, I am calculating a MATLAB matrix. These matrices all must be concatenated together to create one final matrix.  I know the dimensions of this final matrix before entering the loop, so I though preallocating the matrix using the 'zeros' function would be faster than initializing an empty array then simply appending the subarrays in each iteration of my loop.  Oddly, my program runs MUCH slower when I preallocate.  Here is the code (Only the first and last lines differ):
This is slow:
w_cuda = zeros(w_rows, w_cols, f_cols);

for j=0:num_groups-1

    % gets # of rows & cols in W. The last group is a special
    % case because it may have fewer than max_row_size rows
    if (j == num_groups-1 && mod(w_rows, max_row_size) ~= 0)
        num_rows_sub = w_rows - (max_row_size * j);
    else
        num_rows_sub = max_row_size;
    end;

    % calculate correct W and f matrices
    start_index = (max_row_size * j) + 1;
    end_index = start_index + num_rows_sub - 1;

    w_sub = W(start_index:end_index,:);
    f_sub = filterBank(start_index:end_index,:);

    % Obtain sub-matrix
    w_cuda_sub = nopack_cu(w_sub,f_sub);

    % Incorporate sub-matrix into final matrix
    w_cuda(start_index:end_index,:,:) = w_cuda_sub;

end

This is fast:
w_cuda = [];

for j=0:num_groups-1

    % gets # of rows & cols in W. The last group is a special
    % case because it may have fewer than max_row_size rows
    if (j == num_groups-1 && mod(w_rows, max_row_size) ~= 0)
        num_rows_sub = w_rows - (max_row_size * j);
    else
        num_rows_sub = max_row_size;
    end;

    % calculate correct W and f matrices
    start_index = (max_row_size * j) + 1;
    end_index = start_index + num_rows_sub - 1;

    w_sub = W(start_index:end_index,:);
    f_sub = filterBank(start_index:end_index,:);

    % Obtain sub-matrix
    w_cuda_sub = nopack_cu(w_sub,f_sub);

    % Incorporate sub-matrix into final matrix
    w_cuda = [w_cuda; w_cuda_sub];

end

As far as other potentially useful information--my matrix is 3D, and the numbers within it are complex. As always, any insight is appreciated.

A: I have always assumed preallocation is faster for any array size and never actually tested it. So, I did a simple test timing the population of various array sizes from 1x1x3 up to 20x20x3 using 1000 iterations by both appending and preallocation methods. Here's the code:
arraySize = 1:20;
numIteration = 1000;

timeAppend = zeros(length(arraySize), 1);
timePreAllocate = zeros(length(arraySize), 1);

for ii = 1:length(arraySize);
    w = [];
    tic;
    for jj = 1:numIteration
        w = [w; rand(arraySize(ii), arraySize(ii), 3)];
    end
    timeAppend(ii) = toc;
end;

for ii = 1:length(arraySize);
    w = zeros(arraySize(ii) * numIteration, arraySize(ii), 3);
    tic;
    for jj = 1:numIteration
        indexStart = (jj - 1) * arraySize(ii) + 1;
        indexStop = indexStart + arraySize(ii) - 1;
        w(indexStart:indexStop,:,:) = rand(arraySize(ii), arraySize(ii), 3);
    end
    timePreAllocate(ii) = toc;
end;

figure;
axes;
plot(timeAppend);
hold on;
plot(timePreAllocate, 'r');
legend('Append', 'Preallocate');

And here are the (as expected) results:


text:
Q: With Kentor SAML authentication, is there a way to customize the User.Identity.Name? We are currently implementing SAML authentication using Owin with Kentor in .NET.  We are reading the token correctly, and I receive all of the claims back.  However, when I parse the User.Identity object that Owin returns to me, there isn't a name on it (that I would have if I was using Azure Active Directory, etc.).  Does anyone know of a way to use some of the returning claims from the token to set the User.Identity.Name?  In this case, the claims in question are EmpFirstName and EmpLastName.

A: Just to add a third option to the two (better) answers that Anders has provided:
When I needed to do this I located the claim I wanted to be the username and created a new claim with:
 subject.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",claim.Value));

Identity will then recognise it.

A: There are two ways you can do this.

*

*Implement a ClaimsAuthenticationManager (see the Kentor AuthServices docs in the GitHub repo) that is a callback mechanism during the claims creation. You can also use the AcsCommandResultCreated notification if you find that easier to use. In there, add a Name claim that you want (e.g. by combining the existing first and last name claims).

*If you want the Identity.Name to point to an existing claim, change the NameClaimType property of the Identity.


text:
Q: Error conexión proxy cree una conexión a proxy en una carpeta local que nunca funciono,  por error borre dicha carpeta y cree otra, pero al tratar de conectarme con github para hacer pull a los archivos me aparece el siguiente error:
Failed to connect to 0.0.173.67 port 1080 after 0 ms: Network unreachable.

Compruebo la configuración de mi entorno y en efecto me aparece la conexión al proxy en la carpeta que borre y al ingresar el comando git config --global --unset http.proxy, no se desconecta de el. También probe descargar a través de github desktop pero me dice lo siguiente:
Could not resolve proxy:xxxxx

Alguien me puede colaborar?, soy nuevo usando git.
A petición de eftshift0 pongo las salida de los siguientes comandos.
git config -l --global
remote.origin.url=https://github.com/kiadom/PrimerProyecto.git
remote.origin.proxy=192.168.116.191
remote.origin.proxy=44355
http.sslbackend=openssl
http.sslcainfo=D:\Universidad de Antioquia\Ciclo 3\scrum semana
1\RepositorioQuimbayaDev

git config -l
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
http.sslbackend=openssl
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
core.autocrlf=true
core.fscache=true
core.symlinks=false
pull.rebase=false
:

A: Veo 2 cosas bastante raras.
Primero, en la configuración global hay un remote? Eso no debería estar ahí. Los remotes se configuran en cada repositorio.
Segundo, hay dos lineas de proxy para dicho remote. Elimina el segundo proxy (que de paso, ni si quiera es una dirección IP. 173 * 256 + 67 = 44355, de ahí viene esa dirección IP que está poniendo en el mensaje de error. Ahora me pregunto: 44355 es el puerto del proxy? Entonces la dirección del proxy debería ser 192.168.116.191:44355).
En general, si un proxy lo usas para todo y no solo para un remote, podrías configurarlo en el global:
git config --global -w http.proxy 192.168.116.191:8080

(asumiendo que el puerto del proxy es 8080, usa el que corresponda).


text:
Q: Why do I get ImportError when trying to import Pandas Python module? I installed the Pandas module for Python 2.7 using apt-get. However, when I try to import the module, it raises an ImportError:
 import pandas as pd
 File "/usr/lib/pymodules/python2.7/pandas/__init__.py", line 15, in <module>
    raise ImportError('ImportError: C extensions not built: if you installed already verify that you are not importing from the source directory')

The call in /usr/lib/pymodules/python2.7/pandas/__init__.py is:
import pandas.lib as lib
except Exception:  # pragma: no cover
    import sys
    e = sys.exc_info()[1] # Py25 and Py3 current exception syntax conflict
    if 'No module named' in str(e):
        raise ImportError('C extensions not built: if you installed already '
                          'verify that you are not importing from the source '
                          'directory')
    else:
        raise

Why do I get ImportError and how do I solve this?
Following is what I get when trying to import the dependencies of Pandas in an interactive Python shell:
>>> import numpy as np
>>> import dateutil
>>> import pytz
>>> import numexpr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named numexpr
>>> import bottleneck
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named bottleneck

A: Following are the dependencies for Pandas:

*

*NumPy

*python-dateutil

*pytz

And the Pandas project list the following two as highly recommended dependencies:

*

*numexpr

*bottleneck

It looks like apt-get only installed the required dependencies and not the highly recommended ones; as such you get an ImportError when trying to import numexpr and bottleneck. Installing these modules should most probably solve the problem.
Since, you are running Python 2.7 as evident from Python Traceback, install these two modules as suggested below:

*

*numexpr is present in Ubuntu's repositories. So, install it by running:
sudo apt-get install python-numexpr

*bottleneck is not present in Ubuntu's repositories. So, install it using pip. We would also need to install build-essentials package in order to build bottleneck:
sudo apt-get install python-pip build-essentials
sudo pip install bottleneck

A: Also, if a package was installed via easy_install, and now other dependency packages have been installed via PIP, this sort of issue can arise.
To fix, remove any/all modules installed via easy_install by rm -rf /usr/local/lib/python2.7/site-packages/"module_name".
Then run pip install "module_name".


text:
Q: Parsing Bungie Clan Data with PHP I am able to parse json data from multiple sources with PHP, but cant seem to figure out the json data from Bungie, specifically clan members. I have spent hours Googling and attempting as array, as object, etc.
Below is a sample of the first 2 users (yes its public data). If any PHP json parse lords could help me with minimal sample working code Im sure I can run with it.
    {"Response":{"results":[{"memberType":2,"isOnline":false,"groupId":"913961","destinyUserInfo":{"iconPath":"/img/theme/destiny/icons/icon_xbl.png","membershipType":1,"membershipId":"4611686018442185846","displayName":"Gim Allon"},"bungieNetUserInfo":{"supplementalDisplayName":"Gim Allon","iconPath":"/img/profile/avatars/s_tbagjx8.gif","membershipType":254,"membershipId":"3025645","displayName":"Gim Allon"},"joinDate":"2016-06-18T23:05:59Z"},{"memberType":2,"isOnline":true,"groupId":"913961","destinyUserInfo":{"iconPath":"/img/theme/destiny/icons/icon_xbl.png","membershipType":1,"membershipId":"4611686018434168228","displayName":"speedyred8"},"bungieNetUserInfo":{"supplementalDisplayName":"7734728","iconPath":"/img/profile/avatars/bungie_day_15_26.jpg","membershipType":254,"membershipId":"7734728","displayName":"speedyred8"},"joinDate":"2017-05-15T01:06:17Z"},{"memberType":2,"isOnline":false,"groupId":"913961","destinyUserInfo":{"iconPath":"/img/theme/destiny/icons/icon_xbl.png","membershipType":1,"membershipId":"4611686018434232581","displayName":"Fall3N KnighT"},"bungieNetUserInfo":


text:
Q: What is the best way to implement a 'last seen' function in a django web app? I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.
What would be the best way to track this?
I would prefer not writing to the database each time a logged in user loads a page; but what other options are there?

A: An approach might be:
you create a middleware that does the following on process_response:

*

*check for a cookie called 'online', but only if the user is authenticated

*if the cookie is not there,

*

*set a cookie called 'online' with value '1'

*set the lifespan of the cookie to 10 minutes

*update the 'last_login' field of auth.User for this user with the current datetime

now you have all currently logged in users in your auth.User table. All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered "online".
The database will be written for every logged in user about every 10 minutes. Adjust the values "10" and "15" to your needs.
The advantage here is that database writes are rare (according to your two numeric settings 10/15). And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.
Hope this helps.

A: A hashmap or a queue in memory with a task running every hour or so to persist it.

A: You need to persist the info server-side, integrity isn't critical, throughput and latency are important. That means you should use some sort of key-value store.
Memcached and redis have keys that expire. You probably have memcached already installed, so use that.
You can reset expiry time of the user:last-seen:$username key every visit, or you can use mawimawi's cookie technique and have expiry = 4 * cookie-lifetime.

A: You can't do that in django without using a database/persistent-storage because of the same reason why django sessions are stored in database: There can be multiple instances of your applications running and the must synchronize their states+data through a single persistence source [1]
Alternatively, you might want to write this information in a folder in a file named with user id and then check its create/modified date to find the required information.


text:
Q: How to use redis inside logstash filter? I am upgrading my ELK+Redis from a very old version to the latest one.
ES 1.6 to 7.4
LS 1.4 to 7.4
Redis 2.8 to 5.0

I freshly installed everything in a fresh machine. Things went smooth except one thing: logstash-filter-redis plugin
Here is my logstash conf file
input
  {
    redis {
      host
      port => 6380
      data_type
      key
    }
  }
filter {
  grok {
    match => [ "message", "" ]
  }
  redis {
    host => ""
    port => 6379
    key => ""
    }
output {
  elasticsearch {
    host => ""
    index => ""
  }

Here, the first redis:6380 inside input { } is being used to fetch logs (working as logstash input source)
while second redis:6379 is being called inside filter { } to get data associated with those logs.
I cannot see any logstash-filter-redis plugin at https://www.elastic.co/guide/en/logstash/current/filter-plugins.html
Can someone please help me with that?
Thanks

A: There are indeed no supported Redis filters in Logstash. You can find two community filters by synlay and meulop but I'm unsure how well they are supported and maintained.
I just learned recently another way of enriching your data from Redis by accessing Redis through a ruby filter like this :
filter {
   ...
   ruby {
      init => 'require "redis"; $rc = Redis.new(path: "/var/run/redis/redis.sock", db: 0)'
      code => 'event.set("enriched_field", $rc.get(event.get("key_field")))'
   }
}