text:
Q: auto show preview from text box I'm making a post page for my website, and I would like to add an auto update preview box, showing what is being typed into the text box above. Obviously i'd like to use javascript, or jquery. And the thing I need is basically the same thing as on the ask page for this website!

A: Are you looking for .keyup()?
Look at this fiddle for a simple example: http://jsfiddle.net/LUDWQ/2/
$('#tb1').keyup(function() {
    $('#tb2').val($('#tb1').val());
});

When putting in into a div and not another textbox you can use this:
$('#tb1').keyup(function() {
    $('#tb2').html($('#tb1').val()); //tb2 is a <div> here
});

Fiddle: http://jsfiddle.net/LUDWQ/4/

A: If the textarea control has an id of "textarea_control" and the preview div/span/whatever has an id of "preview", you could potentially use something like this (snagged from some code I used in a project and tweaked for your example).
//Wait for input in textarea
$("#textarea_control").keyup(function() {
  var inputB = $(this).val();
  if(globalTimeout != null){
    clearTimeout(globalTimeout);
  }
  //Give the user a slight time to delay while typing
  globalTimeout = setTimeout(function(){
    $("#preview").html(inputB);
  }, 1000);

Hope this helps!
Please note, this does not do any filtering of user's input, so you should probably think about calling a separate function to filter the data to prevent injection or other attacks before displaying the preview.

redpajama_set_name: RedPajamaStackExchange


text:
Q: merge paint results in thread bitmap painting I want to speed up painting a bitmap, therefore I designed a class like BITMAP THREAD CLASS. Once the individual painting of a partial image is finished I want to merge all image in the Thread.done procedure
My code goes like this
    type
      TbmpthreadForm = class(TForm)
        .....
        THreadImage: TImage;
        procedure Button_threadstartClick(Sender: TObject);
        procedure FormCreate(Sender: TObject);
        procedure FormClose(Sender: TObject; var Action: TCloseAction);
      private
        { Private-Deklarationen }
        procedure ThreadDone(Sender: TObject);
      public
        { Public-Deklarationen }
        fserver, fdatabasename, ftablename: String;
        global_thread_counter: Integer;
        XPixel, YPixel: Integer;
        Masterbitmap: TBitmap;
      end;

    var
      bmpthreadForm: TbmpthreadForm;

    implementation

    {$R *.dfm}

    procedure TbmpthreadForm.ThreadDone(Sender: TObject);
    begin
      dec(global_thread_counter);
      MyStatusBar.SimpleText := 'Thread Count ->' + IntToStr(global_thread_counter);

      Masterbitmap.Canvas.Lock;
      with (Sender as TPaintBitmapThread) do
      begin
        bitblt(Masterbitmap.Canvas.handle, 0, 0, XPixel, YPixel,
          bitmap.Canvas.handle, 0, 0, srcand);
        THreadImage.Picture.Bitmap.Assign(Masterbitmap);
        // lets see local tthread intermediate results  and save it to HD
        THreadImage.Picture.Bitmap.SaveToFile('c:\temp\myimage' + IntToStr(Index)
  + '.bmp');
      end;
      Masterbitmap.Canvas.UnLock;

      if (global_thread_counter = 0) then
      begin
         ...
      end;
    end;
procedure TbmpthreadForm.Button_threadstartClick(Sender: TObject);
var
     .....
begin

  index_max := 2000000;
  threadCounter := 10;
  Indexdelta := round(index_max / threadCounter);

  ///
  ///
  ....
  Masterbitmap.Width := XPixel;
  Masterbitmap.Height := YPixel;

  for i := 0 to threadCounter - 1 do
  begin
    n := i * Indexdelta;
    m := (i + 1) * Indexdelta;
    //  just a test sql string ....
    sqlstr := 'select * from  Mytable  where objectindex <' + IntToStr(m) +
      ' and Objectindex >' + IntToStr(n);

    aPaintBitmapThread := TPaintBitmapThread.Create(XPixel, YPixel, ......   , fserver, fdatabasename, ftablename,
      sqlstr, i);
    aPaintBitmapThread.OnTerminate := ThreadDone;
    Memo1.Lines.Add('start thread->' + IntToStr(i));
    inc(global_thread_counter);
  end;

end;

The Thread.done design follows a previous topic here on SO ( reference question
As the resulting image/Masterbitmap looks a bit different from run to run , I guess my approach is not thread safe design for copy Thread bmp content into the masterbitmap in the VCL mainform,
I can not see any error in my code, what is wrong ????
additional question
Q1 :  fbitmap inside TPaintBitmapThread is created inside the Thread.create procedure, for TAdoconnection I found the comment, it should be created inside the thread.execute. Must this also be done the the bitmap ?
Q2 : the attached image shows the expected result of an image(Bitmap) by an Thread and the actual image results (as seen by  the THreadImage.Picture.Bitmap.SaveToFile command)

A:     bitblt(Masterbitmap.Canvas.handle, 0, 0, XPixel, YPixel,
      bitmap.Canvas.handle, 0, 0, srcand);

you explicitly called Masterbitmap.Canvas.Lock, however you didn't call bitmap.Canvas.Lock (so you can loose the canvas handle anytime within this call...)
Additionally, you need to consider thread safety within GDI itself: Sharing of any GDI objects between different threads should be avoided at all cost. For example if you select a bitmap into two different device contexts at the same time (but in different threads) you may run into problems within GDI itself...
Please note that older versions of delphi don't protect against sharing of cached handles (Font, Brush and Pen handles are cached within a global list. This was fixed in an XE3 service pack if I remember correctly).
In short: I'd consider to avoid TCanvas and TBitmap completely if you really need multi-threading. (It's much easier to be multi-threading safe that way)


text:
Q: If $f(x)^2>f(x+dx)f(x-dx)$, then $f(x+dx)f(x-dx)>f(x+adx)f(x-adx)$
Supose that $f(x)$ is continuous and monotonic. Assume that, for all $x$, small $dx$ and $a>1$, $f(x)^2>f(x+dx)f(x-dx)$.
Show that $f(x+dx)f(x-dx)>f(x+adx)f(x-adx)$.

*

*I have tried multiple examples in Mathematica and I believe that the proposition is true. If it is true, I'd be grateful to see a proof. If it is not true, I'd be grateful to see a counter example.

*This is related to a question I posted yesterday (Show that $erfc[\frac{x}{\sqrt{2}}]erfc[\frac{y-c}{b\sqrt{2}}]<erfc[\frac{x-c}{b\sqrt{2}}]erfc[\frac{y}{\sqrt{2}}]$) and for which I have not figured out the solution yet. If the proposition in this post is true, then the proposition in the other post should follow. In this case, I will update the old post to provide the final answer (I post this question in a new post because it is very different from the initial one).

Any solution/idea will be highly appreciated!
Thank you in advance.

A: The statement is not true,  a counter example:

$f(x)=erfc(x)+1$ (one can do a Taylor expansion to see that the initial condition holds for "small" $dx$), $x=1$, $dx=0.001$ and $a=100$. Then:
$f(x)^2=1.339341$
$f(x+dx)f(x-dx)=1.33934$
$f(x+adx)f(x-adx)=1.34722$


text:
Q: Create infinite loop This script is looping only once. I want to make it an infinite loop.
open( FILE, "<$ARGV[0]" );

if ( $LOOP == 1) {

    while ( <FILE> ) {

        if ( $. == $LOOP ) {
            next
        };
   }
}

while ( <FILE> ) {
    $LIST = $_;
    print "$LIST";
}

I want make it looping back to the first line, like this
abc
abcd
abcde
abc
abcd
abcde
...

A: Just wrap what you want to loop with while (1) { ... }.
Cleaned up, you get:
my $qfn = $ARGV[0];

while (1) {
   open(my $fh, '<', $qfn)
      or die("Can't open \"$qfn\": $!\n");

   while (<$fh>) {
      print;
   }
}

A very minor optimization is to avoid re-opening the file, seeking instead.
use Fcntl qw( SEEK_SET );

my $qfn = $ARGV[0];

open(my $fh, '<', $qfn)
   or die("Can't open \"$qfn\": $!\n");

while (1) {
   while (<$fh>) {
      print;
   }

   seek($fh, 0, SEEK_SET);
}

A: You can try something like this...
my ( $filename ) = @ARGV;

while ( 1 )
{
    open my $fh, '<', $filename or die $!;
    my @lines = <$fh>;
    close $fh;
    print @lines;
}

It should open the file, read it in, close it, print contents and then repeat.

A: Use seek to go reset the position in the filehandle. eof is true if the filehandle is on the last line.
open FILE,'<',$ARGV[0];
while (my $line = <FILE>) {
    print $line;
    if (eof) {
        seek FILE,0,0;
    }
}


text:
Q: Concatenate a variable in a string so as to form a URL I'm trying to consume an API which has to be specific for given users based on a variable: their cooker ID.
As such, below is the script I wrote in order to achieve that: I'm parsing the variable as ${cookieuid} in a string so as to form the URL;
getBellNotification() {
    let cookieuid = this.currentUser;
    let headers = new Headers();
    this.authorizeHeaders(headers);
    return this.http.get(
        this.config.apiUrl + 'api/supplier-notification/${cookieuid}?_format=json', {
            headers: headers
        }
    )
        .map(response => response.json())
        .catch(this.handleErrorObservable);
}

It is not working as expected as I get the result below, with undesired special characters:
http://<url>/api/supplier-notification/$%7Bcookieuid%7D?_format=json

What am I doing wrong and how can I achieve that?
I've tried other ways but still cannot get it working.

A: Try this
getBellNotification(){
        let cookieuid = this.currentUser;
        const url = `${this.config.apiUrl}/api/supplier-notification/${cookieuid}?_format=json`;
        let headers = new Headers();
        this.authorizeHeaders(headers);
        return this.http.get(url, { headers: headers })
        .map(response => response.json())
        .catch(this.handleErrorObservable);
    }


text:
Q: Cómo realizar formularios previos al pago en woocommerce? Quiero desarrollar una web donde al comprar un producto antes de ir al pago etc, quiero que rellenen unos formularios con una documentación. No se si esto se puede desarrollar con woocommerce o se debería de hacer algún tipo de php?
El ejemplo lo he tomado de esta pagina web: http://www.nienumberonline.com/apply-nie/?fid=0&pl=2
Gracias

A: Podrías incluir el formulario que necesitas dentro de la página del carrito de woocomerce. Sus plantillas se encuentran en woocommerce/templates/cart/. Aquí se suelen mostrar los productos que has añadido al carrito junto con sus precios, iva y el total del pedido, así como un botón para comenzar el proceso de pedido. Podrías poner el formulario en esta plantilla y que el comportamiento sea algo como que no te deje comenzar el proceso de pedido hasta que rellenes dicho formulario.

A: Inserta un formulario de Contact Form 7 en un producto de WooCommerce
este plugin
https://www.webempresa.com/blog/inserta-un-formulario-de-contact-form-7-en-un-producto-de-woocommerce.html


text:
Q: http:///ReportServer/ReportExecution2005.asmx unable to load the web service in browser http:///ReportServer/ReportExecution2005.asmx unable to load the web service in browser
I get HTTP 500 error on the Browser.
In ULS logs i get the below mentioned error:
Token Cache: Could not find SPSite for 'http://Server Name/_vti_bin/ReportServer/ReportExecution2005.asmx'. Stack: '
 at Microsoft.SharePoint.SPSite.LookupSiteInfo(SPFarm farm, Boolean contextSite, Boolean swapSchemeForPathBasedSites, Uri& requestUri, Boolean& lookupRequiredContext, Guid& applicationId, Guid& contentDatabaseId, Guid& siteId, Guid& siteSubscriptionId, SPUrlZone& zone, String& serverRelativeUrl, Boolean& hostHeaderIsSiteName, Boolean& appWebRequest, String& appHostHeaderRedirectDomain, String& appSiteDomainPrefix, String& subscriptionName, String& appSiteDomainId, Uri& primaryUri)
 at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, Boolean swapSchemeForPathBasedSites, SPUserToken userToken)
 at Microsoft.SharePoint.IdentityModel.SPTokenCache.GetSubscriptionIdFromContext(String context)'.
Unexpected error in ProcessRequest: System.Web.Services.Protocols.SoapException: The report server has encountered a configuration error.
 at Microsoft.ReportingServices.SharePoint.Common.RSProxyUtils.get_ReportServerUrlString()
 at Microsoft.ReportingServices.SharePoint.Soap.RSBaseHttpHandler.ProcessRequest(HttpContext context)


text:
Q: Elixir sourcemaps wrong file app.css[sm] bug With elixir, I compile my stylus files. But I have a problem with generating sourcemaps. In the chrome console, it gives me the right information for the basic files (eg, for reset css). But afterwards, it put me all styles in my app.css file generated.
Besides, he puts me [sm] next and I do not know what that means.
My gulpfile :
elixir(function (mix) {

mix.tinypng({
    key: '###',
    sigFile: '.tinypng-sigs',
    summarize: true,
});

mix.copy('resources/assets/img/*.*', 'public/img/');
mix.copy('resources/assets/svg-inline/*.*', 'public/svg/');
mix.copy('resources/assets/fonts/*.*', 'public/fonts/');

mix.stylus('app.styl'), {
    use: [autoprefixer('last 7 versions', 'ie8' )]
};

mix.scriptsIn();

mix.browserSync({
    proxy: 'ecoleinfographie.app'
});

})
Here is a picture of the problem :
[


text:
Q: Ngx-translate: How to access JSON array value directly in Angular with key reference I am doing POC on translating my app using ngx-translate. I will get JSON response from my API url. In that response, can some one help me how to access the JSON array value with out referring array numbers? My JSON response is given below.
{
    "Data": {
        "FirstData": [{
                "key": "FirstKey",
                "value": "FirstValue"
            },
            {
                "key": "SecondKey",
                "value": "SecondValue"
            }
        ]
    },
    "IsSuccessful": true,
    "HttpStatusCode": 200,
    "Exception": null
}

So, in my view to refer "FirstValue", I have to do something like ( which I dont want to)
<h1> {{'Data.FirstData.0.value' | translate }} </h1> <!--First Value -->

Here "0" is tightly coupled. Is there any other way by accessing via key?
Is that possible?

A: Change the response of your API to contain only the key/value pairs.
This is the desired JSON:
{
    "FirstKey": "FirstValue",
    "SecondKey": "SecondValue"
}

Then use it like that:
<h1> {{'FirstKey' | translate }} </h1>


text:
Q: Bases for spaces of solutions I have these spaces of solutions and im supposed to find an orthogonal basis for them. I can do this,if i have the regular basis for them. And i have no idea how to compute them:
a) $\begin{cases} 2x+y-z=0 \\ y+z=0\end{cases}$
For this the rank is obviously 2. Trying to solve the system I get:
\begin{cases} z=-y \\ 2x = -2y \end{cases}
But I'm not sure where to go from here.
b) $x-y+z = 0$
Rank is 1 obviously.
Solving the system gets me nowhere useful from what I can tell.
If the rank is 1, shouldn't a valid basis for the space be $[1;0;0]$?

