text:
Q: Snakemake InputFunctionException. AttributeError: 'Wildcards' object has no attribute I have a list object with ChIP-seq single-end fastq file names allfiles=['/path/file1.fastq','/path/file2.fastq','/path/file3.fastq'] . I'm trying to set that object, allfiles, as a wildcard (I want the input of the fastqc rule (and others such as mapping, but let's keep it simple). I tried what is seen in the code below (lambda wildcards: data.loc[(wildcards.sample),'read1']). This, however, is giving me the error
"InputFunctionException in line 118 of Snakefile:
AttributeError: 'Wildcards' object has no attribute 'sample'
Wildcards:
"

Does someone know exactly how to define it? It seems I am close, I get the general idea but I am failing to get the syntax correct and execute it. Thank you !
Code:
import pandas as pd
import numpy as np

# Read in config file parameters
configfile: 'config.yaml'
sampleFile = config['samples'] # three columns: sample ID , /path/to/chipseq_file_SE.fastq , /path/to/chipseq_input.fastq
outputDir = config['outputdir'] # output directory

outDir = outputDir + "/MyExperiment"
qcDir = outDir + "/QC"

# Read in the samples table
data = pd.read_csv(sampleFile, header=0, names=['sample', 'read1', 'inputs']).set_index('sample', drop=False)
samples = data['sample'].unique().tolist() # sample IDs
read1 = data['read1'].unique().tolist() # ChIP-treatment file single-end file
inplist= data['inputs'].unique().tolist() # the ChIP-input files
inplistUni= data['inputs'].unique().tolist() # the ChIP-input files (unique)
allfiles = read1 + inplistUni

# Target rule
rule all:
    input:
        expand(f'{qcDir}' + '/raw/{sample}_fastqc.html', sample=samples),
        expand(f'{qcDir}' + '/raw/{sample}_fastqc.zip', sample=samples),

# fastqc report generation
rule fastqc:
    input: lambda wildcards: data.loc[(wildcards.sample), 'read1']
    output:
        html=expand(f'{qcDir}' + '/raw/{sample}_fastqc.html',sample=samples) ,
        zip=expand(f'{qcDir}' + '/raw/{sample}_fastqc.zip',sample=samples)
    log: expand(f'{logDir}' + '/qc/{sample}_fastqc_raw.log',sample=samples)
    threads: 4
    wrapper: "fastqc {input} 2>> {log}"

A: Currently output files of rule fastqc doesn't have any wildcards once they are resolved. That is, there is currently one job in the snakefile where rule fastqc tries to produce one output file for all samples.
However, it appears you would like to run rule fastqc separately for each sample. In that case, it needs to be generalized as below, where {sample} is the wildcard:
rule fastqc:
    input: lambda wildcards: data.loc[(wildcards.sample), 'read1']
    output:
        html = qcDir + '/raw/{sample}_fastqc.html,
        zip=qcDir + '/raw/{sample}_fastqc.zip'
    log: logDir + '/qc/{sample}_fastqc_raw.log'
    threads: 4
    shell: "fastqc {input} 2>> {log}"


text:
Q: If a linear operator $T$ has minimal, characteristic polynomial $q^k$ for $q$ irreducible, a $T$-invariant subspace has no $T$-invariant complement.
Let $T$ be a linear transformation on a finite dimensional vector space $V$ over the field $F$. Let $p_T$ be the minimal polynomial of $T$ and $f_T$ be the characteristic polynomial of $T$. If $p_T = f_T = q^k$ for some irreducible $q$ with $k > 1$, show that no nonzero proper $T$-invariant subspace can have a $T$-invariant complement.

My approach so far is the following: Let $W$ be a nonzero $T$-invariant proper subspace of $V$. Suppose that $W$ has a $T$-invariant complement $W'$.
We know that since $p_T = f_T$, $T$ has a cyclic vector $\alpha$ and that $V$ has a basis $\{\alpha, T\alpha, \dotsc, T^{n-1}\alpha\}$. If $\alpha$ is in $W$ then $W' = \{0\}$ and we are done (and vice versa), so suppose $\alpha = w + w'$ where $w \in W$ and $w' \in W'$.
From here, though, I am not sure how to proceed. Is this the best approach? Is there a better one?

A: As per Christian's observation in a comment on the origin question:
Let $p_W$ and $p_{W'}$ be the minimal polynomials of $W$ and $T$, respectively. Since $p_T = q^k$ with $q$ irreducible ($k = \dim V$), $p_W = q^m$ and $p_{W'} = q^{m'}$.
Now, since both $W$ and $T'$ are $T$-invariant, i.e., $TW \subseteq W$ and $TW' \subseteq W'$, we must have $m < k$ and $m' < k'$ for otherwise $W = 0$ or $W' = 0$, contrary to our assumptions.
Let $n = \max{m,m'}$; $q^n$ annihilates both $W$ and $W'$, so $q^n$ annihilates $W \oplus W' = V$. However, $n < k$, and $q^k$ is the minimal polynomial of $W$, which is a contradiction.
Therefore, if $W$ is a $T$-invariant subspace, then it cannot have a nontrivial $T$-invariant complementary subspace.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python CApi Reference Count Details I'm looking at some example code here ( https://docs.python.org/2.0/api/refcountDetails.html ) and trying to get a better understanding of the difference between two of the examples:  The first example is:
PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
PyTuple_SetItem(t, 2, PyString_FromString("three"));

The author explains that PyTuple_SetItem() steals the reference (so there is no need to DECREF it).  Fine, I get that.  The author then presents similar code using PySequence_SetItem() which does not steal the reference, so the caller must DECREF, and the example code looks like this:
PyObject *l, *x;

l = PyList_New(3);
x = PyInt_FromLong(1L);
PySequence_SetItem(l, 0, x); Py_DECREF(x);
x = PyInt_FromLong(2L);
PySequence_SetItem(l, 1, x); Py_DECREF(x);
x = PyString_FromString("three");
PySequence_SetItem(l, 2, x); Py_DECREF(x);
PyObject *l, *x;

My question is what would happen if the 2nd example were similar to the first in passing PyTYPE_FromSOMETYPE as follows?
PyObject *l;

l = PyList_New(3);
PySequence_SetItem(l, 0, PyInt_FromLong(1L));
PySequence_SetItem(l, 1, PyInt_FromLong(2L));
PySequence_SetItem(l, 2, PyString_FromString("three"));

Is this last case benign, or does it cause a memory leak (because PySequence_SetItem will not take ownership of the reference created by PyInt_FromLong and PyString_FromString, and neither does the caller DECREF it)??

A: It causes a memory leak.
When you create an object, it starts off with a refcount of 1. The object only gets deleted if the refcount goes to 0.
First example: When you pass your new object to a function that steals a reference (takes ownership), like PyTuple_SetItem, the refcount is not incremented, so it's still 1. When the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 0, so it'll be destroyed. All is good.
Third example: When you pass your new object to a function that does not steal a reference (makes a new reference), like PySequence_SetItem, the refcount is incremented, so it's 2. When the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 1, so it won't be destroyed. And, since nobody else has a reference to it anymore (unless you stored it somewhere), there's no way anyone can ever decref it. So it's leaked.
Second example: When you pass your new object to a function that does not steal a reference (makes a new reference), like PySequence_SetItem, but then call Py_DECREF on it, the refcount is incremented to 2 and decremented back to 1. So, when the tuple eventually gets destroyed and decrefs all of its elements, the count will drop to 0. All is good again.

If you're wondering why Python would both with any non-stealing functions, you just need to think of a less trivial case.
What if you wanted to put the item in two tuples instead of one? Or if you wanted to put it in a tuple, but also store it in a C static pointer, or in some module's globals, or somewhere else? You want the reference count to be bumped up by 2 if you want to store it in two places, and them dropped back down by 1 when your local variable goes away. For the really simple case where you're just creating something and immediately handing it off, reference-stealing functions let you avoid that one-incref-and-one-decref, as well as being nice and convenient for one-lines. But for anything more complicated, that doesn't make sense.


text:
Q: Facebook is not fetching link data This is similar to this question but it seems that I have all the og tags in place. I am not an expert.
Share link on facebook. facebook do not fetch to get description and image
My problem:
When I paste a link on facebook, it doesn't show anything. I have checked my source and below is the page where the problem is.
goo.gl/gCul4E (homepage)
goo.gl/iDYzbZ (inner page)

Facebook Open Graph Object Debugger gives the following error:

Error parsing input URL, no data was cached, or no data was scraped

When I click "See exactly what our scraper sees for your URL", I get the following message:

Document returned no data

Thanks in advance.


text:
Q: Any way to block-copy part of picture in WPF? I'm looking for analog of BitBlt functionality, which was available in WinAPI.

A: Check out method BitmapSource.CopyPixels (it also has one more overload).

A: Where do you want to copy that part to?  Another image?
In WPF, you create a Graphics context on an empty Image, then you draw the Image into this Graphics context, where you can specify parameters such as the location and width/height of the source image to draw.


text:
Q: awk rounding the float numbers My first line of file a.txt contains following and fields are separated by (,)
ab,b1,c,d,5.986627e738,e,5.986627e738
cd,g2,h,i,7.3423542344,j,7.3423542344
ef,l3,m,n,9.3124234323,o,9.3124234323

when I issue the below command
awk -F"," 'NR>-1{OFS=",";gsub($5,$5+10);OFS=",";print }' a.txt

it is printing
ab,b1,c,d,inf,e,inf
cd,g2,h,i,17.3424,j,17.3424
ef,l3,m,n,19.3124,o,19.3124

Here I have two issues

*

*I asked awk to add 10 to only 5th column but it has added to 7th column as well due to duplicate entries

*It is rounding up the numbers, instead, I need decimals to print as it is
How can I fix this?

A: awk 'BEGIN {FS=OFS=","}{$5=sprintf("%.10f", $5+10)}7' file

*

*in your data, the $5 from line#1 has an e, so it was turned into 10.0000... in output.

*you did substitution with gsub, therefore all occurrences will be replaced.

*printf/sprintf should be considered to output in certain format.

tested with gawk
If you want to set the format in printf dynamically:
kent$  cat f
ab,b1,c,d,5.9866,e,5.986627e738
cd,g2,h,i,7.34235,j,7.3423542344
ef,l3,m,n,9.312423,o,9.3124234323

kent$  awk 'BEGIN {FS=OFS=","}{split($5,p,".");$5=sprintf("%.*f",length(p[2]), $5+10)}7' f
ab,b1,c,d,15.9866,e,5.986627e738
cd,g2,h,i,17.34235,j,7.3423542344
ef,l3,m,n,19.312423,o,9.3124234323

A: what you did is replacement on the whole record, what you really want to do is
awk 'BEGIN {FS=OFS=","}
           {$5+=10}1' a.txt


text:
Q: Cakephp HABTM association is not working I need an association where therapists have many children and visa-versa.
I have 3 tables:
therapists
children
children_therapists
You can see the association below:
Therapist.php
 public $hasAndBelongsToMany = array('Child' =>
                array(
                               'className' => 'Children',
                               'joinTable' => 'children_therapists',
                               'foreignKey' => 'therapist_id',
                               'associationForeignKey' => 'child_id',
                               'unique' => true,
                               'conditions' => '',
                               'fields' => '',
                               'order' => 'Child.last_name',
                               'limit' => '',
                               'offset' => '',
                               'finderQuery' => '',
                               'with' => ''
                           )
    );

In the Child.php model, I tried this code:
public $useTable = 'children';

but that didn't work.
When I code against it, I get the following error:
Missing Database Table
Error: Table childrens for model Child was not found in datasource default.
Any help is greatly appreciated.
Thanks,
Greg

A: The Child model is not used
Because the code in the question does not reference it.
public $hasAndBelongsToMany = array(
    'Child' => array(
       'className' => 'Children',
//                    ^ Supposed to be a model name

It references the Children model which doesn't exist.
To highlight the meaning of the array key and className keys compare to:
class User extends AppModel {

    public $hasAndBelongsToMany = array(
        'Friend' => array(
    //  ^ Whatever you want
           'className' => 'Child',
    //                    ^ A model name

A simple fix
To correct the question asked, simply replace
'className' => 'Children'

with
'className' => 'Child'


text:
Q: MVC 6 Identity ChangePassword for "SuperUser" I need for "SuperUser" ability to change password of any user in identity system. I checked two solution.
1) add this one overloaded function to CustomUserManager for CRUD:
public async Task<IdentityResult> ChangePasswordAsync(TenantUser user, string newPassword)
    {...}

Use original function with token parameter, but this function in controller not working and return invalid token:
string Token = await manager.GeneratePasswordResetTokenAsync(TenantUser);
var resultPasswordChange = await manager.ResetPasswordAsync(TenantUser, Token, model.TenantUsersPassword.Password);

Custom user manager: All PRIVATE functions and  parameters has been already copied from orig UserManager to derived CustomUserManager. Resources for NotSupportedException are still not available... I'm not satisfacted with result...
Can you help me? What is better? Implement CustomUserManager or solve invalid token error? And please how to do?
Example what you need to copy for one more function (ChangePasswordAsync):
namespace Program.Models
{

public class TenantUserManager<TenantUser> : UserManager<TenantUser>, IDisposable where TenantUser : class
{
   // protected const string ResetPasswordTokenPurpose = "ResetPassword";
  //  protected const string ConfirmEmailTokenPurpose = "EmailConfirmation";

    private TimeSpan _defaultLockout = TimeSpan.Zero;
    private bool _disposed;
    private readonly HttpContext _context;
    private CancellationToken CancellationToken => _context?.RequestAborted ?? CancellationToken.None;

    /// <summary>
    /// Constructs a new instance of <see cref="UserManager{TenantUser}"/>.
    /// </summary>
    /// <param name="store">The persistence store the manager will operate over.</param>
    /// <param name="optionsAccessor">The accessor used to access the <see cref="IdentityOptions"/>.</param>
    /// <param name="userValidators">A collection of <see cref="IUserValidator{TenantUser}"/> to validate users against.</param>
    /// <param name="passwordValidators">A collection of <see cref="IPasswordValidator{TenantUser}"/> to validate passwords against.</param>
    /// <param name="keyNormalizer">The <see cref="ILookupNormalizer"/> to use when generating index keys for users.</param>
    /// <param name="errors">The <see cref="IdentityErrorDescriber"/> used to provider error messages.</param>
    /// <param name="services">The <see cref="IServiceProvider"/> used to resolve services.</param>
    public TenantUserManager(IUserStore<TenantUser> store, IOptions<IdentityOptions> optionsAccessor,
    IPasswordHasher<TenantUser> passwordHasher, IEnumerable<IUserValidator<TenantUser>> userValidators,
    IEnumerable<IPasswordValidator<TenantUser>> passwordValidators, ILookupNormalizer keyNormalizer,
    IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TenantUser>> logger, IHttpContextAccessor contextAccessor)
    : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor)
    {

    }
    /// <summary>
    /// Gets or sets the persistence store the manager operates over.
    /// </summary>
    /// <value>The persistence store the manager operates over.</value>
    protected internal IUserStore<TenantUser> Store { get; set; }

    /// <summary>
    /// Gets the <see cref="ILogger"/> used to log messages from the manager.
    /// </summary>
    /// <value>
    /// The <see cref="ILogger"/> used to log messages from the manager.
    /// </value>
 //   protected internal virtual ILogger Logger { get; set; }

    internal IPasswordHasher<TenantUser> PasswordHasher { get; set; }

    internal IList<IUserValidator<TenantUser>> UserValidators { get; } = new List<IUserValidator<TenantUser>>();

    internal IList<IPasswordValidator<TenantUser>> PasswordValidators { get; } = new List<IPasswordValidator<TenantUser>>();

    internal ILookupNormalizer KeyNormalizer { get; set; }

    internal IdentityErrorDescriber ErrorDescriber { get; set; }

    internal IdentityOptions Options { get; set; }

    public async Task<IdentityResult> ChangePasswordAsync(TenantUser user, string newPassword)
    {
        ThrowIfDisposed();
        var passwordStore = GetPasswordStore();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }
        var result = await UpdatePasswordHash(passwordStore, user, newPassword);
        if (!result.Succeeded)
        {
            return result;
        }
        return await UpdateUserAsync(user);
      //   Logger.LogWarning(2, "Change password failed for user {userId}.", await GeTenantUserIdAsync(user));
      //  return IdentityResult.Failed(ErrorDescriber.PasswordMismatch());
    }

    private static string NewSecurityStamp()
    {
        return Guid.NewGuid().ToString();
    }

    private IUserSecurityStampStore<TenantUser> GetSecurityStore()
    {
        var cast = Store as IUserSecurityStampStore<TenantUser>;
        if (cast == null)
        {
            throw new NotSupportedException("Resources.StoreNotIUserSecurityStampStore");
        }
        return cast;
    }

    // Update the security stamp if the store supports it
    internal async Task UpdateSecurityStampInternal(TenantUser user)
    {
        if (SupportsUserSecurityStamp)
        {
            await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp(), CancellationToken);
        }
    }

    internal async Task<IdentityResult> UpdatePasswordHash(IUserPasswordStore<TenantUser> passwordStore,
       TenantUser user, string newPassword, bool validatePassword = true)
    {
        if (validatePassword)
        {
            var validate = await ValidatePasswordInternal(user, newPassword);
            if (!validate.Succeeded)
            {
                return validate;
            }
        }
        var hash = newPassword != null ? PasswordHasher.HashPassword(user, newPassword) : null;
        await passwordStore.SetPasswordHashAsync(user, hash, CancellationToken);
        await UpdateSecurityStampInternal(user);
        return IdentityResult.Success;
    }

    private async Task<IdentityResult> ValidateUserInternal(TenantUser user)
     {
         var errors = new List<IdentityError>();
         foreach (var v in UserValidators)
         {
             var result = await v.ValidateAsync(this, user);
             if (!result.Succeeded)
             {
                 errors.AddRange(result.Errors);
             }
         }
         if (errors.Count > 0)
         {
         //    Logger.LogWarning(13, "User {userId} validation failed: {errors}.", await GeTenantUserIdAsync(user), string.Join(";", errors.Select(e => e.Code)));
             return IdentityResult.Failed(errors.ToArray());
         }
         return IdentityResult.Success;
     }

    private async Task<IdentityResult> ValidatePasswordInternal(TenantUser user, string password)
     {
         var errors = new List<IdentityError>();
         foreach (var v in PasswordValidators)
         {
             var result = await v.ValidateAsync(this, user, password);
             if (!result.Succeeded)
             {
                 errors.AddRange(result.Errors);
             }
         }
         if (errors.Count > 0)
         {
          //   Logger.LogWarning(14, "User {userId} password validation failed: {errors}.", await GeTenantUserIdAsync(user), string.Join(";", errors.Select(e => e.Code)));
             return IdentityResult.Failed(errors.ToArray());
         }
         return IdentityResult.Success;
     }

    private async Task<IdentityResult> UpdateUserAsync(TenantUser user)
     {
         var result = await ValidateUserInternal(user);
         if (!result.Succeeded)
         {
             return result;
         }
         await UpdateNormalizedUserNameAsync(user);
         await UpdateNormalizedEmailAsync(user);
         return await Store.UpdateAsync(user, CancellationToken);
     }

    private IUserPasswordStore<TenantUser> GetPasswordStore()
     {
         var cast = Store as IUserPasswordStore<TenantUser>;
         if (cast == null)
         {
             throw new NotSupportedException("Resources.StoreNotIUserPasswordStore"); //Resources are not awailable
         }
         return cast;
     }

    /// <summary>
    /// Releases the unmanaged resources used by the role manager and optionally releases the managed resources.
    /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
    protected override void Dispose(bool disposing)
     {
         if (disposing && !_disposed)
         {
             Store.Dispose();
            _disposed = true;
        }
     }

     protected void ThrowIfDisposed()
     {
         if (_disposed)
         {
             throw new ObjectDisposedException(GetType().Name);
         }
     }
}


text:
Q: Cant load folder to import (Pycharm) Hi guys I have a problem. I cant import my module "browser.py" because i cant load my third directory (here: "enums1").
Everytime I enter the dot after the directory "whatsapp", only par, not and main are shown as the only options.
Load Directory


text:
Q: iOS TableView not displaying cells I have seen several related questions, but mine is different in that I want to do it purely in coding, so without storyboards or interface builder.
Basically I get lost in how to properly display the cells in a TableView. I have created a very simple SplitView test application. In it I try to show the same TableView twice: once in the TableViewController and once in the DetailViewController (for a user this would make little sense, but I try to grasp how to get this done).
In the TableViewController, the 3 cells show correctly, but in the DetailView, the TableView shows without the cells. There must be a simple step to have the cells drawn, but all the example cases I find assume you use storyboards or IB
In the SplitView I have:
- (id) init{

    self = [super init];

    JBDetailViewController *detailVC = [JBDetailViewController controller];
    UINavigationController *detailNav = [[UINavigationController alloc] initWithRootViewController:detailVC];

    JBTableViewController *rootVC2 = [[JBTableViewController alloc] init];
    rootVC2.title = @"A TableVC title";

    UINavigationController *rootNav2 = [[UINavigationController alloc] initWithRootViewController:rootVC2];

    self.viewControllers = @[rootNav2, detailNav];
    self.delegate = detailVC;
    self.tabBarItem.title = @"a Tab title";

return self;

}
In the DetailViewer I have:
- (void) loadView {
[super loadView];

self.view.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.85f];
JBTableViewController *rootVC2 = [[JBTableViewController alloc] init];
[rootVC2 loadView];
rootVC2.title = @"Test van Justus";

rootVC2.view.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.85f];

[self.view addSubview:rootVC2.view];

}
Both use the same JBTableViewController that is very simple and should display 3 cells, which it does in the VC, but not in the DetailView.
What do I do wrong?


text:
Q: Firebase: How to add an index for a nested field? I have a locations-orders table that looks like this:
{
  "0BW3H9T3R7HJB" : {
    "orders" : {
      "01750ea0-4980-4bc4-58b2-988c02324e671478636582396" : {
        "created_at" : 1478636560000,
      },
      "01750ea0-4980-4bc4-58b2-988c02324e671478636582483" : {
        "created_at" : 1478636560000,
      }
    }
}

Each location-orders node has an orders node with multiple keys/objects. Those objects have a created_at field on it.
I added this to my database Rules:
{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      ".indexOn": ["orders/created_at"]
    }
  }
}

However, Firebase is still complaining that I'm missing an index:
Using an unspecified index. Consider adding ".indexOn": "created_at" at /locations-orders/1JS53G0TT5ZQD/orders to your security rules for better performance

Am I supposed to run something to create the index? Or is it written incorrectly?
=== UPDATE ===
I changed my file to look into:
{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      "$location_id": {
        ".indexOn": ["orders/created_at", "orders/status_updated_at"]
      }
    }
  }
}