A: In the first case, the single vector $(-1,1,-1)$ forms an orthogonal basis.
In the second case a basis is
$$
\left\{\,
\begin{bmatrix} 1 \\ 1 \\ 0 \end{bmatrix},
\begin{bmatrix} -1 \\ 0 \\ 1 \end{bmatrix}
\,\right\}
$$
and you can orthogonalize it with Gram-Schmidt.
Why is it a basis? The equation is $x=y-z$, so it has two free variables. You get a basis by giving them suitable values, typically $y=1$ and $z=0$ for the first vector and then $y=0$ and $z=1$ for the second vector. This ensures linear independence.

A: I will be writing all vectors as tuples rather than column vectors simply for ease.
In the first case, after row reduction you get
$1x+0y-1z=0$$0x+1y+1z=0$
The $1x$ in the first row and the $1y$ in the second row are pivots, and thus can be given in terms of non-pivots, in this case just $z$: $x=z$ and $y=-z$. This means $(x, y, z) = (z, -z, z)$. Factor out $ z$ and you get that all solutions are of the form $z*(1,-1,1)$. So $(1,-1,1)$ is a basis.
In the second case, since you only have one equation, it's already row reduced, and $y$ and $z$ are your two non-pivot variables. This means that you can take the two dimensional space that you get just varying $y$ and $z$, and any basis of that space will translate to a basis of the solution space. For instance, if you take $(y,z) = (1,0)$ and $(y,z)= (0,1)$, the first one gives you that $x = y-z = 1-0=1$, so the full vector is $(1,1,0)$. The second one gives you $x = -1$, or $(-1,0,1)$. This gives you the basis $\{(1,1,0), (-1,0,1)\}$.
So:
Row reduce, and then for each non-pivot variable, set it to one and the other non-pivots to zero, and solve for the pivot variables. This gives you a vector for each non-pivot variable, and the set of all such vectors is a basis.