but I still get the same warning:
Using an unspecified index. Consider adding ".indexOn": "created_at" at /locations-orders/1JS53G0TT5ZQD/orders to your security rules for better performance

A: If you look at your data structure, there is no orders/created_at under /location-order/$orderId.
{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      "$someid": {
        ".indexOn": ["orders/created_at"]
      }
    }
  }
}

A: Try this:
{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      "orders": {
        "$orderid": {
          ".indexOn": "created_at"
        }
      }
    }
  }
}


text:
Q: google data studio, parse date not working on %Y%W format Everything is in the screenshot:
I have a column with date string in format %Y%W.
The PARSE_DATE function cannot parse the data correctly, it just return the year correctly but doesn't parse the week number
Data sample:
week_year
202204
202208
202203
202205
202202
202207
202206

A: As @MarcinJ replied

%W is not supported in Google Data Studio's PARSE_DATE unfortunately, as per their docs. If you have data source that supports SQL, you can try using a custom query to parse the date before it reaches Data Studio

So basically it wont work


text:
Q: How to provide hint to iOS speech recognition API? I want to create an app that receive voice input using iOS speech API.
In google's API, there is an option for speechContext which I can provide hint or bias to some uncommon words.
Do iOS API provide this feature? I've been searching the site for a while but din't find any.

A: there is no sample code about implementing hints for Google Speech Clouds for Swift online, so I made it up!
Open this class: SpeechRecognitionService.swift
You have to add your hint list array to the SpeechContext, add the SpeechContext to RecognitionConfig, and finally add RecognitionConfig to Streaming recognition config. Like this:
            let recognitionConfig = RecognitionConfig()
            recognitionConfig.encoding =  .linear16
            recognitionConfig.sampleRateHertz = Int32(sampleRate)
            recognitionConfig.languageCode = "en-US"
            recognitionConfig.maxAlternatives = 3
            recognitionConfig.enableWordTimeOffsets = true
            let streamingRecognitionConfig = StreamingRecognitionConfig()
            streamingRecognitionConfig.singleUtterance = true
            streamingRecognitionConfig.interimResults = true

            //Custom vocabulary (Hints) code
            var phraseArray=NSMutableArray(array: ["my donkey is yayeerobee", "my horse is tekkadan", "bet four for kalamazoo"])
            var mySpeechContext = SpeechContext.init()
            mySpeechContext.phrasesArray=phraseArray
            recognitionConfig.speechContextsArray = NSMutableArray(array: [mySpeechContext])
            streamingRecognitionConfig.config = recognitionConfig
            //Custom vocabulary (Hints) code

            let streamingRecognizeRequest = StreamingRecognizeRequest()
            streamingRecognizeRequest.streamingConfig = streamingRecognitionConfig

Bonus: Adding your custom words mixed inside a simple phrase instead of adding the word alone gave me better results.


text:
Q: Kotlin: Fragments used for navigation drawer supportFragmentManager not be able to replace layout as expected This is the code of MainActivity.kt and i am using navigation drawer in this application
fun displayScreen(id: Int) {

    val fragment = when (id) {

        R.id.nav_home -> {

            HomeFragment()
        }
        R.id.nav_favourite -> {

            FavouriteFragment()
        }
        R.id.nav_About -> {
            AboutFragment()
        }
        R.id.nav_Feedback -> {
            FeedbackFragment()
        }
        else -> {
            HomeFragment()
        }

    }

Till now the code is working fine. I think

     supportFragmentManager.beginTransaction().replace(R.id.r1,
      fragment).commit()

After the layout get replaced the Objects automatically moved to top left
        corner

}

override fun onNavigationItemSelected(item: MenuItem): Boolean {

    when (item.itemId) {
        R.id.nav_home -> {
            displayScreen(item.itemId)
            supportActionBar?.setTitle("Home")
        }
        R.id.nav_favourite -> {
            displayScreen(item.itemId)
            supportActionBar?.setTitle("Favourite")
        }
        R.id.nav_About -> {
            displayScreen(item.itemId)
            supportActionBar?.setTitle("About")
        }
        R.id.nav_Feedback -> {
            displayScreen(item.itemId)
            supportActionBar?.setTitle("Feedback")
        }

    }
    displayScreen(item.itemId)

    drawer_layout.closeDrawer(GravityCompat.START)
    return true
}

Expected

enter image description here

Getting

enter image description here

content_main

<RelativeLayout
     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:id="@+id/r1"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:layout_behavior="@string/appbar_scrolling_view_behavior"
     tools:context="com.example.shikh.kotlinnavigationdrawer.MainActivity"
     tools:showIn="@layout/app_bar_main">

</RelativeLayout>

fragment_home

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Home"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView5"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Click" />

</RelativeLayout>

A: 1) Remove the constraint attributes.
2) Change your activity's layout to FrameLayout.
3) Remove the app:layout_behavior="@string/appbar_scrolling_view_behaviorpart since it is not inside a CoordinatorLayout.


text:
Q: Stl c++ dynamic memory allocation I came across some legacy code and I see this.
typedef std::queue < EventDataPair > EventQueue;
_eventQueue = new EventQueue();

Why would one want to use a stl Queue allocated on Heap???
The class containing this code is a Singleton.
To Generalise it, When should one allocate a stl on Heap???
STL's themselves are dynamic in nature, and they may use heap internally.
Furthermore, won't you have the overhead of deallocating it in the destructor??

A: Well, unless you want to share the particular object between different contexts in the code there isn't much incentive to allocate on heap.
However for some legacy architectures you might be concerned with the size of your stack.

A: One reason I can think of, is to avoid overhead of creating a copy when returning it from a function.
However, this is not needed any more with C++ 11 and move semantics.
Have a look at this example that Bjarne Stroustrap is talking about.


text:
Q: assembly lea instruction of int *q = p++ and int c = a++ In order to deepen the impression about how the " (*p)++ " works, I wrote some test codes like:
int main()
{
  int  a = 3;
  int *p = &a;
  int b = (*p)++;
  int *q = p++;
  int c = a++;
  int d = c++;
  printf("a = %d, b = %d, c = %d, d = %d, p = %#x, q = %#x\n",a, b, c, d, p, q);
}

OUTPUT IS: a = 5, b = 3, c = 5, d = 4, p = 0xc6dc3490, q = 0xc6dc348c
But my question is about the assembly (codes are in orders and not off and on):
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 48

;int a = 3 :
        mov     DWORD PTR [rbp-36], 3

;int *p = &a :
        lea     rax, [rbp-36]
        mov     QWORD PTR [rbp-8], rax

;int b = (*p)++ :
        mov     rax, QWORD PTR [rbp-8]
        mov     eax, DWORD PTR [rax]
        lea     ecx, [rax+1]               ;Flag1
        mov     rdx, QWORD PTR [rbp-8]
        mov     DWORD PTR [rdx], ecx
        mov     DWORD PTR [rbp-12], eax

;int *q = p++ :
        mov     rax, QWORD PTR [rbp-8]     ;Flag2
        lea     rdx, [rax+4]               ;Flag3
        mov     QWORD PTR [rbp-8], rdx
        mov     QWORD PTR [rbp-24], rax

;int c = a++;
        mov     eax, DWORD PTR [rbp-36]
        lea     edx, [rax+1]               ;Flag4
        mov     DWORD PTR [rbp-36], edx
        mov     DWORD PTR [rbp-28], eax

;int d = c++;
        mov     eax, DWORD PTR [rbp-28]
        lea     edx, [rax+1]               ;Flag5
        mov     DWORD PTR [rbp-28], edx
        mov     DWORD PTR [rbp-32], eax

... ... (ignore some)

Please pay attention to the "Flagx" lines which make me confused.
From above , we know that
when pointer:   int *q = p++ :
lea     rdx, [rax+4]    ;Flag3

Here, 'lea' seems to read the addr value store in 'rax' and +4. then pass to 'rdx'.
while:   int c = a++ or int d = c++ :
lea     edx, [rax+1]    ;Flag4/Flag5

Here,  'lea' seems to read the content of the addr value store in 'rax' (which is 3 here), and +1, come to 4 and pass to 'edx'.
But! the point is that 'rax' in these two statments are the same one. They're all from
mov     rax, QWORD PTR [rbp-8]   ;Flag2

As we can see, they ( Flag3 and Flag4/Flag5 )  look very similar, but they work very differently base on a same 'rax', how come ?  Can the 'lea' instruction distinguish between 'rdx' and 'edx / ecx' and turn out different results ?
Thank you very much.

A:
Here, 'lea' seems to read the content of the addr value store in 'rax' (which is 3 here), and +1, come to 4 and pass to 'edx'.

No, you are mistaken. lea edx, [rax+1] doesn't change rax. rax is already 3 before the lea instruction is evaluated.

But! the point is that 'rax' in these two statments are the same one. They're all from mov rax, QWORD PTR [rbp-8]

No, you are mistaken. rax is being set by mov eax, DWORD PTR [rbp-36].
Different parts of the general purpose registers can be referenced using different names.
   64                  32        16    8    0
    |                   |         |    |    |
    v                   v         v    v    v
     +----+----+----+----+----+----+----+----+
     |    |    |    |    |    |    |    |    |
     +----+----+----+----+----+----+----+----+

     |<------------------------------------->| rax
                         |<----------------->| eax
                                   |<------->|  ax
                                   |<-->|       ah
                                        |<-->|  al

This means that when you write to eax, you are also writing to the bottom half of rax (and the top half gets zeroed).
So,
                                         ; rax       eax          rdx       edx
; q = p++                                ; +----+----+----+----+  +----+----+----+----+
A1      mov     rax, QWORD PTR [rbp-8]   ; |                 p |  |               ??? |
A2      lea     rdx, [rax+4]             ; |                 p |  |               p+4 |
A3      mov     QWORD PTR [rbp-8], rdx   ; |                 p |  |               p+4 |
A4      mov     QWORD PTR [rbp-24], rax  ; |                 p |  |               p+4 |
; c = a++                                ; |                 p |  |               p+4 |
B1      mov     eax, DWORD PTR [rbp-40]  ; |       0 |       a |  |               p+4 |
B2      lea     edx, [rax+1]             ; |       0 |       a |  |       0 |     a+1 |
B3      mov     DWORD PTR [rbp-40], edx  ; |       0 |       a |  |       0 |     a+1 |
B4      mov     DWORD PTR [rbp-28], eax  ; |       0 |       a |  |       0 |     a+1 |
                                         ; +----+----+----+----+  +----+----+----+----+

A: p and q are pointers to int and the size of an int is 4 on your platform. So incrementing p actually increments its value by 4.
int *q = p++;

   mov     rax, QWORD PTR [rbp-8]     ; rax = p
   lea     rdx, [rax+4]               ; same as rdx = rax + 4
   mov     QWORD PTR [rbp-8], rdx     ; p = rdx
   mov     QWORD PTR [rbp-24], rax    ; q = rax

c is an int. So incrementing a actually just increments its value by 1.
c = a++;

   mov     eax, DWORD PTR [rbp-40]    ; rax = a (yes modifying eax actually modifies rax)
   lea     edx, [rax+1]               ; same as edx = rax + 1
   mov     DWORD PTR [rbp-40], edx    ; a = edx
   mov     DWORD PTR [rbp-28], eax    ; c = eax (eax still contains the inital value of a)

More details about the LEA instructions here.

A: In line int *q = p++ the address pointer is getting incremented. As you know the size of int is 4 bytes and size of int is size of pointer variable, so in assembly code you can see lea     rdx, [rax+4].
But in line int c = a++ the value of variable a is getting incremented. So in assembly code you can see lea     edx, [rax+1].
Note: Size of int may vary from compiler to compiler. But as per GCC based compilers and in your case int is 4 byte long


text:
Q: Centering header content divs I'm having trouble centering the divs named 'one' and 'two'. They need to retain their styles exactly as they are which keep them side by side and margins but also be centered which is the bit I can't work out?
Also the nav divs need to be centered which I have achieved with the styles below.

#header {
  position: relative;
  overflow: hidden;
  min-width:300px;
  height:auto;
  text-align: center;
  border-bottom:1px solid  #ccc;
  padding-bottom:5px;
  margin: 0 5px 0 5px;
}
#header #one {
  font: 1.625em "Arial Black", Helvetica, sans-serif;
  font-weight:100;
  float: left;
  color:#95061e;
  margin-bottom:10px;
 }
#header #two {
  font:1.625em Arial, Helvetica, sans-serif;
  float:left;
  margin-top:3px;
  margin-left:3px;
  margin-right:5px;
  color:#953606;
 }

Birch

Wood

A: Use display:inline-block; instead of float:left;.

#header {
  position: relative;
  overflow: hidden;
  min-width:300px;
  height:auto;
  text-align: center;
  border-bottom:1px solid  #ccc;
  padding-bottom:5px;
  margin: 0 5px 0 5px;
}
#header #one {
  font: 1.625em "Arial Black", Helvetica, sans-serif;
  font-weight:100;
  display:inline-block;
  color:#95061e;
  margin-bottom:10px;
 }
#header #two {
  font:1.625em Arial, Helvetica, sans-serif;
  display:inline-block;
  margin-top:3px;
  margin-left:3px;
  margin-right:5px;
  color:#953606;
 }

Birch

Wood

A: use this code:
#header {
  position: relative;
  overflow: hidden;
  height:auto;
  text-align: center;
  border-bottom:1px solid  #ccc;
  padding-bottom:5px;
  margin: 0 auto;
}
#header #one {
        font: 1.625em "Arial Black", Helvetica, sans-serif;
        font-weight:100;
        color:#95061e;
        margin-bottom:10px;display:inline-block;
    }
#header #two {
        font:1.625em Arial, Helvetica, sans-serif;margin-top:3px;
    display:inline-block;
        color:#953606;
    }

jsfiddle link click here

A: Remove the floating in your css, as shown here.
https://jsfiddle.net/dy8bzuv3/
If you want to have both divs in a single line, simply add display:inline; to your css rules for #one and also #two

A: Good luck on your learning journey! The change I've made here is the #one and #two divs are being given display:inline. This will treat them similar to text, so the text-align option applies to them.

#header {
  position: relative;
  overflow: hidden;
  min-width:300px;
  height:auto;
  text-align: center;
  border-bottom:1px solid  #ccc;
  padding-bottom:5px;
  margin: 0 5px 0 5px;
}
#header #one {
  font: 1.625em "Arial Black", Helvetica, sans-serif;
  font-weight:100;
  color:#95061e;
  margin-bottom:10px;
  display: inline;
 }
#header #two {
  font:1.625em Arial, Helvetica, sans-serif;
  margin-top:3px;
  margin-left:3px;
  margin-right:5px;
  color:#953606;
  display: inline;
 }

Birch

Wood


text:
Q: Can I compile my code in JAVA 6 And run it in JAVA 8 I have to connect to a service that accepts only TLS 1.2 handshake protocols,in our organization we use java 1.6 which doesnt support TLS 1.2 ,I was thinking by compiling the java code in java 6 and have java 8 in my weblogic server can I use tls 1.2.

A:
Can I compile my code in JAVA 6 And run it in JAVA 8?

Yes, you can.
Java versions are expected to be binary backward-compatible.
So JDK 8 can run code compiled by JDK 7 or JDK 6.
You can always refer Compatibility Guide after a major release to check if something specific is not backward compatible


text:
Q: getting null values when parsing json column in .csv file using from_json (using spark with scala ver 2.4) H/a, i am getting null values when using from_json , can you help me figure out the missing piece here.
~ input is the .csv file with json e.g.
id,request
1,{"Zipcode":704,"ZipCodeType":"STANDARD","City":"PARC PARQUE","State":"PR"}
2,{"Zipcode":704,"ZipCodeType":"STANDARD","City":"PASEO COSTA DEL SUR","State":"PR"}

~my code (scala/spark)
val input_df = spark.read.option("header",true).option("escape","\"").csv(json_file_input)
 val json_schema_abc = StructType(Array(
      StructField("Zipcode",IntegerType,true),
      StructField("ZipCodeType",StringType,true),
      StructField("City",StringType,true),
      StructField("State",StringType,true))
    )
  val output_df =   input_df.select($"id",from_json(col("request"),json_schema_abc).as("json_request"))
                    .select("id","json_request.*")

A: You problem is because the commas in your json column are being used as delimiters. If you have a look at the contents of you input_df:
val input_df = spark.read.option("header",true).option("escape","\"").csv(json_file_input)