text:
Q: pymongo: name 'ISODate' is not defined I have problem when i try to select data in mongodb with pymongo, this is my code :
import pymongo
from pymongo import MongoClient
import sys
from datetime import datetime

try:
    conn=pymongo.MongoClient('10.33.109.228',27017)
    db=conn.mnemosyne
    data_ip=db.session.aggregate({'$match':{'timestamp':{'$gte': ISODate('2016-11-11T00:00:00.000Z'),'$lte': ISODate('2016-11-11T23:59:59.000Z')}}},{'$group':{'_id':'$source_ip'}})
    for f in data_ip:
        print f['_id']

except pymongo.errors.ConnectionFailure, e:
    print "Could not connect to MongoDB: %s" % e

and when i execute it i have some error like this:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    data_ip=db.session.aggregate({'$match':{'timestamp':{'$gte': ISODate('2016-11-11T00:00:00.000Z'),'$lte': ISODate('2016-11-11T23:59:59.000Z')}}},{'$group':{'_id':'$source_ip'}})
NameError: name 'ISODate' is not defined

I want the result like this:
{ "_id" : "60.18.133.207" }
{ "_id" : "178.254.52.96" }
{ "_id" : "42.229.218.192" }
{ "_id" : "92.82.171.117" }
{ "_id" : "103.208.120.205" }
{ "_id" : "185.153.208.142" }

this is example structure of mydatabase:
> db.session.findOne()

    {
            "_id" : ObjectId("5786398d1f50070f31f27f7c"),
            "protocol" : "epmapper",
            "hpfeed_id" : ObjectId("5786398d1f50070f31f27f7b"),
            "timestamp" : ISODate("2016-07-13T12:52:29.112Z"),
            "source_ip" : "23.251.55.182",
            "source_port" : 2713,
            "destination_port" : 135,
            "identifier" : "d3374f14-48f7-11e6-9e19-0050569163b4",
            "honeypot" : "dionaea"
    }

Please help me to fix the error

A: ISODate is a JavaScript Date object. To query range of date using PyMongo, you need to use a datetime.datetime instance which mongod will convert to the appropriate BSON type. You don't need any third party library.
Also you shouldn't be using the Aggregation Framework to do this because the _id field is unique within the collection which makes this a perfect job for the distinct() method.
import datetime

start = datetime.datetime(2016, 11, 11)
end = datetime(2016, 11, 11, 23, 59, 59)

db.session.distinct('_id', {'timestamp': {'$gte': start, '$lte': end}})

If you really need to use the aggregate() method, your $match stage must look like this:
{'$match': {'timestamp': {'$gte': start, '$lte': end}}}

A: ISODate is a function in the Mongo shell, which is a javascript environment, it's not available within Python.
You can use dateutil for converting a string to datetime object in Python,
import dateutil.parser
dateStr = "2016-11-11T00:00:00.000Z"
dateutil.parser.parse(dateStr)  # returns a datetime.datetime(2016, 11, 11, 00, 0, tzinfo=tzutc())

Using PyMongo, if you want to insert datetime in MongoDB you can simply do the following:
import pymongo
import dateutil
dateStr = '2016-11-11T00:00:00.000Z'
myDatetime = dateutil.parser.parse(dateStr)
client = pymongo.MongoClient()
client.db.collection.insert({'date': myDatetime})


text:
Q: Is there a working example of React Transition Group's SwitchTransition component? I am trying to use a SwitchTransition component. Unfortunately, the code in the docs is not a complete example and I'm having trouble filling in the blanks. Does anyone have a simple example of this component being used, such as a CSS fade-out then fade-in?
I can't find any examples online. Does this mean that there is another common approach that I'm overlooking? Thanks!

A: I've made a simple example here that uses SwitchTransition to transition the text being displayed.
The react-transition-group docs link to vue transition modes which give some insight into how the switch transition works.


text:
Q: Allowing first undelimited argument to be empty Consider the following macro definitions:
\def\mymacro#1{\mymacroii#1\nil}
\def\mymacroii#1#2\nil{%
  \ifx\\#1\\%
    empty%
  \else
    #1%
  \fi
}%
\mymacro{foo}% -> f
\mymacro{}
\bye

This is supposed to extract the first character of the parameter to \mymacro. This works, but only if the argument is not empty.
How must I change my macros, so that the call \mymacro{} works as expected, i.e. outputs "empty"? Note, that is is only a simplified version. In reality I have several checks in \mymacroii for the first character, if it is a number, an opening brace, and so on.
This question is for sure related to Why does TeX remove braces around delimited arguments?, but I couldn't apply those informations to my case.

A: \def\mymacro#1{\mymacroii#1{empty}\nil}
\def\mymacroii#1#2\nil{%
    #1%
}%

\mymacro{foo}% -> f

\mymacro{}
\bye

In your version, in the empty case, the inner call is
\mymacroii\nil

so #1 is \nil and then it starts looking for the next \nil (which isn't there) to make #2 and things go wrong.

A: Just check for emptyness first.
\long\def\firstoftwo#1#2{#1}
\long\def\secondoftwo#1#2{#2}
\def\mymacro#1{%
  \ifx\\#1\\%
    \expandafter\firstoftwo
  \else
    \expandafter\secondoftwo
  \fi
  {empty}%
  {\mymacroii#1\nil}%
}
\def\mymacroii#1#2\nil{#1}