input_df.show(false)
+---+--------------+
|id |request       |
+---+--------------+
|1  |{"Zipcode":704|
|2  |{"Zipcode":704|
+---+--------------+

You see that the request column is not complete: it was chopped off at the first comma in the request column.
The rest of your code is correct, you can test it like this:
val input_df = Seq(
  (1, """{"Zipcode":704,"ZipCodeType":"STANDARD","City":"PARC PARQUE","State":"PR"}"""),
  (2, """{"Zipcode":704,"ZipCodeType":"STANDARD","City":"PASEO COSTA DEL SUR","State":"PR"}""")
).toDF("id","request")

import org.apache.spark.sql.types.{StructType, StructField, IntegerType, StringType}

val json_schema_abc = StructType(Array(
  StructField("Zipcode",IntegerType,true),
  StructField("ZipCodeType",StringType,true),
  StructField("City",StringType,true),
  StructField("State",StringType,true))
)

val output_df = input_df
  .select($"id",from_json(col("request"),json_schema_abc).as("json_request"))
  .select("id","json_request.*")

output_df.show(false)
+---+-------+-----------+-------------------+-----+
|id |Zipcode|ZipCodeType|City               |State|
+---+-------+-----------+-------------------+-----+
|1  |704    |STANDARD   |PARC PARQUE        |PR   |
|2  |704    |STANDARD   |PASEO COSTA DEL SUR|PR   |
+---+-------+-----------+-------------------+-----+

I would suggest changing your CSV file's delimiter (for example ; if that does not appear in your data), that way the commas won't be bothering you.


text:
Q: How do I create a lambda expression from a Kotlin interface? I have a simple Kotlin interface:
@FunctionalInterface
interface ServiceMethod<T> {
  fun doService(): T
}

This, in spite of the name, is essentially identical to Java's Supplier functional interface. The only difference is that I can implement the Supplier, and I can't implement my own.
val supplier = Supplier<String> {
  "Hello"
}
val serviceMethod = ServiceMethod<String> {
  "Hello"
}

The ServiceMethod implementation gives me a compiler error saying "Interface ServiceMethod does not have constructors." Huh? Of course it doesn't! It's a functional interface.
I know that I can write it as an anonymous inner class:
val serviceMethod = object : ServiceMethod<String> {
  override fun doService(): String {
    return "Hello"
  }
}

But this is much more verbose. In this case I could just use the Supplier interface, but that won't work for other interfaces. I shouldn't have to write an interface in Java, just to be able to a lambda in Kotlin. I'd rather use a lambda for all my Kotlin interfaces, especially since I'll be writing a lot of these. Am I missing something obvious?

A: Use the fun interface modifier since Kotlin 1.4
In Kotlin 1.3 and earlier, SAM (single abstract method) conversions, where you can instantiate an interface like Supplier using a lambda function, were only supported for Java interfaces.
The language designers originally thought SAM conversions wouldn't be useful for Kotlin interfaces, because a Kotlin function already has a type. For example, the type of your doService function can be written as () -> T. Instead of creating an object that implements an interface, you could simply write:
val serviceMethod: () -> String = { "Hello" }

Kotlin 1.4 adds SAM conversions for Kotlin interfaces, but it doesn't work out of the box for every interface. Instead, you have to apply the special fun modifier to a Kotlin interface to make it eligible for SAM conversion.
In your example, it would simply look like this:
fun interface ServiceMethod<T> {
  fun doService(): T
}

With the modifier added, you can create an instance using a lambda exactly as you were hoping in your question.
val serviceMethod = ServiceMethod<String> { "Hello" }

You can learn more in the Kotlin documentation for functional interfaces.


text:
Q: Do Cygwin paths propagate to native Python? I'm invoking a native (Windows) Python installation from Cygwin, and I'm
surprised to find that appending Cygwin paths, excluding those
starting with ~, to sys.path appear to be picked up successfully
by Python.
I can't wrap my head around why that is. I'd assume as much for
Python within Cygwin, but for native Python I'd think proper
Windows paths would have to be provided.
Why does this work? What am I not getting and where  can I find out more?
/home/waldo/foo/bar.py
import sys
sys.path.append('/home/waldo/foo/baz')
print 'sys.path:\n%s' % sys.path

import qux
qux.say_hi()

/home/waldo/foo/baz/qux.py
def say_hi():
    print 'hi'

$ cd /home/waldo/foo
$ /cygdrive/c/Python_2_7_13/python.exe bar.py
sys.path:
['C:\\home\\waldo\\foo', ..., '/home/waldo/foo/baz']
hi


text:
Q: Receive embedded RTF objects in Outlook 2007(To,Bcc,Cc - Fields) I have a problem with the Rich Text Fields of Outlook 2007. I try to read the values(email addresses) in the "To,Bcc,Cc Fields". I've read that the problem is known and that you only can read the fields when the mailItem in Outlook is saved.
So, I tried to access the email addresses with a window handler and the SendMessage function. But it only returns :

{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fswiss\fprq2\fcharset0
  Tahoma;}} {*\generator Riched20 12.0.6606.1000;}\viewkind4\uc1
  \pard\f0\fs17{\pict\wmetafile0

So I think Outlook replaces the email address with an embedded object and this object shows the email address. Can anybody help and tell me how to access the object and get the email address?

A: Use the MailItem.Recipients collection - it will be populated at all times.

A: I know this, but in Outlook 2007 there is a bug or missing feature. When you delete a (Email-Address)recipient from the to field, the mailItem is not refreshing its recipients collection. It only refreshes when a recipient is added and resolved!
So the only way I see is to read the content of the To-Field is..via SendMessage.
    private int EditStreamProc(MemoryStream dwCookie, IntPtr pbBuff, int cb, out int pcb)
    {
        pcb = cb;
        byte[] buffer = new byte[cb];
        Marshal.Copy(pbBuff, buffer, 0, cb);
        dwCookie.Write(buffer, 0, cb);
        return 0;
    }

    private delegate int EditStreamCallback(MemoryStream dwCookie, IntPtr pbBuff, int cb, out int pcb);

    [StructLayout(LayoutKind.Sequential)]
    private struct EDITSTREAM
    {
        public MemoryStream dwCookie;
        public int dwError;
        public EditStreamCallback pfnCallback;
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hwnd, uint msg, uint wParam, ref EDITSTREAM lParam);

    private const int WM_USER = 0x0400;
    private const int SF_RTF =3;
    private const int EM_STREAMOUT = WM_USER + 74;

    public string ReadRTFContentInOL2007(IntPtr handle)
    {
        string result = String.Empty;
        using (System.IO.MemoryStream stream = new MemoryStream())
        {
            EDITSTREAM editStream = new EDITSTREAM();
            editStream.pfnCallback = new EditStreamCallback(EditStreamProc);
            editStream.dwCookie = stream;

            SendMessage(handle, EM_STREAMOUT, SF_RTF, ref editStream);

            stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(stream))
            {
                result = reader.ReadToEnd();
            }
        }
        return result;
    }

When the email addresses are resolved then i receive this :

{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fswiss\fprq2\fcharset0 Tahoma;}} {*\generator Riched20 12.0.6606.1000;}\viewkind4\uc1 \pard\f0\fs17{\pict\wmetafile0

So Outlook replaces the plain text with an object and I need to receive all the Information of the RTF Content! I think somewhere in this content must be the email address. To - Field Class is : RichEdit20WPT


text:
Q: Does union pay and JCB card uses same specifications of EMV cards? can we read union pay and JCB cards using the specifications described in EMV standards for contact and contact less technologies

A: Sure you can do it in the lab for development purposes. For production Contactless and Contact EMV Kernels implementations must be certified.
EMV Contact terminal flow is the same for both schemes. The differences from the card profiles not visible from terminal contact interface.
In regards Contactless:

*

*JCB uses EMV Contactless Book C-5 Kernel 5 Specification,

*CUP uses EMV Contactless Book C-7 Kernel 7 Specification.

See EMVCo site for details.


text:
Q: Javascript object structure difference Can you explain me what is the difference between these two objects? How can I add word 'Product' at the beginning of the object?
Array(2)
0: {status: "published", _id: "5ff584e56153e75706790fa9", title: "bbbbb", imageUrl: "images/2021-01-06T11:59:42.006Z-7pIfYwyRCL8.jpg", price: 3333111, …}

1: Product {_id: "5ff58d1c6153e75706790faa", title: "5555555", imageUrl: "images/2021-01-06T11:30:26.521Z-7pIfYwyRCL8.jpg", description: "sddsdsd", price: 3333, …}length: 2

Also, the image:

A: Thats because this second one was most likely created using
const product = new Product(...)

while first one
const product = {...}

And so the type doesn't match
It's similar to this case
const someMap = new Map();
someMap.set("hello", "world");

const someObject = {
    hello: "world",
}

someMap == someObject // false
someMap === someObject // false

A: The Product prefix shows that it is an instance of a class Product, while the first object is a normal JavaScript object.
We can use instanceof to determine if an object is an instance of a class.
class Product {
    constructor() {}
}

const product = new Product()

// product
console.log(product instanceof Product); // true
// empty object
console.log({} instanceof Product); // false


text:
Q: Using chars into an int datatype Using C, One array with 5 memory spaces
int call[5]

I'm trying to figure out how to use the first 3 spaces of the array to make a base-36 conversion (meaning 1K0 base-36 equals to 2040 in base-10), the other 2 spaces would be filled with data (probably more ints).
However... does 1K0 look actually like an int? (to me K looks like a char and in theory, char should be enough -127 to 127 for the conversion using base-36)
however what would happen if i try to do this using int instead of char?
is there any alternative to use a base-36 conversion in the first array only mixed with ints for the rest of the spaces in memory
does it matter? (since the array was declared int)
EDIT: to be clear i just want to know if i can declare an int array and fill it with chars, and if i cant, how can i achieve this?

A: I'm not exactly sure if you can tell the compiler that, you can signal Hex (0x), octal (o) Binary (b) but base 36 is odd enough to not be standard.
You can always make a function (and maybe embed it in a class) that does the string-to-base10 conversion of base 36
I'll do my best in C terms
int base10Number = 0
int base36StringLenght = strlen(base35String);
for( int i = base36StringLenght - 1; i <= 0; i--){ //count from the end of the string back
  char c = base36String[i];
  if(c <= '9'){
    c -= '0' //gives a 0 to 9 range
  }
  else{ //assuming that the string is perfect and has no extra characters is safe to just do this
    c = tolower(c); //first make sure it's lowercase
    c -= 'a' + 10 // this will make the letters start at 10 dec
  }
  base10Number += c * pow(36, base36StringLenght - 1 - i) // the power function specifies which 'wheel' you're turning (imagine an old analog odometer) and then turns the wheel c times, then adds it to the overall sum.
}

This whole code works by the theory that every digit starting from the last is worth its base 10 number multipled by 36 to the power of its position from last.
So last digit is c * 36^0 which is one, the c*36^1 and so on. similar on how 2*10^1 equals 20 if the 2 is in second-to-last position.
Hope that some of this makes sense to you, and dont forget to make your base36 number a string
EDIT:
  I saw your edit to the answer and the short asnwer is yes, you can totally do that, it would be a waste of space since you'll have a whole 3 bytes unused at all times, you can simply make a char array. Besides, all string functions will demand you to feed them a char array (you can cast it) but if you're storing one digit per array space char will do the trick. If your array is dynamic and/or you need to make some math on it the base 36 to base 10 conversion will allow you to do math and to blow the whole array for a single int or float type. But if you're just going to store it to display it later or to feed it to another function in the same format the conversion is not necessary at all. (If you're working with a big ammount of this numbers and you need to put them in a database converting to base10 and storing in a single in will save tons of space)
PS: also edited the code to use ' ' enclosed chars instead of ascii numbers, thanks for the request!


text:
Q: Why aren't the overlapping annotations realigning themselves in the graph? I found some code on stack overflow about fixing overlapping annotations in matplotlib. I wanted to test it out, so I copied it into my own iPython notebook. However, when I ran it, it didn't have the same output.
The point of the code is to test if the annotations are overlapping, and if they are, they move so they aren't, and drop a red arrow to show the data point that they are describing. However, when I ran the code myself, this didn't happen.
I am using Python 3
Here is the original link: Matplotlib overlapping annotations / text
The code is shown below:
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def get_text_positions(text, x_data, y_data, txt_width, txt_height):
    a = zip(y_data, x_data)
    text_positions = list(y_data)
    for index, (y, x) in enumerate(a):
        local_text_positions = [i for i in a if i[0] > (y - txt_height)
                            and (abs(i[1] - x) < txt_width * 2) and i != (y,x)]
        if local_text_positions:
            sorted_ltp = sorted(local_text_positions)
            if abs(sorted_ltp[0][0] - y) < txt_height: #True == collision
                differ = np.diff(sorted_ltp, axis=0)
                a[index] = (sorted_ltp[-1][0] + txt_height, a[index][1])
                text_positions[index] = sorted_ltp[-1][0] + txt_height*1.01
                for k, (j, m) in enumerate(differ):
                    #j is the vertical distance between words
                    if j > txt_height * 2: #if True then room to fit a word in
                        a[index] = (sorted_ltp[k][0] + txt_height, a[index][2])
                        text_positions[index] = sorted_ltp[k][0] + txt_height
                        break
    return text_positions

def text_plotter(text, x_data, y_data, text_positions, txt_width,txt_height):
    for z,x,y,t in zip(text, x_data, y_data, text_positions):
        plt.annotate(str(z), xy=(x-txt_width/2, t), size=12)
        if y != t:
            plt.arrow(x, t,0,y-t, color='red',alpha=0.3, width=txt_width*0.1,
                head_width=txt_width, head_length=txt_height*0.5,
                zorder=0,length_includes_head=True)

# start new plot
plt.clf()
plt.xlabel("Proportional Euclidean Distance")
plt.ylabel("Percentage Timewindows Attended")
plt.title("Test plot")

together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
together.sort()

text = [x for (x,y,z) in together]
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]

p1 = plt.plot(eucs,covers,color="black", alpha=0.5)

txt_height = 0.0037*(plt.ylim()[1] - plt.ylim()[0])
txt_width = 0.018*(plt.xlim()[1] - plt.xlim()[0])

text_positions = get_text_positions(text, eucs, covers, txt_width, txt_height)

text_plotter(text, eucs, covers, text_positions, txt_width, txt_height)

plt.show()

This is what the output should look like:

This is what I get:

How do I get it to work?


text:
Q: Find and replace digits not in brackets in Notepad++ I have a Latex document that looks like
Hello, my figure \ref{figure1} has an ecuation $e=mc^2$ with a mass of 10.5Kg or 20.5 Kg.

I want to use the siunitx package, so my goal is to convert the text to
Hello, my figure \ref{figure1} has an ecuation $e=mc^2$ with a mass of \SI{10.5}{Kg} or \SI{20.5}{Kg}.

How can I find any digits with or without decimal places, followed by a word with or without an empty space between them.  Find only those that are not between {} or $$. Replace the match with \SI{digit found}{word after digit}
Any suggestions would be helpfull. Ideally using notepad++ but open to use Python, Sed...

A: How about:
Find what: (?<!\{)(?<!\$)\b(\d+(?:\.\d+)?)(?!=\})(?!=\$)\s*([a-zA-Z]+)
Replace with: \\SI{$1}{$2}


text:
Q: Matrix elements combination There is a m x n array, I need to output each possible combination Of each line's element. For example, for array{{1,2,3},{4,5,6}}, I need to output{{1,4},{1,5},{1,6},{2,4},{2,5},{2,6},{3,4},{3,5},{3,6}}.

I think there should be a m loop to solve this. For the example above, I wrote the code:
        int[,] array = new int[,] {{1, 2, 3}, {4, 5, 6}};

        for (var i = 0; i < 3; i++)
        {
            for (var j = 0; j < 3; j++)
            {
                Console.WriteLine($"{{{array[0, i]},{array[1, j]}}}");
            }
        }

With m changes, the number of for loop also changes. But m is unknown when I write the code. How can I solve it?

A: Maintain a list of active combinations c. Initialize c to be the array's first row. Then iterate every additional row and update c. Basically, you augment each of the current combinations with each of the row's items. Here is some pseudo code:
c = array[0]; //read: the first row of the array
for(var i = 1; i < m; ++i) { //iterate all rows
    var c_modified = [];
    for(var j = 0; j < n; ++j) { //iterate all row entries
        for(var k = 0; k < c.length; ++k) { //iterate all entries of c
            add c[k].array[i, j] to c_modified; // . represents concatenation
        }
    }
    c = c_modified;
}

A: This combination of elements (n^m sets) is called Cartesian product. There are ready-to-use functions for its generation in some language libraries
I believe that the simplest code is recursive one.
type
  TArr2D = TArray<TArray<Integer>>;

procedure CartesianProduct(const A: TArr2D; Line: Integer; Reslt: TArray<Integer>);
var
  i: integer;
begin
  if Line > High(A) then
    Memo1.Lines.Add(ArrayToString(Reslt)) // output m-element set
  else
    for i in A[Line] do
       CartesianProduct(A, Line + 1, Reslt + [i]);  // include element in set
end;

var
  A: TArr2D;
  n, m, i, j: Integer;
begin
  m := 3;
  n := 3;
  SetLength(A, m, n);
  for j := 0 to m - 1 do
    for i := 0 to n - 1 do
       A[j, i] := j * n + i;
    //0 1 2
    //3 4 5
    //6 7 8

  CartesianProduct(A, 0, []);

gives
0 3 6
0 3 7
0 3 8
0 4 6
0 4 7
0 4 8
0 5 6
0 5 7
0 5 8
1 3 6
1 3 7
1 3 8
1 4 6
1 4 7
1 4 8
1 5 6
1 5 7
1 5 8
2 3 6
2 3 7
2 3 8
2 4 6
2 4 7
2 4 8
2 5 6
2 5 7
2 5 8


text:
Q: Removing edges from a forest in Tikz I have the following forest in my Latex using Tikz:
\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage{forest}
\usetikzlibrary{trees} % this is to allow the fork right path

\begin{figure}[H]
    \centering
    \scalebox{1.0}{
        \begin{forest}
            for tree={
            line width=0.5pt,
            draw=black,
            fit=rectangle,
            if level=0{%
                    l sep+=1cm,
                    edge from parent fork down,
                    for descendants={%
                            calign=first,
                        },
                    align=center,
                    parent anchor=south,
                }{%
                    if level=1{%
                            parent anchor=south west,
                            child anchor=north,
                            tier=three ways,
                            align=center,
                            for descendants={%
                                    child anchor=west,
                                    parent anchor=west,
                                    align=left,
                                    anchor=west,
                                    xshift=-20pt,
                                    edge path={
                                            \noexpand\path[\forestoption{edge}]
                                            (!to tier=three ways.parent anchor) |-
                                            (.child anchor)\forestoption{edge label};
                                        },
                                },
                        }{}%
                },
            }
            [Optimal Transport Application\\to Machine Learning
            [Optimal Transport \\ Usage Type
            [Optimal Transport\\Cost as Metric
            [Optimal Transport\\Mapping]]
            ]
            [Optimal Tranport\\Problem formulation
            [Wasserstein
            [Entropic Wasserstein
            [Sliced-Wasserstein
            [Gromov-Wasserstein
            [Other]]]]]
            ]
            ]
        \end{forest}}

What I'd like to do is to remove (or color white) the two edges coming down from "Optimal Transport Application to Machine Learning". How do I do this?

A: To get no edge, use no edge.
\documentclass{article}
\usepackage{forest}
\begin{document}
\begin{figure}[h]
 \centering
  \begin{forest}
      for tree={
      line width=0.5pt,
      draw=black,
      fit=rectangle,
      if level=0{%
              l sep+=1cm,
              for descendants={%
                      calign=first,
                  },
              align=center,
              parent anchor=south,
          }{%
              if level=1{%
                      no edge,% <- added
                      parent anchor=south west,
                      child anchor=north,
                      tier=three ways,
                      align=center,
                      for descendants={%
                              child anchor=west,
                              parent anchor=west,
                              align=left,
                              anchor=west,
                              xshift=-20pt,
                              edge path={
                                      \noexpand\path[\forestoption{edge}]
                                      (!to tier=three ways.parent anchor) |-
                                      (.child anchor)\forestoption{edge label};
                                  },
                          },
                  }{}%
          },
      }
      [Optimal Transport Application\\to Machine Learning
       [Optimal Transport \\ Usage Type
        [Optimal Transport\\Cost as Metric
         [Optimal Transport\\Mapping]]
       ]
       [Optimal Tranport\\Problem formulation
        [Wasserstein
         [Entropic Wasserstein
          [Sliced-Wasserstein
         [Gromov-Wasserstein
        [Other]]]]]
       ]
      ]
  \end{forest}
\end{figure}
\end{document}


text:
Q: Putting ControlWrapper into a js function I have a bunch of controlwrappers for my google visualization dashboard in the form of
var compositeScorePicker = new google.visualization.ControlWrapper({
   'controlType': 'CategoryFilter',
   'containerId': 'compositeScorecontrol',
   'options': {
       'filterColumnLabel': 'compositeScore',
       'ui': {
          'allowTyping': false,
          'allowMultiple': false
             }
          }
        });

How can I create a function that does this where I enter in "compositeScore" and output this variable?  Thanks

A: I think you mean something like this:
  function getWrapper(name) {
    result = new google.visualization.ControlWrapper({
      'controlType': 'CategoryFilter',
      'containerId': name + 'control',
      'options': {
        'filterColumnLabel': name,
        'ui': {
          'allowTyping': false,
          'allowMultiple': false
        }
      }
    });
    return result;
  }
  var compositeScorePicker = getWrapper('compositeScore');

This will just change the containerId to be the name you pass in with "control" concatenated at the end, and will set the filterColumnLabel to the name you pass in.


text:
Q: On horizontal scroll for a table, how can I have sticky th until reach the next th? I have a table with a horizontal scrollbar. I need to make the data of the first two rows sticky when horizontally scroll the table.
This is the table at the first place:

When I scroll I want "2016" and "Dec" to be displayed until I reach "2017" and "Jan", and the same for 2017 and Jan until I reach the next date.
This is the picture while scrolling:

and the picture when I reach the next date:

Please note that I don't want numbers to be sticky.
I already used scrollToFixed library for vertical scroll, but i'm not sure if it works in my situation.
Any hints will be appreciated.

A: You can do it using only css with position: sticky.
Note:

*

*Putting .sticky on both th and the text to have the effect like this:

*If you don't want the text to be cut, just remove class sticky on th.

.sticky {
  position: sticky;
  left: 0;
}
.table-wrapper {
  max-width: 200px;
  overflow-x: auto;
}
td {
  min-width: 40px;
}
th {
  padding: 0 5px;
  background-color: white;
  text-align: left;
}

          2016

           2017

          Dec

          Jan

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10


text:
Q: ForEach Enumerator has failed with error 0x80131509 "(null)" SSIS ForEachLoop Error
I am trying to load multiple excel files with multiple sheets but after deploy into server only i am getting this error.
The GetEnumerator method of the ForEach Enumerator has failed with error 0x80131509 "(null)". This occurs when the ForEach Enumerator cannot enumerate.
i also changed in the properties Run64BitRuntime = false. anyone can suggest me what to do for this error?
FOReach loop container

A: This error gets thrown when trying to enumerate NULL.
It looks like, once deployed, your SSIS package is not finding any excel files, and returning NULL, instead of an empty list.
Sources;

*

*Foreach loop container in SSIS using variable