Just to get the flavor with LaTeX3, here's a version that allows you to define a function that examines the first token of the argument provided it was not empty in the first place (in this case it would output empty). It works also in expanded definitions, as shown below.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\mymacro}{ m }
 {
  \tl_if_empty:nTF { #1 }
   { empty }
   { \christoph_examine_first:f { \tl_head:n { #1 } } }
 }
\cs_new:Npn \christoph_examine_first:n #1
 {
  Whatever~you~want~with~#1~which~is~one~token
 }
\cs_generate_variant:Nn \christoph_examine_first:n { f }
\ExplSyntaxOff
\begin{document}

\mymacro{foo}

\mymacro{}

\edef\x{\mymacro{foo}\mymacro{}}\x

\end{document}


text:
Q: Need an unobtrusive method for logging So, I'm supposed to design a method that I would use to log everything my app does and I was thinking of doing something like this in my methods:
Declaration:
public static void Write(string text, params object[] parameters) {}

Usage:
if (Log.On) Log.Write("Hello", valueA, valueB, valueC);

So this is elegant and clean in my view. However it has one big flaw, the values are not labeled in any way. For me, the obvious solution is a method like this:
public static void Write(string text, Dictionary<string, object> parameters) {}

but this method will clutter my code.
if (Log.On)
{
Dictionary<string, object> p = new Dictionary<string, object>();
p.Add("valueA", valueA);
p.Add("valueB", valueB);
p.Add("valueC", valueC);
Log.Write("Hello", p);
}

Any ideas how to make this method as unobtrusive as possible?

A: You can use this:
public static void LogValues(string text, object values)
{
    var properties = values.GetType().GetProperties();
    Log.WriteLine(text + ": " + string.Join(", ",
        properties.Select(property =>
        {
            var name = property.Name;
            var value = property.GetValue(values);
            return name + " = " + (value != null ? value.ToString() : "null");
        })));
}

Like this:
int x = 5;
double y = 7.2;
LogValues("Some message", new { y, s = "test", x });

Which will generate a line like this in your log:
Some message: y = 7.2, s = test, x = 5

The key here is in using the anonymous type for the values parameter. This lets you pass in "named" variables, instead of just the values of those variables.
If you want a consistent ordering on the <name> = <value> pairs printed out, you can insert a .OrderBy(property => property.Name) before the .Select(...) in the LINQ query.


text:
Q: Communication between exe? I have several users on a single Windows Server 2012 (they are using Remote Desktop).
I have two (vb.net) programs, that need to communicate with eachothers - that is ... each user have two applications that need to communicate.
What is the easies (and most realiable) approach to have two apps communicate while several instances is running on the same box (on instance per RDS user)?
Thanks!

A: There're a lot of options:

*

*Message queue (for, example, MSMQ).

*ASP.NET WebAPI self-host

*WCF self-host.

*...

Maybe, in your case, I would go for the use of message queues. And, since MSMQ comes with Windows (in order to install it, go to Add/remove Windows features in Control Panel) and .NET Framework has support for it out-of-the-box, it could be a good choice.
Side-note
When I mention WCF/WebAPI self-host, I mean that each process can have a very tiny REST or SOAP (or whatever) API that may allow that any of the whole processes may act as clients and/or servers. It's a good way of having interprocess messaging

A: You can:
1) Use the SendMessage api - http://msdn.microsoft.com/en-gb/library/windows/desktop/ms644950(v=vs.85).aspx
2) Run a client-server http://www.codeproject.com/Articles/12318/Building-Client-Server-applications-with-VB-NET-fo
3) Use UDP broadcasting http://www.solidautomation.com/bryon/Using_UDP_and_Winsock_in_Visual_Basic_6.htm

A: Available options inter process communication would be:
WCF
Remoting
ASP.Net WebSevices
WM_COPYDATA
Socket programing
Interprocess Communications on MSDN would be resource


text:
Q: profiling / improving performance of AngularJS In searching for potential bottlenecks in AngularJS I found this  :
 var KEYWORD_REGEX = /^((ng:|[$_a-z])[\w\-_]+)/;

src :
https://github.com/angular/angular.js/blob/b77defde81fc265c13fa504dc78b41a43997abf4/docs/config/processors/keywords.js
KEYWORD_REGEX seems to have a high call count as it's called within loop :
_.forEach(tokens, function(token) { (line 72)

Which itself is within an inner loop :
_.forEach(doc, function(value, key) { (line 97)

Which is also within an inner loop ! :
_.forEach(docs, function(doc) { (line 88)

Se we have a nested loop two layers deep : O(N)^3 performance
This question : How Do I Measure the Performance of my AngularJS app's digest Cycle? suggests cpu profile run using Chrome dev tools to measure performance, but I don't think is granular enough to measure the performance of a specific section of code.
I'm not sure what code to write in order to hit this file. From reading the commend of file keywords.js :
 * This processor extracts all the keywords from each document and creates
 * a new document that will be rendered as a JavaScript file containing all

It seems any angular enabled file should invoke keywords.js as angularjs scan's every document for directives ? To measure performance an approach is run AngularJS from source , modify the loops described above to include timings (using getTime() ) which measures each loop to complete, create many AngularJS directives and run the app ?


text:
Q: Python Sqlite query help needed? I want to get data from my security and exchange tables. The columns in exchange are id, mic, exchange_code, and security tables have id, country, ticker, full_name, exchange_id. I want columns from both tables (like id, ticker, full_name, country, mic, exchange_code ).  I have tried this query in SQLite it's working fine in the SQLite browser.
SELECT security.id, ticker, security.country, exchange_code AS exchange, mic from security
INNER JOIN exchange ON exchange.id = security.exchange_id;

But when I tried in VS Code it shows empty dataset. The query is:
connection = sqlite3.connect(config.DB_FILE)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()

cursor.execute("""
    SELECT security.id, ticker, security.country, exchange_code AS exchange, mic from security
    INNER JOIN exchange ON exchange.id = exchange_id
    GROUP BY security.id ORDER BY ticker
""")
rows = cursor.fetchall()

A: It would seem to miss
ON exchange.id = security.exchange_id;

and not
exchange.id = exchange_id

exchange_id doesn't exist, this is why you have an empty result


text:
Q: How to convert String to Timestamp in kafka connect using transforms and insert into postgres using jdbc sink connector from confluent? Below is my kafka-connect-sink.properties file
I am using confluent-6.0.1.
name=enba-sink-postgres
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
connection.url=jdbc:postgresql://IP:PORT/DB
connection.user=USERNAME
connection.password=PASSWORD
tasks.max=1
topics=postgresInsert
insert.mode=INSERT
table.name.format=schema."tableName"
auto.create=false
key.converter.schema.registry.url=http://localhost:8081
key.converter.schemas.enable=false
value.converter.schemas.enable=false
config.action.reload=restart
value.converter.schema.registry.url=http://localhost:8081
errors.tolerance=all
errors.log.enable=true
errors.log.include.messages=true
print.key=true

# Transforms
transforms=TimestampConverter
transforms.TimestampConverter.type=org.apache.kafka.connect.transforms.TimestampConverter$Value
transforms.TimestampConverter.format=yyyy-MM-dd HH:mm:ss
transforms.TimestampConverter.target.type=Timestamp
transforms.TimestampConverter.target.field=DATE_TIME

I am using avro data and schema is :
 {\"type\":\"record\",\"name\":\"log\",\"namespace\":\"transform.name.space\",\"fields\":[{\"name\":\"TRANSACTION_ID\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"MSISDN\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"TRIGGER_NAME\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"W_ID\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"STEP\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"REWARD_ID\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"CAM_ID\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"STATUS\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"COMMENTS\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"CCR_JSON\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"},{\"name\":\"DATE_TIME\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"avro.java.string\":\"String\"}]}

Basically DATE_TIME column in Postgres is of type Timestamp and from avro I tried sending String date and also of type long .
DATE_TIME = 2022-12-15 14:38:02
Issue is If I dont use transform then I am getting error :
ERROR: column "DATE_TIME" is of type timestamp with time zone but expression is of type character varying

And If I use transforms as mentioned above then error is :
    [2021-02-06 21:47:41,897] ERROR Error encountered in task enba-sink-postgres-0. Executing stage 'TRANSFORMATION' with class 'org.apache.kafka.connect.transforms.TimestampConverter$Value', where consumed record is {topic='enba', partition=0, offset=69, timestamp=1612628261605, timestampType=CreateTime}. (org.apache.kafka.connect.runtime.errors.LogReporter:66)
org.apache.kafka.connect.errors.ConnectException: Schema Schema{com.package.kafkaconnect.Enbalog:STRUCT} does not correspond to a known timestamp type format

A: I got it working using :
 # Transforms
transforms= timestamp
transforms.timestamp.type= org.apache.kafka.connect.transforms.TimestampConverter$Value
transforms.timestamp.target.type= Timestamp
transforms.timestamp.field= DATE_TIME
transforms.timestamp.format= yyyy-MM-dd HH:mm:ss

For some reason transforms=TimestampConverter was not working.


text:
Q: Angular-material-data-table doesn't work I'm doing a web app and I'm using angular-data-table to display data in infinite scroll.
Now, for testing, I'm using a very little table (height: 150px), and I want to retrieve 4 items each time the user scroll.
But actually (always for test) I don't send the index of position to the server, so for now it retrieve all data in the database (that contains 11 items).
This is the code:
angular.module('app').controller('MyCtrl', ['$scope', 'DataSrv', function ($scope, DataSrv) {
$scope.testData = {
    numLoaded_: 0,
    toLoad_: 0,
    items: [],
    // Required.
    getItemAtIndex: function(index) {
        if (index > this.numLoaded_) {
            this.fetchMoreItems_(index);
            return null;
        }
        return this.items[index];
    },
    // Required.
    // For infinite scroll behavior, we always return a slightly higher
    // number than the previously loaded items.
    getLength: function() {
        return this.numLoaded_ + 2;
    },
    fetchMoreItems_: function(index) {
        if (this.toLoad_ < index) {
            this.toLoad_ += 2;

            var searchObject= {};
            searchObject.SearchCriteria = $scope.searchCriteria;
            searchObject.Local = $scope.filterLocal;

            var that = this;
            DataSrv.getData.get(
                {}, function (data) {
                            that.items = that.items.concat(data);
                            that.numLoaded_ = that.toLoad_;
                }, function (error) {
                    alert(error);
                }
            );
        }

    }
};
}]);

HTML:
  <md-virtual-repeat-container>
  <md-table-container>

          Title

          {{item.title}}

  </md-table-container>
  </md-virtual-repeat-container>

The problem is that if I write this in the html code

{{item.title}}

and if I write the page for the first time, it shows more than 20 items (repeated). So it call a lot of time the server. Why?


text:
Q: Multicast works only in promiscuous mode I'm trying to receive MPEG-TS over UDP multicast transport in Arch Linux.
So when I run ffprobe -i udp://@224.1.1.240:6000 it hangs forever with no result. Then I run tcpdump and it shows no multicast traffic from the address.
But if there is running tcpdump -i eth0 -n net 224.0.0.0/4 in background while ffprobe, it works! tcpdump shows packets and ffprobe correctly detects a stream.
As one may notice the problem likely dissappears while NIC is in promiscuous mode.
Can someone help with it? What's wrong with my config?

*

*Everything in iptables is ACCEPTed.

*cat /proc/sys/net/ipv4/conf/*/rp_filter
0
0
0
0
0
0
0

*ip r
default dev ppp0  scope link
83.221.214.192 dev ppp0  proto kernel  scope link  src 10.7.248.143
192.168.168.192/28 dev enp3s0  proto kernel  scope link  src 192.168.168.193
224.0.0.0/4 dev enp3s0  scope link

Network connected to ISP through D-LINK DGS-1005A.
PS Everything works perfect in Windows 7 on the same PC.

A: I know the question is old, but...
it was necessary to set the allmulti flag on your network card
ifconfig enp3s0 allmulti


text:
Q: changing the value of argument(list) in python I wanted to change the value of the argument(list),
so I wrote the code as follows, but it didn't work properly.
def add1(s): # s is a list
    for i in s:
        i += 1

So I changed the code as shown below, and it worked.
However, I want to know why the first code didn't work properly.
def add1(s):
    for i in range(len(s)):
        s[i] += 1

If you know the reason and explain it, I would really appreciate it.

A: i is a local variable in the loop that's holding the number that s holds. Reassigning a variable doesn't effect the data that it held originally.
It's similar to how this doesn't change a:
a = 1
b = a  # This is somewhat what's happening with `for i`
b += 1  # And this is comparable to i += 1

print(a, b)  # Will print 1 2, not 2 2

A: int values are immutable. You can't change the value of an existing int; you can only replace it with a different int. But that means you only change what the name i refers to, not the element of s used to initialize i in the first place.
In your first code, you make i reference a new int.
In your second code, you make a particular slot of s refer to a new instance of int.


text:
Q: What are the geometric, harmonic, and quadratic averages of a function? In Mean of a function, they describe the arithmetic mean of a function and at the bottom of the article they said:

There is also a harmonic average of functions and a quadratic average (or root mean square) of functions.

My question is what is the form of these averages?

A: Typically, if $(X,\mathscr{B},\mu)$ is a probability space, and $\phi$ is nice bijective function from $(a, b)$ to another interval $(c, d)$, then the $\phi$-mean, defined for measurable  functions $f: X\rightarrow (c,d)$ for which $\phi\circ f$ is integrable  is defined as $$\phi^{-1}\Big(\int\phi\circ f\,d\mu\Big)$$
The most common examples are

*

*$\phi(x)=x$ (arirthmetic mean)

*$\phi(x)=\log(x)$, $x>0$, (geometric mean)

*$\phi(x)=\frac{1}{x}$, $x>0$ (harmonic mean)

*and $\phi(x)=x^p$, $x\geq 0$ (the $p$-mean).

In many applications of the means described in 1-4, one considers  $|f|$, which is nonnegative, and defined
$$|f|_\phi:=\phi^{-1}\Big(\phi(|f|)\,d\mu\Big)$$
When $\phi(x)=x^p$, the space $L_p(\mu):=\{f:|f|_\phi<\infty\}$ is a (complex) linear space and $|\;|_p$ defines a (pseudo)-norm that is complete. As Prof. GEdgar mentioned in his comment below, $\phi(x)=x^2$ corresponds to the quadratic mean (or quadratic norm).


text:
Q: Redirect to user page after login Changed my code to the following thanks to the tips. But I'm still not redirected to the user.php. Added the variable $rowcount and give it a value. If the query has a value of a user it have to be redirected to the user.php page.
<?php
    include("inc/header.php");
?>

<?php
    if(isset($_POST["submit"])) {

    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);

        if($username == "" && $password == "") {
            echo "Please fill in all the details";
            exit;
        }

        if($username == "admin" &$password == "test") {
            $_SESSION["admin"] = true;
            header("location: admin-panel.php");
        }

        $rowcount = 0;
        $password_secure = md5($password);
        if($username != "" && $password != "") {
            $sql = "SELECT * FROM user WHERE username = '".mysqli_escape_string($connection, $username)."'
            AND password = '".mysqli_escape_string($connection, $password_secure)."'";
            $query = mysqli_query($connection, $sql);
            $rowcount = mysqli_num_rows($query);
        } else {
            echo "Username of password was not right, please try again.";
        }

        if($rowcount != 0) {
            $row = mysql_fetch_array($connection, $query);
            $_SESSION["username"] = $row["username"];
            $_SESSION["login"] = true;
            header("location: user.php");
            exit;
        }
    }
?>

<?php
    include("inc/footer.php");
?>

A: // if logged in, redirect towards user account
if($logged_in) {
    header("Location: useraccount.php");
    exit(0);
}

Change $logged_in with your php stracture

A: Add session_start() at the top of your page. Also change the following code.
session_start();
..
..

if($rowcount == 1)
{
   while($row = mysqli_fetch_array($query))
   {
        $_SESSION["username"] = $row["username"];
        $_SESSION["login"] = true;
   }
   header("location: user.php");
}

In user.php, first check whether user is logged in or not. For that write a simple function -
function is_loggedin()
{
    if(isset($_SESSION['username']) && isset($_SESSION['login']))
        return TRUE;
    else
        return FALSE;
}

If return FALSE, redirect back to Login page.

A: Your $rowcount must to be declared at outside of the "if":
$rowcount=0;
if($username != "" && $password != "") {
    $sql = "SELECT * FROM user WHERE username = '".$username."'
            AND password = '".$password_secure."'";
    $query = mysqli_query($connection, $sql);
    $rowcount = mysqli_num_rows($query);
}


text:
Q: Sequelize querying inside virtual column like Laravel get attribute function inside model? I want to calculate rank from user model where rank is just number.
example rank:

*

*bronze : 50 point

*silver : 100 point

*gold   : 200 point

and when user rank is 150 point it should be in silver rank. Can I calculate rank from virtual column to get the rank name with querying into rank table ?
"use strict";
module.exports = (sequelize, DataTypes) => {
const Rank = sequelize.define("Rank", {
   name: DataTypes.STRING,
   tier_total: DataTypes.INTEGER
});
const UserGameID = sequelize.define(
"UserGameID",
{
  user_id: DataTypes.INTEGER,
  total_win: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  total_lose: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  total_match: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  total_point: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  rank: {
    type: DataTypes.VIRTUAL,
    get: async function() {
      var rank = await Rank.findOne({
        where: {
          tier_total: { $lte: this.total_point }
        },
        order: [["tier_total", "desc"]]
      });
      return rank;
    }
  },
  status: DataTypes.BOOLEAN //false: unapproved, true: approved
}, { }
);

expected result:
user_id: 1
total_win: 2
total_lose: 1
total_match: 3
total_point: 150
rank: silver

but rank always returning {}


text:
Q: Mercurial - block access to a branch using ACL extension on Windows I am trying to deny everyone commit access to a branch using ACL on Windows but can't quite seem to figure it out.  According to the little documentation I've found this should work.
My hgrc file:
[extensions]
hgext.acl=

[hooks]
pretxncommit.acl = python:hgext.acl.hook

[acl]
sources = commit

[acl.deny.branches]
default = *

Shouldn't this deny everyone commit access to the default branch? I tried and now every commit, no matter the branch give:
error: pretxncommit.acl hook failed: config error - hook type "pretxncommit" can
not stop incoming changesets
transaction abort!
rollback completed
abort: config error - hook type "pretxncommit" cannot stop incoming changesets

Leads me to think I configured it wrong, but it's pretty much exactly how they do it in the AclExtension documentation.

A: Here's the relevant code from acl.py:
if hooktype not in ['pretxnchangegroup', 'pretxncommit']:
    raise util.Abort(_('config error - hook type "%s" cannot stop '
                       'incoming changesets nor commits') % hooktype)

Which I would think checks after the ".acl" from your hook name is removed, but perhaps in your version of mercurial (what version?) it isn't?
Try changing your [hooks] section to just this:
[hooks]
pretxncommit = python:hgext.acl.hook

the .acl is only necessary when you have multiple hooks of the same type.


text:
Q: Console output one time every 40 seconds with interval doesn't work I'm trying to use Twitter API in order to retweet.And because Twitter has limitation to 2400 actions per day I decided to limit the retweet to one time every 40 seconds.
I'm using https://www.npmjs.com/package/twit using Streaming API.
My problem is that it continuously streams console.log instead of using setInterval.
By stream I mean it outputs console.log multiple times instead of one time.
function hastagRetweet() {

    var stream = T.stream('statuses/filter', { track: ['#hastag']})

    stream.on('tweet', function (tweet,error) {

        var retweetId = tweet.id; // id
        var retweetId_str = tweet.id_str;
        var tweetTextRetweet = tweet.text; // tweet text

        function twInterval() {

            console.log('INFO ------- ',tweet.id);
            console.log('INFO ------- ',tweet.text);

        };

        setInterval(twInterval, 1000 * 40);

    });

}

Any way of getting the variales data retweetId,retweetId_str,tweetTextRetweet outside stream.on beside inserting them into a mysql table so that every 40 seconds it checks the variables fixed data and executes console.log?

A: There are multiple problems here:

*

*You're trying to start an interval timer in an event handler.  That means that every time the event fires you would be attempting to start a new interval timer and they would pile up.

*Even if you did sucessfully start up an interval timer, each one would never change it's output since the variables in scope for it never change as it is started up within a given function and the arguments to that function are what they were when it was first called.  Subsequent calls of the function will start a new function not change the arguments on the prior call of the function.

*You aren't even starting your interval correctly.  As it is, all you're doing is calling the function and passing it's return value to setInterval() which does nothing.
If the goal is just to output to the console each stream tweet event, then probably what you want is just this:
function hastagRetweet() {

    var stream = T.stream('statuses/filter', { track: ['#hastag']})

    stream.on('tweet', function (tweet,error) {

        var retweetId = tweet.id; // id
        var retweetId_str = tweet.id_str;
        var tweetTextRetweet = tweet.text; // tweet text

        console.log('INFO ------- ',tweet.id);
        console.log('INFO ------- ',tweet.text);
    });
}

You cannot get these variables outside the .on() handler.  It's an async callback and the only place they reliably exist is within that handler.
If you can describe in more detail what the end result you're trying to achieve is, we can likely help more specifically.  If you want to do something every 40 seconds, then maybe you need to collect data in some collection (probably an array) and then every 40 seconds evaluate what you have just recently collected.
Here's a method of collecting the events in an array and then evaluating them every 40 seconds:
function hastagRetweet() {

    var stream = T.stream('statuses/filter', { track: ['#hastag']});
    var tweets = [];

    stream.on('tweet', function (tweet,error) {
        tweets.push({id: tweet.id, str: tweet.id_str, text: tweet.text});
    });

    setInterval(function() {
        // evaluate the tweets in the tweets array every 40 seconds

        // do something with them
        for (var i = 0; i < tweets.length; i++) {
            // tweets[i].id
            // tweets[i].str
            // tweets[i].text
        }

        // reset the tweets array
        tweets.length = 0;
    }, 40 * 1000);

}

Please note that once you call hastagRetweet(), it will run forever.


text:
Q: When a media network can't show/say a certain brand/logo/product of a company so they censor/blurr/avoid topic, cause brand didn't bought ad It's simply, that in TV, whenever a logo appears, they censor it, or when a person says a brand name, either they cut it, or bleep it. This is due to the network charges for ads, however in that case they obviously can't charge them.
I'm asking for the english expression. In spanish, at least Argentina, the expression is "chivo publicitario".

A: I couldn't find anything more specific than censorship, so I guess this humorous term from TV Tropes will have to suffice.

Product Displacement: [...] when products or corporate logos turn
  up incidentally in TV programming without having paid the requisite
  dues, they will be censored.

Apparently, the process of obscuring brand names is called "greeking".
Related to Brand X, when instead of a regular censorship the producers just make up a brand.


text:
Q: Modifying whitelisted property on Spring cloud Data Flow UI I am able to whitelist properties in a task using spring-configuration-metadata-whitelist.properties. The properties whitelisted is displayed in read only mode on the application detail screen.
Even on the task creation or detail screen the whitelisted properties are not shown in order to override the default value. Is there any way to change the whitelisted property value using the spring cloud dataflow screen?

A: It is possible to change the properties of Stream/Task applications when building the data pipeline from the GUI.
You'd click the application that requires the change and then select the "gear" icon (see attached pic) to go about changing the properties. Alternatively, you can manually provide the k/v pairs (e.g.: --job.config-file=file:spring_v02.xml) that'd like to override on the textual DSL section on the top section to the drag-and-drop canvas.


text:
Q: lua inheritance on existing object I am writing a new constructor and I have something like this:
function Map:new(path, world, debug)
    local map = sti(path, { "box2d" })
    return map
end

function Map:update(dt)
    print('call this')
end

sti is some thirdparty library that constructs a class object.
What I am trying to do is make it so when I call:
map:update(dt)
it calls the functions I have declared. If not found, it calls the actual function that sti sets up on the object.
I've tried stuffing around with metatables but can't seem to get my functions to take priority over the third party library supplied functions....

A: Reading the source code for what I believe is the library you're using (Simple-Tiled-Implementation), I figured out it actually overrides your metatable with another one:
local function new(map, plugins, ox, oy)
    local dir = ""

    if type(map) == "table" then
        map = setmetatable(map, Map) -- Here
    else
        -- Check for valid map type
        local ext = map:sub(-4, -1)
        assert(ext == ".lua", string.format(
            "Invalid file type: %s. File must be of type: lua.",
            ext
        ))

        -- Get directory of map
        dir = map:reverse():find("[/\\]") or ""
        if dir ~= "" then
            dir = map:sub(1, 1 + (#map - dir))
        end

        -- Load map
        map = setmetatable(assert(love.filesystem.load(map))(), Map) -- Or here
    end

    map:init(dir, plugins, ox, oy)

    return map
end

The function above is defined here
You'll need to pass a table argument as map instead of the path, there you can define update(), which will take precedence over the metatable provided by STI.
I believe you can copy the procedure STI does to load your map and provide it with a table containing the function you wish to define inside:
-- Check for valid map type
local ext = map:sub(-4, -1)
assert(ext == ".lua", string.format(
    "Invalid file type: %s. File must be of type: lua.",
    ext
))

-- Get directory of map
dir = map:reverse():find("[/\\]") or ""
if dir ~= "" then
    dir = map:sub(1, 1 + (#map - dir))
end

-- Load map
local map = assert(love.filesystem.load(map))()
function map:update()
    -- Do things
end

sti(map, { "box2d" })

A: unfortunately sti declares 'local dir' at the top of the function so copying the code did not work.
I found a solution how ever I have made myself some way to easily set a class as a proxy in lua:
-- forward a function call from oldSelf:fn(...) to newSelf:fn(...)
function utils.forwardFunc(fn, newSelf)
   return function(oldSelf, ...)
      local function __NULL__() end
      return (fn or __NULL__)(newSelf, ...)
  end
end

-- make a function fn(...) call newSelf:fn(...)
function utils.func(fn, newSelf)
   return function(...)
      local function __NULL__() end
      return (fn or __NULL__)(newSelf, ...)
  end
end

-- forward any undefined functions called on 'from' to 'to'
-- if 'to' is a function, it acts as a dynamic proxy, incase you are changing what class you are proxying to
-- on the fly. For example, a state machine proxies to the current state
function utils.proxyClass(from, to)
   local mt = getmetatable(from)
   setmetatable(from, {__index = function(_, func)
         if mt and mt[func] then
            return mt[func]
         end

         local forwardTo = to
         if type(to) == 'function' then
            forwardTo = to(from)
         end

         if type(forwardTo[func]) == 'function' then
            return utils.forwardFunc(forwardTo[func], forwardTo)
         else
            return forwardTo[func]
         end
   end})
end


text:
Q: Hyperledger Fabric Manually generate the artifacts I have clone the fabric-samples and tried to run the balance-transfer sample. When run it as it is, it runs smoothly with no issues. But when I remove the crypto-config folder and generate it with command cryptogen generate --config=./cryptogen.yaml. Then when I try Login Request with any user other than Jim I get error, adding image of logs.

Can anyone guide what am i doing wrong here?
System Configuration
**OS**
CentOS Linux release 7.4.1708
**Docker**
Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:23 2017
 OS/Arch:      linux/amd64
Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:49 2017
 OS/Arch:      linux/amd64
 Experimental: false
**GoLang**
go version go1.9.2 linux/amd64
**Docker Images**

dev-peer0.org1.example.com-mycc-v0-f021beca29998638e0bb7caa7af8fda7f1e709518214a3181d259abcb2347093   latest              d69f39aae76e        About an hour ago   145MB
dev-peer1.org1.example.com-mycc-v0-f76f22af4a360dd2172e04459b1687f933a29d4b8d6c97ea0a4a21144a108361   latest              7cbe869e1a5e        About an hour ago   145MB
hyperledger/fabric-ca                                                                                latest              17f38f1c8e80        3 weeks ago         238MB
hyperledger/fabric-ca                                                                                x86_64-1.0.3        17f38f1c8e80        3 weeks ago         238MB
hyperledger/fabric-tools                                                                              latest              ac1f4a1e58a6        3 weeks ago         1.33GB
hyperledger/fabric-tools                                                                              x86_64-1.0.3        ac1f4a1e58a6        3 weeks ago         1.33GB
hyperledger/fabric-couchdb                                                                            latest              b2188fa55138        3 weeks ago         1.47GB
hyperledger/fabric-couchdb                                                                            x86_64-1.0.3        b2188fa55138        3 weeks ago         1.47GB
hyperledger/fabric-kafka                                                                              latest              9e2a425c9dd6        3 weeks ago         1.29GB
hyperledger/fabric-kafka                                                                              x86_64-1.0.3        9e2a425c9dd6        3 weeks ago         1.29GB
hyperledger/fabric-zookeeper                                                                          latest              3b50cfad9af3        3 weeks ago         1.3GB
hyperledger/fabric-zookeeper                                                                          x86_64-1.0.3        3b50cfad9af3        3 weeks ago         1.3GB
hyperledger/fabric-orderer                                                                            latest              fd1055ee597a        3 weeks ago         151MB
hyperledger/fabric-orderer                                                                            x86_64-1.0.3        fd1055ee597a        3 weeks ago         151MB
hyperledger/fabric-peer                                                                               latest              b7f253e87c0c        3 weeks ago         154MB
hyperledger/fabric-peer                                                                               x86_64-1.0.3        b7f253e87c0c        3 weeks ago         154MB
hyperledger/fabric-javaenv                                                                            latest              1d778fcc14c0        3 weeks ago         1.41GB
hyperledger/fabric-javaenv                                                                            x86_64-1.0.3        1d778fcc14c0        3 weeks ago         1.41GB
hyperledger/fabric-ccenv                                                                              latest              2e5898d8b21b        3 weeks ago         1.28GB
hyperledger/fabric-ccenv                                                                              x86_64-1.0.3        2e5898d8b21b        3 weeks ago         1.28GB
hello-world                                                                                latest              05a3bd381fc2        6 weeks ago         1.84kB
hyperledger/fabric-ca                                                                                x86_64-1.0.2        7e53be14f804        8 weeks ago         238MB
hyperledger/fabric-tools                                                                              x86_64-1.0.2        ba9750b2565d        8 weeks ago         1.33GB
hyperledger/fabric-couchdb                                                                            x86_64-1.0.2        3f922f54bd68        8 weeks ago         1.47GB
hyperledger/fabric-kafka                                                                              x86_64-1.0.2        0b4b1d249e65        8 weeks ago         1.29GB
hyperledger/fabric-zookeeper                                                                          x86_64-1.0.2        1efb063147d3        8 weeks ago         1.3GB
hyperledger/fabric-orderer                                                                            x86_64-1.0.2        6efd17e86e65        8 weeks ago         151MB
hyperledger/fabric-peer                                                                               x86_64-1.0.2        0e2ed51971c9        8 weeks ago         154MB
hyperledger/fabric-javaenv                                                                            x86_64-1.0.2        0be45dbd7ff4        8 weeks ago         1.41GB
hyperledger/fabric-ccenv                                                                              x86_64-1.0.2        d0f166e1a89e        8 weeks ago         1.28GB
hyperledger/fabric-baseos                                                                             x86_64-0.3.2        bbcbb9da2d83        2 months ago        129MB
hyperledger/fabric-membersrvc                                                                         latest              b3654d32e4f9        12 months ago       1.42GB

A: After generating certificate using cryptogen tool you need to update the docker-compose.yaml according to the new keys generated by the cryptogen tool. For example in case of balance-transfer example, you will need to update keys
here; the key can found at ..artifacts\channel\crypto-config\peerOrganizations\org1.example.com\ca
here the key can found at ..artifacts\channel\crypto-config\peerOrganizations\org1.example.com\ca
here the key can found at..artifacts\channel\crypto-config\peerOrganizations\org2.example.com\ca
and here the key can found at ..artifacts\channel\crypto-config\peerOrganizations\org2.example.com\ca

A: If you to create and utilize crypto-config by generating it using cryptogen tool make sure that to you clean everything from previous configuration firstly e.g. channel artificates, channel transactions etc.

A: I don't understand very well when you get the error. When you execute the cryptogen tool, you generate the certificates for the users of the balance-transfer. Is the user Jim among those users? Which is the configuration that you have in the cryptogen.yaml file?
Edit
I understand that you get the error because you are trying to enroll again the user Jim.
If you use the cryptogen tool, you dont' need to use the CA. You have to define a via to create the certificates.
However, if you don't use the cryptogen tool and you registry and enroll your user via de Fabric CA, you should have a DB for your users. The DB is created in the Fabric CA Server. Could you query the DB of the CA?! Probably, it would be a sqlite file.


text:
Q: расстояние между айтемами recyclerview Требуется при использовании RecyclerView не использовать CardView, тем самым корневой элемент становится LinearLayout и необходимое расстояние между элементами пропало.
Скрин №1:

Наглядно о том, что именно пропало.
Скрин №2:

А вот и разметочка подъехала:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="16dp">

        <ImageButton
            android:id="@+id/thumpup"
            android:layout_width="wrap_content"
            android:layout_height="27dp"
            android:background="#00000000"
            android:src="@drawable/thumbupgrey" />

        <TextView
            android:id="@+id/likes"
            android:singleLine="true"
            android:layout_width="50dp"
            android:textAlignment="center"
            android:layout_height="wrap_content"
            android:text="likes" />

        <ImageButton
            android:id="@+id/thumpdown"
            android:layout_width="wrap_content"
            android:layout_height="27dp"
            android:layout_gravity="right"
            android:background="#00000000"
            android:src="@drawable/thumbdowngrey" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="32dp"
            android:textSize="16sp"
            android:background="#00000000"
            android:textStyle="bold"
            android:textColor="#000000"
            android:id="@+id/mainwords"
            android:layout_weight="1"/>

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:padding="2dp"
            android:background="#00000000"
            android:layout_gravity="right"
            аndroid:layout_alignParentRight="true"
            android:src="@drawable/info"
            android:id="@+id/infobtn" />

    </LinearLayout>

Каким образом снизу добавить линию для разделения итемов?
Пытался следующим образом, но холдер выплюнул эксепшеном в лицо:

<item>

    <shape android:shape="line">

        <stroke android:layout_width="match_parent" android:color="#F20107" />

    </shape>

</item>

A: Вам нужно создать наследника RecyclerView.ItemDecoration и в нём задать нужные отступы:
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class SpacesItemDecoration extends RecyclerView.ItemDecoration
{
    private int space;

    public SpacesItemDecoration(int space)
    {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
    {
        //добавить переданное кол-во пикселей отступа снизу
        outRect.bottom = space;
    }
}

Потом, при инициализации RecyclerView присвоить его:
RecyclerView rv = ...;
rv.addItemDecoration(new SpacesItemDecoration(100));


text:
Q: How to implement the simple Rect.insersects(Rect one, Rect two) method? I have read the android spill on this method tons of times and it isn't ringing any bells. Bellow is a part of my code:
@Override
    protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);

          boolean CollisionTest;

          Rect jSquare = new Rect();
          Rect mSquare = new Rect();

          jSquare.set(0,500,600,400);
              mSquare.set(0, 500,700, 100);

    canvas.drawRect(mSquare, Some Color..);
        canvas.drawRect(jSquare, Some Color...);

  CollisionTest = Rect.intersects(jSquare, mSquare);

  if (ColisionTest==true){
    canvas.drawColor(Color.RED);
      }

A: From the documentation for set
public void set (int left, int top, int right, int bottom)

Set the rectangle's coordinates to the specified values. Note: no range checking is performed, so it is up to the caller to ensure that left <= right and top <= bottom.

500 > 100


text:
Q: What is wrong in my analysis? Let $x = 1 + 1 + 1 + \cdots  \infty \textrm{ times}$.
$\therefore \quad x = 1 + x$
$\therefore \quad x - x = 0 = 1$
But this is absurd. I am unable to understand where I have gone wrong. I remember using this kind of analysis for solving problems like this.

A: Thank you for pointing out a clear absurdity! There are some ludicrous people on the internet who come across this pseudo-proof as you have and then think that all of mathematics must be false. (You are fortunate to recognize that you have made some error, and that's good.) So the problem with this line of reasoning is that $1 + 1 + \cdots$ is not a number. In fact, the series $\sum\limits_{i=0}^\infty 1$ does not converge to a number. (If you have not yet taken Calculus II or dealt with convergence of series, then...don't worry so much about the convergence details and just recognize that $1 + 1 + \cdots$ does not represent an actual number in the sense of an integer, rational, real, or complex number.)
Hence you cannot add 1 to $x$, because there is no definition of $+$ in this context. You also cannot subtract $x$ from itself, because $x$ is, again, not a number!
Hopefully that answers your question! Feel free to ask for more details, though I'm not sure what more I can give.