*ssis error : foreach in foreach loop container
I'd suggest to put some logging in your package Before the enumeration to see if anything is found, then redeploy it, run and check your logs.


text:
Q: Visual Studio Code: Disable quote wrapping text selection When I want to change from double quotes to single quotes, I'm used to selecting the double quote, and then type a single quote. I'm intending to use the overwrite feature, but instead, I'm getting the 'wrap with quote' feature.
For example:
"id"

Would result in:
'"'id"

I always turn this auto surround with wrapping off, but I was unable to find a setting for this in the settings file...
Is there a way to turn this off?

A: It is possible!
In settings.json which you can open via File>Preferences>UserSettings
UPDATE 2023
There are two settings
"editor.autoSurround": "never",

Possible values:

*

*"never"

*"languageDefined" - This is vsCode's default

*"brackets" - meaning it automatically adds brackets, but not quotes

*"quotes" - meaning it automatically adds quotes but not brackets

"editor.autoClosingQuotes": "never",

Possible values:

*

*"never"

*"languageDefined" - This is vsCode's default

*"beforeWhitespace"

*"always"

PS: In old ancient versions of vsCode, there was less granularity and a single setting would control quotes, braces and brackets. "editor.autoClosingBrackets" : "never"

A: I found this question via Google and the selected answer didn't work for me. I'm using VSCode version 1.27.2, and for me the I had to disable the Auto Surround option.
"editor.autoSurround": "never"

A: Using VSCode version: 1.36.0
You can use: "editor.autoClosingQuotes": "never"
or


text:
Q: Median and Boxplot (R) I am writing to your forum because I do not find solution for my problem. I am trying to represent graphically the Median catching time (MCT) of mosquito that we (my team and I) have collected (I am currently in an internship to study the malaria in Ivory Coast). The MCT represents the time for which 50% of the total malaria vectors were caught on humans.
For example, we collected this sample:
Hour of collection / Mosquitoes number:
20H-21H = 1
21H-22H = 1
22H-23H = 2
23H-00H = 2
00H-01H = 13
01H-02H = 10
02H-03H = 15
03H-04H = 15
04H-05H = 8
05H-06H = 10
06H-07H = 6

Here the effective cumulated is 83 mosquitoes. And I am assuming that the median of this mosquito serie is 83+1/2 = 42 (And I don't even find this number on R), inducing a Median catching time at 2 am (02).
Therefore, I have tried to use the function "boxplot" with different parameters, but I cannot have what I want to represent. Indeed, I have boxes for each hour of collection when I want the representation of the effective cumulated over the time of collection. And the time use in R is "20H-21H" = 20, "21H-22H" = 21 etc.
I have found an article (Nicolas Moiroux, 2012) who presents the Median Catching Time and a boxplot that I should like to have. I copy the image of the cited boxplot:
Boxplot_Moiroux2012
Thank you in advance for your help, and I hope that my grammar is fine (I speak and write mainly in French, my mother tongue).
Kind Regards,
Edouard
PS : And regarding the code I have used with this set of data, here I am (with  "Eff" = Number of mosquito and "Heure" = time of collection):
sum(Eff)
as.factor(Heure)
tapply(Eff,Heure,median)
tapply(Heure,Eff,median)
boxplot(Eff,horizontal=T)
boxplot(Heure~Eff)
boxplot(Eff~Heur))
(My skills on R are not very sharp...)

A: You need to use a trick since you already have counts and not the time data for each catch.
First, you convert your time values to a more continuous variable, then you generate a vector with all the time values and then you boxplot (with a custom axis).
txt <- "20H-21H = 1
21H-22H = 1
22H-23H = 2
23H-00H = 2
00H-01H = 13
01H-02H = 10
02H-03H = 15
03H-04H = 15
04H-05H = 8
05H-06H = 10
06H-07H = 6"

dat <- read.table(text = txt, sep = "=",  h = F)
colnames(dat) <- c("collect_time", "nb_mosquito")

# make a continuous numerical proxy for time
dat$collect_time_num <- 1:nrow(dat)

# get values of proxy according to your data
tvals <- rep(dat$collect_time_num, dat$nb_mosquito)

# plot
boxplot(tvals, horizontal = T, xaxt = "n")
axis(1, labels = as.character(dat$collect_time), at = dat$collect_time_num)

outputs the following plot :


text:
Q: DataGridViewComboBoxColumn do not update directly I have one DataGridViewComboBoxColumn in FormA, and I have a button that opens another FormB which enable user from adding a new item. When the user add a new item, it will not appear until you reopen formA, I want the added item to appear directly, how can I do this? thank you in advance. Following is my code:
Following is the code in FormB:
   DataGridViewComboBoxColumn itemCmbClmn = new DataGridViewComboBoxColumn();

            itemCmbClmn.ValueMember = itemID.ToString();
            itemCmbClmn.DisplayMember = txtItemAr.Text;

            BindingSource bs = new BindingSource();
            DataTable itemDataTable = prcFrm.ItemData;
            bs.DataSource = itemDataTable;
            itemCmbClmn.DataSource = bs;

The added item will appear but you need to reopen the form, any help please?


text:
Q: Nginx: Restrict access by IP with exception on some routes I would like to know if it's possible to restrict by IP some ressources:
I want to allow a root pattern to everybody , and I want to restrict all roots to some IP and subnet.
In my nginx conf, I put this:
#1 allow pdf files access to all
location ~* /\.pdf$ {
  allow all;
}

#2 restrict to these networks
  allow <ip1>;
  allow <network1>/22;
  allow <network2>/23;

#3 deny all other network
  deny  all;

When I'm trying to connect from ips different of block #2, I get an access denied.
How could I do to access pdf files from different IP of block #2 ?

A: Your approach is fine, but the regular expression is wrong. You are currently matching URIs which end with /.pdf, but you probably mean to match URIs that end with .pdf.
Try:
location ~* \.pdf$ {
    allow all;
}


text:
Q: Error Python not enough values to unpack (expected 3, got 2) Tengo este codigo:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import FuncionesFiltros as fun

Im = Image.open('build.jpg')
Im_a = np.array(Im)
plt.figure()
plt.imshow(Im_a)
plt.title('IMAGEN ORIGINAL')
plt.axis("off")

Im_cmy = fun.my_cmy2rgb(Im_a)
plt.figure()
plt.imshow(Im_cmy)
plt.title('IMAGEN RGB A CMY')
plt.axis("off")

Im_rgb = fun.my_rgb2cmy(Im_cmy)
plt.figure()
plt.imshow(Im_rgb)
plt.title('IMAGEN CMY A RGB')
plt.axis("off")

Im_hsi = fun.RGB_TO_HSI(Im_rgb)
plt.figure()
plt.imshow(Im_hsi)
plt.title('IMAGEN RGB A HSI')
plt.axis("off")

-Esta es la funcion:
def RGB_TO_HSI(R,G,B):
    if(0<=R<=255 and 0<=G<=255 and 0<=B<=255):

        d = R+G+B
        r = float(R)/d
        g = float(G)/d
        b = float(B)/d
        numerador = float( 0.5 * ((r - g) + (r - b)))
        denominador = float(((r - g)**(2) + (r - b)*(g - b))**(0.5))

    if(b <= g):
        h = math.acos(numerador/denominador)

    if(b > g):

        h = (2*math.pi) -  math.acos(numerador/denominador )
        s = 1 - (3 * min(r,g,b))
        i = float(R+G+B)/float(3*255)
        rturn h,s,i

Cuando lo compilo me aparece un error:
ValueError: not enough values to unpack (expected 3, got 2)

Por lo que entiendo es que se esperan 3 valores y apenas obtiene 2, pero no se en que parte estoy fallando. Si alguien me podria indicar el error lo agradeceria.
Gracias


text:
Q: Assert issue in selenium Java I am trying to assert the other language text .While asserting i am getting a error message
Expected: a string containing "Fornavn er et felt som mÃ¥ fylles ut." but: was "Fornavn er et felt som må fylles ut."

Below is the Code i am using in the framework
default void assertElementContainsText(WebElementFacade element, String text) {
        try {
            Assert.assertThat(element.waitUntilVisible().waitUntilClickable().getText(), CoreMatchers.containsString(text));
        } catch (NoSuchElementException e) {
            throw new NoSuchElementException("Could not find element " + element);
        }
    }

Its working fine for the English language when its comparing with other language getting the issue as
Expected: a string containing "Fornavn er et felt som må fylles ut."
     but: was "Fornavn er et felt som må fylles ut."


text:
Q: Ruby Oneline Rescue I recently learned that you can use rescue on a line of code in case something goes wrong on that line (see http://www.rubyinside.com/21-ruby-tricks-902.html Tip #21). I have some code that used to look like this:
if obj['key'] && obj['key']['key2'] && obj['key']['key2']['name']
  name = obj['key']['key2']['name']
else
  name = ''
end

With the rescue method, I believe I can change that code into something like this:
name = obj['key']['key2']['name'] rescue ''

If a nil exception is thrown at any level of accessing the hash, it should get caught by the rescue and give me '', which is what I want. I could also choose to set name to nil if that were the desired behavior.
Is there any known danger in doing this? I ask because this seems too good to be true. I have so much ugly code that I'd love to get rid of that looks like the first code example.

A: Reads good! But it will hit your performance. In my experience rescue is much slower when triggered and slightly slower when it's not. In all cases the if is faster. Other thing to consider, is that exceptions shouldn't be expected and you kind of are with this code. Having a hash so deeply nested might be a good smell that a refactoring is nede

A: This specific example can now be achieved with Ruby 2.3's dig method.
name = obj.dig 'key', 'key2', 'name'

This will safely access obj['key']['key2']['name'],  returning nil if any step fails.
(In general, it's usually advised to use exceptions only for real, unanticipated, errors, though it's understandable in an example like this if the syntax makes it cumbersome.)


text:
Q: how does the short(vector.size()) command conversion work in C++? I don't know any other way to return the size of a vector other than the .size() command, and it works very well, but, it return a variable of type long long unsigned int, and this in very cases are very good, but I'm sure my program will never have a vector so big that it need all that size of return, short int is more than enough.
I know, for today's computers those few enused bytes are irrelevant, but I don't like to leave these "loose ends" even if they are small, and whem I was programming, I came across some details that bothered me.
Look at these examples:
for(short int X = 0 ; X < Vector.size() ; X++){

}

compiling this, I receive this warning:
warning: comparison of integer expressions of different signedness: 'short int' and 'std::vector<unsigned char>::size_type' {aka 'long long unsigned int'} [-Wsign-compare]|
this is because the .size() return value type is different from the short int I'm compiling, "X" is a short int, and Vector.size() return a long long unsigned int, was expected, so if I do this:
for(size_t X = 0 ; X < Vector.size() ; X++){

}

the problem is gone, but by doing this, I'm creating a long long unsigned int in variable size_t and I'm returning another variable long long unsigned int, so, my computer allocale two variables long long unsigned int, so, what I do for returning a simple short int? I don't need anything more than this, long long unsigned int is overkill, so I did this:
for(short int X = 0 ; X < short(Vector.size()) ; X++){

}

but... how is this working? short int X = 0 is allocating a short int, nothing new, but what about short (Vector.size()), is the computer allocating a long unsigned int and converting it to a short int? or is the compiler "changing" the return of the .size() function by making it naturally return a short int and, in this case, not allocating a long long unsined int? because I know the compilers are responsible for optimizing the code too, is there any "problem" or "detail" when using this method? since I rarely see anyone using this, what exactly is this short() doing in memory allocation? where can i read more about it?
(thanks to everyone who responded)

A: In all cases, X has a storage duration of automatic, and the result of Vector.size() does not outlive the full expression where it is created.

I don't need anything more than this, long long unsigned int is overkill

Typically, automatic duration variables are "allocated" either on the stack, or as registers. In either case, there is no performance benefit to decreasing the allocation size, and there can be a performance penalty in narrowing and then widening values.
In the very common case where you are using X solely to index into Vector, you should strongly consider using a different kind of for:
for (auto & value : Vector) {
    // replace Vector[X] with value in your loop body
}

A: Forget for a moment that this involves a for loop; that's important for the underlying code, but it's a distraction from what's going on with the conversion.
short X = Vector.size();

That line calls Vector.size(), which returns a value of type std::size_t. std::size_t is an unsigned type, large enough to hold the size of any object. So it could be unsigned long, or it could be unsigned long long. In any event, it's definitely not short. So the compiler has to convert that value to short, and that's what it does.
Most compilers these days don't trust you to understand what this actually does, so they warn you. (Yes, I'm rather opinionated about compilers that nag; that doesn't change the analysis here). So if you want to see that warning (i.e., you don't turn it off), you'll see it. If you want to write code that doesn't generate that warning, then you have to change the code to say "yes, I know, and I really mean it". You do that with a cast:
short X = short(Vector.size());

The cast tells the compiler to call Vector.size() and convert the resulting value to short. The code then assigns the result of that conversion to X. So, more briefly, in this case it tells the compiler that you want it to do exactly what it would have done without the cast. The difference is that because you wrote a cast, the compiler won't warn you that you might not know what you're doing.
Some folks prefer to write that cast is with a static_cast:
short X = static_cast<short>(Vector.size());

That does the same thing: it tells the compiler to do the conversion to short and, again, the compiler won't warn you that you did it.
In the original for loop, a different conversion occurs:
X < Vector.size()

That bit of code calls Vector.size(), which still returns an unsigned type. In order to compare that value with X, the two sides of the < have to have the same type, and the rules for this kind of expression require that X gets promoted to std::size_t, i.e., that the value of X gets treated as an unsigned type. That's okay as long as the value isn't negative. If it's negative, the conversion to the unsigned type is okay, but it will produce results that probably aren't what was intended. Since we know that X is not negative here, the code works perfectly well.
But we're still in the territory of compiler nags: since X is signed, the compiler warns you that promoting it to an unsigned type might do something that you don't expect. Again, you know that that won't happen, but the compiler doesn't trust you. So you have to insist that you know what you're doing, and again, you do that with a cast:
X < short(Vector.size())

Just like before, that cast converts the result of calling Vector.size() to short. Now both sides of the < are the same type, so the < operation doesn't require a conversion from a signed to an unsigned type, so the compiler has nothing to complain about. There is still a conversion, because the rules say that values of type short get promoted to int in this expression, but don't worry about that for now.
Another possibility is to use an unsigned type for that loop index:
for (unsigned short X = 0; X < Vector.size(); ++X)

But the compiler might still insist on warning you that not all values of type std::size_t can fit in an unsigned short. So, again, you might need a cast. Or change the type of the index to match what the compiler think you need:
for (std::size_t X = 0; X < Vector.size(); ++X_

If I were to go this route, I would use unsigned int and if the compiler insisted on telling me that I don't know what I'm doing I'd yell at the compiler (which usually isn't helpful) and then I'd turn off that warning. There's really no point in using short here, because the loop index will always be converted to int (or unsigned int) wherever it's used. It will probably be in a register, so there is no space actually saved by storing it as a short.
Even better, as recommended in other answers, is to use a range-base for loop, which avoids managing that index:
for (auto& value: Vector) ...


text:
Q: Updating information in SQL via C# Visual Studio does not work I have created a program (for school) that has create account, manage account (update and delete), and delete account. All functions work except for Update and I am not sure why. There's no error whatsoever, it just does nothing. Below is the code:
    private void btnUpdate_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString);
        con.Open();
        using (SqlCommand cmd = new SqlCommand("UPDATE Inventory SET ItemID=@ItemID, ItemName=@ItemName, ItemType=@ItemType, Quantity=@Quantity,WarehouseLocation=@WarehouseLocation,QuadrantNumber=@QuadrantNumber,BinNumber=@BinNumber,DateUpdated=@DateUpdated" +
                " WHERE ItemID= '" + txtItemID.Text + "'", con))
        {
            if (txtItemID.Text == "@ItemID")
            {
                cmd.Parameters.AddWithValue("@ItemName", txtItemName.Text);
                cmd.Parameters.AddWithValue("@ItemType", cmbType.Text);
                cmd.Parameters.AddWithValue("@Quantity", udQuantity.Text);
                cmd.Parameters.AddWithValue("@WarehouseLocation", cmbWarehouse.Text);
                cmd.Parameters.AddWithValue("@QuadrantNumber", cmbQuadrant.Text);
                cmd.Parameters.AddWithValue("@BinNumber", cmbBin.Text);
                cmd.Parameters.AddWithValue("@DateUpdated", Convert.ToString(DateTime.Now));
                cmd.ExecuteNonQuery();
                con.Close();

                MessageBox.Show("Item Updated!");
            }
        }
    }

A: This answer is based in assumption you already have this item in your DB and you just need to update it. I'll separate the answer in three steps:
First step: I assume your primary_key is the ItemID, so you shouldn't really update it as you're doing here:

UPDATE Inventory SET ItemID=@ItemID,...

You should just remove the ItemID = @ItemID, part, as we don't want to update it.
Second step: Now, this piece of code looks incorrect:
if (txtItemID.Text == "@ItemID")

It will try to match the txtItemID.Text with the string "@ItemID", which I believe it is not your goal, since I can understand it is your ID - It would be always false.
You should just remove this if.
Third step: You also need to change your where clause to have your ItemID as parameter, as below:
" WHERE ItemID=@ItemID", con))

Then add it to your parameters:
cmd.Parameters.AddWithValue("@ItemID", txtItemID.Text);

You should be good with these changes.
Another thing you could do is to always debug your application when you're struggling to understand a problem. It helps a lot!


text:
Q: Can't input new line in multiline edittext box(enter button will change focus to next input field) I have an EditText field with following java code:
EditText edittxt=new EditText(cntxt);
edittxt.setInputType(EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
edittxt.setMinLines(minLines);
edittxt.setGravity(Gravity.TOP);
edittxt.setVerticalScrollBarEnabled(true);

But it will change focus to next EditText field when I type "enter" button on soft keyboard. So the problem is user can't input new lines in this multiline text box.
Anyone know this issue?  I've searched on google. Most of those solutions are how to disable "enter" button.

A: Did you try setting the IME option setImeOptions(int) and set it IME_NULL


text:
Q: Implements wild card dns on laravel After hours of research for the right keyword to implement a simple way of using wild card dns on laravel.
Here I'm using windows 10 and laragon.
This is the code I tried to implement in laravel route
Route::group(['domain' => '{account}.tindahan.local'], function() {
  Route::get('/page-one', function () {
    return view('welcome0');
  });
  Route::get('/page-two', function () {
    return view('welcome1');
  });
});

Base on the articles I read which you need to setup something like *.domian.com on vhost I have this automatically set in laragon
<VirtualHost *:80>
    DocumentRoot "C:/laragon/www/tindahan/public/"
    ServerName tindahan.local
    ServerAlias *.tindahan.local
    <Directory "C:/laragon/www/tindahan/public/">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

But when I tried to visit page-one.tindahan.local on Chrome browser I got this message

This site can't be reached

I don't know what's missing of what I am doing. This is the first time I am doing something like this, so basically I don't have lots of idea.
Can you give me the right way to implement this?

A: For sure you should add entries to your hosts file (On windows usually C:\Windows\System32\drivers\etc\hosts). For example you should have:
127.0.0.1 tindahan.local

for main domain, but you should also add other subdomains for example:
127.0.0.1 page-one.tindahan.local
127.0.0.1 page-two.tindahan.local

and so on


text:
Q: Use additional request param to generate a model field in DRF 3 I am new to Djnago Rest Framework 3 and not able to understand how to achieve this:
I have following model:
class Interface(models.Model):
    name = models.CharField(max_length=25)
    current_location = models.CharField(max_length=25, blank=True)

And in request param, I am expecting latitude, longitude field which will generate the geohash from latitude, longitude and store in current_location.
I tried using following serializer and ViewSet, but it is giving error

'Interface' object has no attribute 'latitude'.

class InterfaceSerializer(serializers.ModelSerializer):
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()
    class Meta:
        model = Interface
        fields = ('id', 'name', 'latitude', 'longitude',)
        read_only_fields = ('id',)

class InterfaceViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows interface to be viewed or edited.
"""
    queryset = Interface.objects.all()
    serializer_class = InterfaceSerializer

Even using the serializers.Serializer instead of serializers.ModelSerializer gives same error.
What is wrong here ? How to structure the serializer for given model and requirement ?

A: How do you think serializer will know about purpose of latitute and longitute fields?
You should override create method and set you current_location manually
class InterfaceSerializer(serializers.ModelSerializer):
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()

    class Meta:
        model = Interface
        fields = ('id', 'name', 'latitude', 'longitude',)

    def create(self, validated_data):
        latitute = validated_data.get('latitude')
        longitude = validated_data.get('longitude')
        name = validated_data.get('name')
        # suppose you want to store it charfield comma separated
        current_location = str(latitute) + ',' + str(longtitute)
        return Interface.objects.create(
                         current_location=current_location,
                         name=name
                         )

There is also useful package django-geoposition it provides field and widget for geoposition.