Q: Write to MySQL on mouseover After months of testing, I'm not succeeding to create a script that writes a logtext to the MySQL when a div gets a mouseover.
I think I have to use $.ajax, the only problem is, is that ajax (still) is the language which I'm not very good at.
One of the 100 things i've tried:
<?
echo "
Some dynamic text
";
?>

Who can help?

A: Ok, there's a much better way to do this, but since I'm on a phone that's dying and you have been waiting a year...
var info = $("#div0").html();
// if Js in a php file you can do var info = <?php echo $logtext ?>; To bring it to JS
$.get("phpfilehere.php", {info:info}, function(data){
alert(data);
});

The mouseover function...
$("#div0").on("mouseover", function(){
// my JS code above goes here
 });

PHP file:
if(isset($_GET['info'])){
$log = $_GET['info'];
// Put ur stuff here, make sure u only echo when u want ur php script to stop and be sent back to Ajax function as data var.
// insert $log
echo "test";
} else {
echo "no get info supplied":
}

And here is a tool I made to teach people how to write prepared statements for SQL queries :) if you need it...
http://wbr.bz/QueryPro/index.php?query_type=prepared_insert


Q: Basic Javascript Variable Scoping So I'm trying to make an app that would return whether each of these twich users
  ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx",      "RobotCaleb", "noobs2ninjas"]

is streaming. This is my code:
var users= ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var progress =0;
var streaming = [];
$(document).ready( function() {
console.log(window.progress);
while (window.progress<8) {

var url = 'https://api.twitch.tv/kraken/streams/' + window.users[window.progress] + '?callback=?';
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
if (data.stream) {

window.streaming[window.progress]="streaming";

}
//if closed
else {
window.streaming[window.progress]="not streaming";
};
//else closed

console.log(window.progress);
console.log(window.users[window.progress]);
var html = "
 "+window.users[window.progress]+ " is currently " +window.streaming[window.progress] + "
";
$("body").append(html);
}});
// getjson closed
        window.progress +=1;
        };
// for loop closed

});

//document ready closed

and this is what I'm getting:
"undefined is currently streaming"
so it doesn't seem to pull the users. Thanks

A: Your streaming array isn't initialized, so this can't be done due there's no 0,1,... element on it
window.streaming[window.progress]="streaming"; //streaming.length == 0, streaming[0] == 'undefined'

maybe you would like to clone the users.length on it to have a index
streaming = []; // length == 0
streaming.length = users.length; // length == users.length


Q: How to properly plot a ratio I am trying to plot a ratio but my problem is that when the dividend is larger than the divisor my quotient can be as high as possible.  When the divisor is larger than the dividend the quotient is between 0 and 1.  That is fine, but when I plot out the results the ratios with the larger dividend take up a huge portion of the plot and the smaller dividend ratios are limited to a much smaller area.  Is there a way to show ratios on a plot (hopefully using base plots) where the dividend is five times greater than the divisor will take up the same amount of space as when the divisor is five times greater than the dividend.
Here is some sample data:
x=1:10
y=10:1
ratioxy=x/y

The data is:
x
[1]  1  2  3  4  5  6  7  8  9 10
y
[1] 10  9  8  7  6  5  4  3  2  1
ratioxy
[1]  0.1000000  0.2222222  0.3750000  0.5714286  0.8333333  1.2000000  1.7500000  2.6666667
[9]  4.5000000 10.0000000

When I do this:
plot(ratioxy,type='l',col='blue')
abline(h=1)

I get this:

All I can think of is somehow playing around with the quotients in ratioxy that are less than one, but nothing is coming to me right now.

A: Try using a logarithmic scale.
plot(ratioxy,type='l',col='blue')


Q: Getting False with my Def, What is wrong with my code? def richNumber(n):
    nb = []
    n = int(n)
    sum1 = 0
    for i in range(n, n+1):
        if n % i ==0:
            nb.append(i)
    sum1 = sum(nb) - nb[-1]
    if sum1 > n:
        return True
    else:
        return False

n = int(input("n:"))

print(richNumber(n))

I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100

With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False

A: for i in (n, n+1)

Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)

A: Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
    nb = []
    n = int(n)
    sum1 = 0
    for i in range(1, n):
        if n % i == 0:
            nb.append(i)
    sum1 = sum(nb)
    if sum1 > n:
        return True
    else:
        return False


Q: how to make display to console text I am beginner at C# and I am trying like welcome message like as
 Console.WriteLine(" Enter Your Name:");
 Console.Write(new string(' ', Console.WindowWidth));
 Console.Write("first name:");
 string name = Console.ReadLine();

I need after entering the first name to clear the window and go for next output like:
 Console.Write("last name:");
 string lastname = Console.ReadLine();

How do I do this?

A: You can clear the console window with
Console.Clear()

If you put this in between your two blocks of code you should have what you need.
You can also make a blank line by doing
Console.Writeline();

Instead of
Console.Write(new string(' ', Console.WindowWidth));

A: Did you try this...
Console.WriteLine(" Enter Your Name:");

Console.WriteLine("first name:");
string firstName = Console.ReadLine();

Console.WriteLine("last name:");
string lastName = Console.ReadLine();

Please feel free to use Console.Clear() to clear the console.
You may further print/see the values using
Consile.WriteLine("Your First Name is " + firstName + " and last name is " + lastName);


Q: Match and replace string in text using regular expressions I have a large string and it might have the following:

How can I replace values in the string from anything above to:

this is what I came up with, but it does not work:
        string source = "bunch of text";
        string regex = "
";
        string regexReplaceTo = "
";
        string output = Regex.Replace(source, regex, regexReplaceTo);

A: What about...

*

*Regex to match : class=\"[A-Za-z0-9_\-]+\"

*Replace with   : class=\"\"
This way, we ignore the first part (id="Specs", etc) and
just replace the class name... with nothing.

A: Looks like another case of http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html.  What happens to the following valid tags with a Regex?

I don't see a how using Linq2Xml wouldn't work with any combination:
XElement root = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
var specsDivs = root.Descendants()
                    .Where(e => e.Name == "div"
                           && e.Attributes.Any(a => a.Name == "id")
                           && e.Attributes.First(a => a.Name == "id").Value == "Specs"
                           && e.Attributes.Any(a => a.Name == "class"));
foreach(var div in specsDivs)
{
  div.Attributes.First(a => a.Name == "class").value = string.Empty;
}
string newXml = root.ToString()

A: If your input isn't XML compliant, which most HTML isn't, then you can use the HTML Agility Pack to parse the HTML and manipulate the contents. With the HTML Agility PAck, combined with Linq or Xpath, the order of your attributes no longer matters (which it does when you use Regex) and the overall stability of your solution increases a lot.
Using the HTML Agility Pack (project page, nuget), this does the trick:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("your html here");
// or doc.Load(stream);

var nodes = doc.DocumentNode.DescendantNodes("div").Where(div => div.Id == "Specs");

foreach (var node in nodes)
{
    var classAttribute = node.Attributes["class"];
    if (classAttribute != null)
    {
        classAttribute.Value = string.Empty;
    }
}

var fixedText = doc.DocumentNode.OuterHtml;
//doc.Save(/* stream */);


Q: Testing Exceptions in Nunit 3.0 and above I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?
Feel free to improve code if you want, just started learning programming few months ago.
When running it gives the exception itself, does not pass.
Test errors out- Message: System.ArgumentException : Too much data
public class ParseVendorSupply
{
    public VendorSupply FromCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        if (values.Length > 3)
        {
            throw new System.ArgumentException("Too much data");
        }
        VendorSupply vendorsupply = new VendorSupply();
        vendorsupply.VendorId = Convert.ToInt16(values[0]);
        vendorsupply.ProductId = Convert.ToInt16(values[1]);
        vendorsupply.Quantity = Convert.ToInt16(values[2]);
        return vendorsupply;
    }
}

Test:
public class ParseVendorSupplyNunit
{

    ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
        string csvLineTest = "5,8,3,9,5";
        //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
        Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
    }

A: You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:
Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));

There is also an async version if you are using async/await
Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));

A: The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.
Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.
Defining an Action avoids this problem because it specifies a method call that won't be made immediately.
However, a more colloquial way to specify this in NUnit is by using a lambda directly...
Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);

A: Wrap method you are testing into an Action
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseFromCsv, Throws.ArgumentException)

And when testing for common exceptions, such as ArgumentException, always test for exception message as well.
Because common exception can occur in some other places and test will pass for a wrong reason.
I prefer to use FluentAssertions, which I found little bid more readable.
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");


Q: Count number of records in lmdb databse with python I open a lmdb database using this code:
    lmdb_env = lmdb.open(source_path, readonly=True)

How can I count the number of records in this database?

A: I think it should be like this:
lmdb_env = lmdb.open(lmdb_file_name, readonly=True)
print lmdb_env.stat()

Then it prints the directory that Jaco pasted here.

A:     env = lmdb.open('db file path', max_dbs = ' > 0')
    with env.begin() as tx:
        db = env.open_db(b'db name', txn=tx)
        print(env.stat())
        print(tx.stat(db)) # this gives stats about one specific db

env.stat() gives entries of the main database. tx.stat(db) gives entries of one named database.

A: You can use event.stat(). It will return the following dictionary with entries detailing the number of records in this database:
{'branch_pages': 1040L,
'depth': 4L,
 'entries': 3761848L,
 'leaf_pages': 73658L,
 'overflow_pages': 0L,
 'psize': 4096L}

A: I found a simple solution using for loop. Here it is:
count = 0
for key, value in lmdb_env.cursor():
        count = count + 1

However, I think there should be a better way using pre-defined function.


Q: Why am I getting Interceptor attempted to ‘Proceed’ for a method without a target error? In my case I have main project and test project. I was getting proper results on the test project where I have only one Installer class and register everything in one place. In my main project I had several installers (one for service, one for interceptors, one for common libraries, one for data persistence). For the main project I was getting the error specified:
This is a DynamicProxy2 error: the interceptor attempted to ‘Proceed’ for a method without a target, for example, an interface method or an abstract method
I was struggling to find out what was wrong. I plugged into my constructor that accepts interface of a data persistence layer and saw that it only receives a proxy object.

A: Also, see here: Manually Loading the Factory Extension into the Ninject Kernel
Under some circumstances it may be necessary to manually load the extension. The solution in my case was to add the following code during kernel construction:
if (!kernel.HasModule("Ninject.Extensions.Factory.FuncModule"))
{
    kernel.Load(new FuncModule());
}

A: Why this was happening is specified here: http://kozmic.net/2009/03/20/castle-dynamic-proxy-tutorial-part-viii-interface-proxy-without-target/
Krzysztof explains that you Castle can resolve even an interface, and Windsor will create a class for you. However if you want to use an interceptor and call a invocation.Proceed() method you need to specify what happens inside that method (for ex. using lambda expression)
Solution:
In my case solution was to put all installers into one, except of the interceptor installer. That one could stay alone, and eveything was fine.

A: If you have this problem by Update method so change it like this :
 var myObj = _dbContext.Set<T>().Find(entity.Id);
 _dbContext.Entry(myObj).CurrentValues.SetValues(entity);
_dbContext.SaveChanges();


Q: Generic class factory or method of hierarchy objects I have hierarchy  class and generic class:
       public class Form
       {
           public string Name { get; set; }
           public string Producer { get; set; }
       }

       public class Book : Form
       {
           public string Topic { get; set; }
           public string Autor { get; set; }
       }

       public class Copybook : Form
       {
           public string Topic { get; set; }
           public int CountPages { get; set; }
       }

       public class Notebook : Form
       {
           public int Cost { get; set; }
       }

       public class Request<T> where T : Form
       {
           public T Form { get; set; }
       }

I want to make factory or method, which will create objects of generic class in depend of logic and params. How it make? I tried to do this, but the code did not work:
        public enum FormParams
        {
            Book,
            Copybook,
            Notebook
        }

        public static class RequestFactory
        {
            public static Request<Form> Create(FormParams formParams)
            {
                if (formParams == FormParams.Book)
                {
                    return new Request<Book>();
                }

                if (formParams == FormParams.Copybook)
                {
                    return new Request<Copybook>();
                }

                return new Request<Notebook>();
            }
        }

A: If you think carefully, what you're asking for doesn't really make sense. What if you did this?
var request = RequestFactory.Create(FormParams.CopyBook);
request.Form = new Book();

If the underlying type of request was Request<CopyBook>, then its Form property would have the type of CopyBook, and trying to set its value to a Book wouldn't make sense.
If you determine that the above use-case should never happen, you can formalize that fact by using an interface that doesn't allow the Form property to be set. Then you can make that interface covariant.
public class Request<T> : IRequest<T>
    where T : Form
{
    public T Form { get; set; }
}

public interface IRequest<out T> where T : Form
{
    T Form { get; }
}

...
    public static IRequest<Form> Create(FormParams formParams)

But in that case you may find there's no reason to have IRequest be generic at all.
public class Request<T> : IRequest
    where T : Form
{
    public T Form { get; set; }

    Form IRequest.Form => this.Form;
}

public interface IRequest
{
    Form Form { get; }
}

...
    public static IRequest Create(FormParams formParams)

A: You need to add an Interface to your hierarchy so you can flag the generic parameter as covariant.
public class Request<T> : IRequest<T> where T : Form
{
    public T Form { get; set; }
}

public interface IRequest<out T>
{
    public T Form
    {
        get;
    }
}

And then you need to change the return type of your Create method to an IRequest<Form>.
public static class RequestFactory
{
    public static IRequest<Form> Create(FormParams formParams)
    {

        if (formParams == FormParams.Book)
        {
            return new Request<Book>();
        }

        if (formParams == FormParams.Copybook)
        {
            return new Request<Copybook>();
        }

        return new Request<Notebook>();
    }
}


Q: Varnish VCL "Symbol not found: std.querysort" I am copying some VCL rules from this handy template and running on the latest stable Varnish4. However this section of the VCL:
vcl 4.0;

sub vcl_init {
    # ...

    # Normalize query arguments
    set req.url = std.querysort(req.url);
}
                  ^

Returns this error:
-- Logs begin at Tue 2016-03-15 10:44:31 UTC, end at Tue 2016-03-15 13:02:10 UTC. --
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Message from VCC-compiler:
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Symbol not found: 'std.querysort' (expected type STRING_LIST):
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: ('/etc/varnish/test.vcl' Line 55 Pos 23)
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: set req.url = std.querysort(req.url);
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: ----------------------#############----------
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Running VCC-compiler failed, exited with 2
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: VCL compilation failed

Should I include a mod or define std somehow?

A: Yes! I stumbled on the answer inside another answer. Adding import std; at the top of the script stopped the error.
vcl 4.0;
import std;

sub vcl_init {
    # ...

    # Normalize query arguments
    set req.url = std.querysort(req.url);
}


Q: Declare Variable Character Length My table is shown below:

Name
Depth
IsFile

GMES9604U 1.10 770 CFM-2135.csv
1
1

When I declare my variable, only part of the Name is stored:
declare @filename222 varchar(max)

SET @filename222 = CAST((
    SELECT Top 1 Name
    FROM #MyFiles
) AS Varchar)

print(@filename222)

Result Messages:
GMES9604U 1.10 770 CFM-2135.cs

I was wondering how can I get the entire Name as my variable. Thanks!

A: Why are you casing to a varchar?  In SQL Server, you should never use string declarations without a length.  But the explicit cast is unnecessary.
Just use:
SELECT Top 1 @filename222 = Name
FROM #MyFiles  ;

The default length of varchar -- when used without a length -- depends on the context.  You could use an explicit cast(), but you would use varchar(max).

A: What is the name column in your table defined as?  Is it also VARCHAR(MAX) or is it defined as VARCHAR(<some number>)
If you already have the value in a table then the variable should be declared as the same data type and then you will never have a truncation issue.
Your issue is likely to be stemming from the fact that the default when no value is added for a VARCHAR declaration will be either 1 or 30 (see https://sqlblog.org/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length)


Q: Vue component Data not working in bootstrap modal I have a Vue Component which I reuse on the same page. I use a bootstrap 4 modal in the component. My problem is when I update the component data in the bootstrap modal, the data bind is not working properly when I reuse the same component in the view page.
Here is my component:
<template>

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#test">
      Launch demo modal
    </button>

Modal title

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

            <button @click="filterHistory">Add</button>
            <button @click="closeFilter">Remove</button>

{{filter}}

</template>

And here I reuse it in a view page:
<template>

     <Test></Test>
     <Test></Test>

</template>

The value of filter, which is a boolean expression, is only updated in the component declared first. So the data binding fails... Has anyone come across this? Or know how to resolve it?


Q: Android Studio- Attempt to invoke interface method 'android.graphics.Canvas android.view.SurfaceHolder.lockCanvas()' on a null object reference Very much a newbie to Android Studio and StackOverflow, so please forgive me in advance.
I've tried to make a simple android program that outputs its own framerate.
When I run it I get this error:
Attempt to invoke interface method 'android.graphics.Canvas android.view.SurfaceHolder.lockCanvas()' on a null object reference

I'm fairly certain this is the problem area for the program:
while(running){
        startTime=System.nanoTime();
        canvas=null;
        try{
            canvas=this.surfaceHolder.lockCanvas();
            synchronized(surfaceHolder){
                this.gamePanel.update();
                this.gamePanel.draw(canvas);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally{
            if(canvas!=null){
                try{
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }catch(Exception e) {
                    e.printStackTrace();}
            }
        }

I've copied it directly from this tutorial: https://www.youtube.com/watch?v=OojQitoAEXs    and as far as I can tell I copied it line for line. Do you know how I can fix this error?

Here is the whole program if it helps (sorry for the dump):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new GamePanel(this));
    }
}

import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.MotionEvent;
import android.graphics.Canvas;
import android.content.Context;
import java.lang.Thread;

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
    private MainThread thread;

    public GamePanel(Context context){
        super(context);

        getHolder().addCallback(this);

        thread=new MainThread(getHolder(), this);
        setFocusable(true);
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){

    }

    public void surfaceCreated(SurfaceHolder holder){
        thread=new MainThread(getHolder(), this);
        thread.setRunning(true);
        thread.start();
    }

    public void surfaceDestroyed(SurfaceHolder holder){
        boolean retry=true;
        while(true){
            try{
                thread.setRunning(false);
                thread.join();
            }catch(Exception e){
                e.printStackTrace();}

            retry=false;
        }
    }

    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    public void update(){

    }

    public void draw(Canvas canvas) {
        super.draw(canvas);

    }

}

import android.view.SurfaceHolder;
import android.graphics.Canvas;

public class MainThread extends Thread {
    public static final int MAX_FPS = 30;
    private double averageFPS;
    private SurfaceHolder surfaceHolder;
    private GamePanel gamePanel;
    private boolean running;
    public static Canvas canvas;

    public void setRunning(boolean running){
        this.running=running;
    }

    public MainThread(SurfaceHolder surfaceholder, GamePanel gamepanel){
        super();
        this.surfaceHolder=surfaceHolder;
        this.gamePanel=gamePanel;
    }

    public void run(){
        long startTime;
        long timeMillis=1000/MAX_FPS;
        long waitTime;
        int frameCount=0;
        long totalTime=0;
        long targetTime=1000/MAX_FPS;

        while(running){
            startTime=System.nanoTime();
            canvas=null;
            try{
                canvas=this.surfaceHolder.lockCanvas();
                synchronized(surfaceHolder){
                    this.gamePanel.update();
                    this.gamePanel.draw(canvas);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }finally{
                if(canvas!=null){
                    try{
                        surfaceHolder.unlockCanvasAndPost(canvas);
                    }catch(Exception e) {
                        e.printStackTrace();}
                }
            }
            timeMillis=(System.nanoTime()-startTime)/1000000;
            waitTime=targetTime-timeMillis;
            try{
                if(waitTime>0){
                    this.sleep(waitTime);
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
            totalTime+=System.nanoTime()-startTime;
            frameCount++;
            if(frameCount==MAX_FPS){
                averageFPS=1000/(totalTime/frameCount)/1000000;
                frameCount=0;
                totalTime=0;
                System.out.println(averageFPS);
            }
        }
    }
}

A: you need to change the following line
 canvas=this.surfaceHolder.lockCanvas();

to
 canvas=surfaceHolder.lockCanvas();

for simple reason. Scope of the variable


Q: Python Stock Portfolio Rebalancing based on Factors (excel Solver imitation) Would like to calculate optimal weights and stock combo to add to portfolio to minimize certain exposures.
For example, I have below portfolio of stocks with stock sensitivity to 5 factors and sumproduct to get total portfolio sensitivities.

I want to pull the right combo of stocks from below list to minimize the difference in sensitivities between the portfolio and benchmark. The addition would need certain constraints such as: WGT cannot be negative, SUM of WGT have to equal to 1, each ticker cannot have WGT exceed 20% (0.2)

The list of stocks are narrowed down to 5 for example purposes.
What would be the best way to go about coding this in python?


Q: C++ aligned unaligned property of arrays EDIT:This is from a working project of mine. Working.
I declared some char arrays at the beginning of .cpp file(even before the #include parts). Then i could use these arrays with "instructions for 16-Byte aligned variables".
Question: what happens if i use this .cpp file in another .cpp file as an include? Could i use that arrays for aligned operations in another projects too?
Question-2: is there a short-cut for this? I dont want to place all my variables in the beginning.
Some of the code:(i worked on some 16-Byte-aligned arrays)
    //I put these arrays at the beginning, so they are aligned
//for the movaps instructions(x2 speed for reading and writing memory)
float v1[16];
float v2[16];
char counters[32];
char array_of_ones[32];
char source_array[4096];
char destination_array[4096];
struct bit_field
{
    bf1:32;
    bf2:32;
    bf3:32;
    bf4:32;
}some_area;
struct bit_mask_x
{
    bf1:32;
    bf2:32;
    bf3:32;
    bf4:32;
}some_mask;
float var_fast[16];
char alignment_purge[5];    //for the unalignment tests
char unaligned_source_array[4096];
char unaligned_destination_array[4096];

#include <math.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
.....
.....

What happens if i include this program in another like this:
#include <math.h>
#include<my_aligned.h> <-------- or my_aligned.cpp
#include<stdio.h>
#include<time.h>

Do i have to use a .h file for this?
Thanks...

A: Have you actually tried if this aligns your variables correctly? When you compile, the executable always has a header whose size may not be a multiple of 16. Also, alignment_purge may not really get the variables following it out of alignment, because the compiler may add padding. Finally, the headers don't introduce variables, so if you put your variables above or below headers, that doesn't change anything.
You can take a look at this question to see how  to request aligned memory.
As a side note, normally you wouldn't want to include source files into another file. See this question on this subject.

A: Putting variable declarations at the top of a file is not required to enforce any specific alignment. You may just be getting lucky here, or it may be an idiosyncrasy of your compiler.
If you're using gcc, you can use the aligned attribute to request the correct alignment - other compilers probably have equivalent extensions or #PRAGMAs.
eg. your variable declarations with gcc's extension would look like:
float v1[16] __attribute__ ((aligned (16)));
float v2[16] __attribute__ ((aligned (16)));

If you need it to be entirely portable, I think your only solution is to dynamically allocate a large block of memory, and then manage the alignment of allocated blocks within it yourself.

Note that the alignment only needs to be enforced where the variables are actually stored, in the .cpp file.  You can just forward declare them in a header, and that will let you refer to them in your other files.  #includeing the .cpp file is not only unnecessary, it will cause a link error as every file has its own copy of the variables with the same names.

OP is using Digital Mars (if you'd mentioned this right away, I would have looked it up).
Searching for digital mars alignment, the first hit is the pragma documentation. I looked at align first, and it referred me to pack.
Using this, your code would look like:
#pragma pack(push, 16)
float v1[16];
float v2[16];
// ... any other aligned variables defined here
#pragma pack(pop)

However, pack affects the alignment of members inside structures - it's not clear what it does for global variables.
I think, to be certain, you need to write an aligned allocator: start by searching _aligned allocation C++` for example, and post a dedicated question if you can't figure it out.


Q: Does scoping in julia 1.0.0 with for-loops make sense to beginners? In julia 1.0.0, I get the following for-loop scoping behavior:
julia> counts = 0
0
julia> for i in 1:10
       counts += 1
   end
ERROR: UndefVarError: counts not defined

I found the solution was to make the counts variable global inside the for loop.
julia> for i in 1:10
           global counts += 1
       end
julia> counts
10

However, as a newcomer to julia this behavior almost made me quit the language because it seems so different from other languages.
Now that I see the solution above, I wonder if this is intuitive to beginning julia users.  It was not intuitive to me, though I was finally able to solve it after quite a bit of time.
Here is the confusing part.  I thought making a variable global when it was initialized would solve the problem.  It does not:
julia> global c = 0
julia> for i in 1:10
           c += 1
       end
ERROR: UndefVarError: c not defined

It would seem natural that the global scope of c above would flow down into the for-loop, but the first initialization of c in the for-loop apparently creates a different for-loop local c.
Does this make sense to experienced julia developers?

A: I think there is agreement that, for interactive usage, this behavior is not optimal and it is likely going to change to the expected behavior in the REPL, IJulia etcetera soon. You can find the discussion here: https://github.com/JuliaLang/julia/issues/28789
Note, however, that everything works as expected once you wrap it into a local scope, such as a function or a let block for example.
See my answer here: Scope of variables in Julia for some more information/references.


Q: Twilio 11200 errors in sms status callback We are using node.js to send SMS to customers, and recently added the status callback to log sent and delivered statuses.  We are also now seeing a ton of 11200 errors in our Twilio logs on calls that apparently were successful.  Looking at the debugger, I see this in the response body:

Twilio was unable to fetch content from:
  https://api.mycompany.com:443/api/1.0/sms/response Error: Error
  reading response: Response does not contain content type

and the message text has:

Msg   "Request to StatusCallback URL was unsuccessful."
  httpResponse  "502"

On our side, the handler for /api/1.0/sms/response takes the MessageSid sent with the response, matches it to one in the database, then looks at the MessageStatus.  For "sent" it logs the current time in a sent field and saves it back to the database, likewise for delivered.  At the end, it just does a res.end() as shown in the node.js example.
Here's the code:
app.post('/api/1.0/sms/response', function(req, res) {
    var post_id = req.body.MessageSid || "";
    var status = req.body.MessageStatus || "";
    var item = Item.create(globals);

    if (post_id === "") {
        globals.logger.error(moduleName, "POST sms/response", "Missing MessageSid: " + JSON.stringify(req.body), true);
        res.end();
        return;
    }

    item.loadFromPostId(post_id).then(function() {
        if (status.toLowerCase() === "sent") {
            item.sent = new Date();
        }
        else if (status.toLowerCase() === "delivered") {
            item.delivered = new Date();
        }

        item.save().then(function() {
           res.end();
        });

    });
});

Looking at a couple of the errors, they are when Twilio is trying to send a "delivered" status to us.  Checking our database for the MessageSids from these errors, the matching item has a timestamp in the "delivered" column, so it made it all the way through the code to the save.
We also have nothing but 200 responses in our nginx log (which we are using in front of node) for this endpoint, no upstream timeouts and no 502s.  So I don't know where this error is coming from, or how to get rid of it.
And yes, we should be handling undelivered, etc., but this was just a quick pass at getting some responses in.

A: Twilio developer evangelist here.
First up, you have nothing to worry about here. As you say, you are receiving the callbacks and doing what you need to. You probably want to stop the debugger icon flashing at you in your Twilio console though.
From what I can see, this is a small oversight in the case of the Node.js example that you linked to.
Just calling res.end() closes the stream. It appears that if nothing else has been set, this means the response will get a status code of 200 and no body. While Twilio doesn't expect a response to callbacks like this, it seems it still wants to know something happened.
The error message says that the response didn't have a content type. You can remedy this by setting a content type on the response by calling res.set('Content-Type', 'text/plain') before you call res.end() and that seems to please the Twilio HTTP client.
Alternatively, you can use the express response method sendStatus to set the status and content type of the response in one call. Just call res.sendStatus(200) and the response will be set to text/plain, the status will be 200 and there will be a body of "OK". The Twilio HTTP client will happily accept all of that.
I recommend you change your calls to res.end() to res.sendStatus(200) and I'm going to go fix that in the Node.js example too.

A: You should respond with HTTP status code 204:
res.status(204).end();

The 204 status is still a success, like 200, but specifically means you are not sending any content back (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
Note that the following also works, and doesn't need the end():
res.sendStatus(204);


Q: Insert into else update from array Hoping someone can point me in the right direction with this as i'm not able to get this working.
This is what happens:
My client uploads a (Rightmove) .blm file to server, Script unpacks the zip file and using a parser gets the properties into an array.. From here I'm able to INSERT into the database no problem however, i need this to update information in the database if exists otherwise insert as the blm file may contain New properties or existing ones editted.
The blm file only contains property information, there is no id etc so once inserted into the database i give it an id (propid) by means of auto incriment.
Please view the code below and hopefully you may have a suggestion that i could use to get this doing what i need it to do :)
foreach ($rmdata as $key => $properties) {

$fields = array();
$values = array();

foreach ($rmdata[$key] as $field=>$value) {
if (!isset($value)) {

}

if (isset($value)) {

$sql_props = mysql_query("SELECT propid FROM epsales");
 while($row = mysql_fetch_array($sql_props)){
     $propid = $row["propid"];
}

$fields[] = $field;
$values[] = "'".$value."'";

$array1 = array($field);
$array2 = array($value);

$sqlupdate = array_combine($array1, $array2);

foreach ($sqlupdate as $field=>$value) {
        $sql_update = "$field='$value', ";
}
}
}

$sql_fields = implode(', ', $fields);
$sql_values = implode(', ', $values);

$sqlPropInsert = mysql_query('INSERT INTO epsales ('. $sql_fields .') VALUES ('.    $sql_values .') ON DUPLICATE KEY UPDATE SET '. $sql_update .'');

Thank you for your time it's greatly appriciated!

A: Several notes:

*

*foreach ($rmdata[$key] as $field=>$value) is the same as foreach ($properties as $field=>$value) in this context

*the whole if(isset($value)) thing can be avoided by starting that loop with if(!$value) continue;

*When you select for the propid, you are selecting every row in the table, surely this is not what you intend to do, since you loop through them all and only every use the last one.

*the section building the update section is flawed in a few ways. The simplest fix is to realize that you can achieve the correct result by re-combining the $fields and $values arrays after the loop (as shown later)

*I can't readily see where you would get the conflict of keys, unless $rmdata will contain a propid if it's an update instead of an insert, or else if there is some other key and it's just being handled without explicitly seeing it in the code, which would be fine.

Below is code which I copied directly from yours and just modified to address these issues:
foreach ($rmdata as $properties) {
  $fields = array();
  $values = array();
  $updates = array();
  foreach ($properties as $field=>$value) {
    if (!$value) continue;
    $fields[] = $field;
    $values[] = "'".$value."'";
    $updates[] = $field . '="'.$value.'"';
  }
  $sql_fields = implode(', ', $fields);
  $sql_values = implode(', ', $values);
  $sql_updates = implode(', ', $updates);
  $sqlPropInsert = mysql_query('INSERT INTO epsales ('. $sql_fields .') VALUES ('.    $sql_values .') ON DUPLICATE KEY UPDATE SET '. $sql_updates .'');
}

note that this technique requires something in the data to have a conflicting key in order for the ON DUPLICATE KEY to trigger. If there is some value in the data array which you can uniquely identify these rows by, that field should be a UNIQUE KEY in the database, which will 'cause this conflict to occur quite nicely.


Q: Mercurial hg status displaying ignored files Can anyone tell me why mercurial is displaying ignored files for the 'hg status' command?
Here's the confirmation that mercurial is indeed ignoring the files:
$ hg addremove
$ hg commit
nothing changed

Now, have a look at the status output. I ran this immediately after the lines above. (Prinout is partial, with identifiable text removed)
$ hg status
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
? Core/target/classes/META-INF/MANIFEST.MF
? Core/target/classes/xxx/yyy/zzz/X.class
? Core/target/classes/xxx/yyy/zzz/XBackup.class
? Core/target/classes/xxx/yyy/zzz/XBackupInput.class
? Core/target/classes/xxx/yyy/zzz/XBackupOutput.class
? Core/target/classes/xxx/yyy/zzz/XImpl$GetResultsAndStatistics.class
? Core/target/classes/xxx/yyy/zzz/XImpl$MonitoringMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl$UpdateMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl.class
? Core/target/classes/xxx/yyy/zzz/XIsFullException.class
? Core/target/classes/xxx/yyy/zzz/XSource.class
? Core/target/classes/xxx/yyy/zzz/XUsageException.class
? Core/target/classes/xxx/yyy/zzz/CheckResults.class
? Core/target/classes/xxx/yyy/zzz/Noise.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator$TemporalMeasure.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator.class
? Core/target/classes/xxx/yyy/zzz/core/LoggingConfigurator.class
? Core/target/classes/xxx/yyy/zzz/core/ManagedIterator.class
? Core/target/classes/xxx/yyy/zzz/core/NetworkUtils.class
? Core/target/classes/xxx/yyy/zzz/core/StackTraceUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Summarisable.class
? Core/target/classes/xxx/yyy/zzz/core/TimingUtils.class
? Core/target/classes/xxx/yyy/zzz/core/XMLStaticStringUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Zipper.class
...

There's something like a thousand lines of these ignored files showing in the status printout; that's some serious guff.
How can I get rid of this?
Thanks
UPDATE:
Here's my .hgignore file.
syntax:glob
.metadata*

syntax:regexp
^target.*$
^[^/]*/target.*$
^[^/]*/[^/]*/target.*$
^bin.*$
^[^/]*/bin.*$
^[^/]*/[^/]*/bin.*$

UPDATE:
Modified regexps a wee bit * -> .*

A: Your regexp syntax is wrong.  You have this:
syntax:regexp
^target*$

which means "ignore anything beginning with target and ending with an asterisk
Which fails to ignore these:
Core/target/classes/META-INF/MANIFEST.MF
Core/target/classes/xxx/yyy/zzz/X.class

for two reasons -- they begin with Core/ not target and they don't end with an asterisk.
What you probably meant was this:
syntax:regexp
^.*/target/.*$

which matches anything that has /target/ in it (notice it's .* in a regexp * is for glob style).  However the ^ and $ only serve to root your regex and you don't want it rooted -- you want to find it anywhere in the string, so just do this:
syntax:regexp
/target/

The clue in all this was that the files were marked with ? which means not ignored and not added, if they were ignored you wouldn't see them at all without adding --ignored to the status command.

A: I got similar issue because I changed letter case for some files. So previously I got file called "sitenav.ext", renamed it to "siteNav.ext" and started to have same sort of issues - when I tried to "hg st" I got "? siteNav.ext".
Fix was easy
rename to "_siteNav.ext",
addremove,
commit,
rename back to "siteNav.ext",
addremove,
commit -> profit!

A: As commented by Jerome in the question, providing your config might help.
One (admittedly strange) reason for your problem could be a permission issue with the .hgignore file combined with exclude defaults for the addremove command.
I could reproduce your situation by revoking any read permission from the ignore file and by using -X "**/target/**" as a default option for the addremove command (which might be set in any of the possible Mercurial configuration files):
$ hg st
# no output, as expected
$ chmod 000 .hgignore
$ hg addremove # with '-X "**/target/**"' set as default somewhere
$ hg commit
nothing changed
$ hg st
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
...

hg fails in reading the ignore file and thus does not know that the target stuff should be ignored. A corresponding warning from hg would be helpful here.
This question has been updated in response to Jerome's comment.

A: Many thanks for everyone's help on this. I haven't found an answer to the problem but I did find a workaround that got rid of it. So I'm assuming that at some point when modifying the hgignore regexps mercurial got confused and corrupted it's internal data... or something. I don't know enough internals to know what this could have been.
Anyway, should you find yourself in the same boat, here's what I did:

*

*Make sure your .hgignore file says what you want it to and that all the files turning up in the hg status are the ones you want to ignore.

*Add all the files to be ignored. hg addremove doesn't work because it does honour the hgignore contents, so I used Eclipse's hg plugin and did each file manually (well, I selected them all and Eclipse applied the add to them all individually).

*Revert all added files. I used the following because I'm on linux. (thanks to another poster on a separate question here on SO - which I can now no longer find unfortunately)
hg status -an0 | xargs -0 hg revert

*repeat the above step until it no longer works. In my case this was sometimes up to as many as 3 reverts in a row! (No idea what it was actually doing though :( )

*commit

You should now no longer see the ignored files in the hg status output.
I'm sorry, I have no idea why this worked, or what the original problem was. If anyone does, I'd be very interested to know your thoughts.
Many thanks again to everyone :)

A: ? does not mean ignored.
It just means that mercurial is not tracking the file.
If you don't want to see them just do
hg status -mard
i.e. only show modified, added, removed, deleted

A: Your .hgignore file says "^target" is ignored, but the files are in Core/target. So the ignore line should rather be "target" (without the ^) or "^Core/target".
Or am I missing sth here?
(Note: ^ implies that regex matching starts from the beginning of the path, i.e. only paths starting with target would be matched!)

A: Had the same problem and Bob's answer did the trick for me.
If you are using TortoiseHg you can select "edit ignore filter" in the context menu (windows) to verify and change your .hgignore settings there.


Q: AS3 - Show splash screen until all is code is loaded I am developing an adobe air mobile app and after I launch it, if I click the buttons right away, the sound does not play. If I wait a few seconds, the buttons function normally. How do I have a movie clip/splash screen show on top until all is loaded so I don't have this problem? thanks for your help.

A: Are your sounds embedded in the app or are you loading them at runtime? I assume embedded, but in that case it shouldn't take time before they are available.
If loading sounds at runtime, just respond to Event.COMPLETE to hide your splash screen. Or use setTimeout with a suitable delay if you have no events to respond to:
//wait 5000ms
setTimeout(hideSplashScreenFunction, 5000);
....
function hideSplashScreen():void
{
    //hide splash screen
}

A: You can set splashScreenMinimumDisplayTimeproperty you can achieve. Like this
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
            splashScreenImage="@Embed('assets/icons/chrome/logo.png')"
            splashScreenMinimumDisplayTime="4000" splashScreenScaleMode="none">

Hope it will help you.


Q: woocommerce product with multiple categories, active category in sidebar I need some food for thought on this because I have had trouble finding a decent solution here.
There is a woocommerce shop, categories on the left side (sidebar) and on the right side products. A product can have multiple categories; for example, the product "Burger" is in the categories "Food" and "Fastfood".
Now on the left side we have the categories "Food" and "Fastfood" with both "Burger" in them.
I go to category "Food". On the left side in the sidebar I highlight the category food with:
(start loop going through categories)

 if(get_query_var('product_cat') == $cat->slug) - echo

 else - echo

(end loop)

so the category "Food" is highlighted. Then I select the product "Burger".
Now, because the product "Burger" is also in the category "Fastfood", the category "Fastfood" is displayed as active.
The active category should be based on the category that the product was selected from originally ("Food"). If you go to the category "Fastfood" and select "Burger", then "Fastfood" should be active. Open "Burger" from "Food", "Food" should be the active category.
My attempt is to change the category in the permalink (<?php the_permalink(); ?>) to the current category when displaying all the products, but it just doesn't feel like the right way.
Maybe someone has a better solution.
Wish you a good day!

EDIT:
I've managed to create the permalink with the right category:
$custom_permalink = get_settings('siteurl')."/".get_query_var('product_cat')."/".basename(get_permalink());

Sadly this does not work.. (redirects me to the "wrong" category) but I don't like this hack anyways :)..

A: I got it working. This is what I did:
In your custom template file /yourtheme/woocommerce/content-product.php you will change the a href.
Code that generated the new permalink (using the current selected category):
    // HOOK FOR CORRECT ACTIVE SIDEBAR ELEMENT WHEN PRODUCT HAS MULTIPLE CATEGORIES
    if(get_query_var('product_cat') == ""){
        $product_categries = get_the_terms( $post->ID, 'product_cat' );
        foreach ($product_categries as $category) {
            $cur_cat = $category->slug;
        }

        $custom_cat = $cur_cat;
    }else{
        $custom_cat = get_query_var('product_cat');
    }

    $custom_permalink = get_permalink(5).$custom_cat."/".basename(get_permalink());

I also check if a category is set (because there is none if you are viewening "All Products", in this case I loop through the Products and get their category to use it in the permalink).
The get_permalink with the id 5 is basically my shop-page, so it stays dynamic when you change the permalink from your shop. Don't like hardcoded stuff here because it's already an ugly hack.
Place this code before the a href that wraps your Product, in my case this was on line 42 (Woocommerce V2.0.10).
Then change this a href from
<a href="<?php the_permalink(); ?>">

to
<a href="<?php echo $custom_permalink; ?>">

I hope this will help you when you face the same issue!


Q: Re-design suggestions for the attached code segment My program needs to run like this:
./myprogram inputType [Can be I1, I2 or I3]

Most of the functions of this program are like:
void Foo::foo (IType inputType) {
    // Some common code
    if (inputType == I1) ... // some I1 specific code
    if (inputType == I2) ... // Some I2 specific code
    ...// similarly for I3
}

These checks of inputType are scattered over multiple places and with time have became increasingly difficult to manage. I have thought of refactoring this code to something like :
InputType* iType = new InputTypeI1(); // or I2 or I3

void Foo::foo (IType inputType) {
    // Some common code
    iType.DoSomething(this, arg1, arg2,..)
}

class InputType1 : public InputType
{
     // Virtual functions.. (with default implementations)
}

InputType1::DoSomething(Foo* f, Arg1* arg1, Arg2* arg2)
{
    f->DoSomethingFor1(arg1, arg2);
}

This results in organizing things for I1, I2 or I3 as well as automatically call relevant function based upon the input type.
However, I feel this could be done better. Any suggestions?

A: Difficult to tell from the snippet you provide, but I'd consider having three derived foo classes, FooI1, FooI2 and FooI3, and constructing the appropriate one with a factory based on InputType.
Then all the specializations just get implemented in virtual methods for each of the new classes.
class FooI1: public Foo {
 void doSomething() {...};
}

ditto for I2/I3..
Foo * fooFactory(InputType iType)
{
   return new FooX - depending on iType
};
Foo *f = fooFactory(i)

f->doSomething();

A: your current code couples Foo and InputType:
  1. Foo creates InputType Object
  2. InputType calls Foo function

Suggested solution is:
 1. Decouple InputType and Foo by using composites mode
    Foo could hold a pointer to `InputType*` then call InputType `virtual` function.
 2. To make InputType, a factory will simple enough.

Sample code:
class InputType
{
 public:
    virtual ~InputType();
    virtual void DoSomething();
};

InputType* MakeInputObject(const IType& inputType)
{
   return new InputTypeX;
}

class Foo
{
public:
  Foo(const InputType& input) : input_type_ptr(MakeINputObject(input) {}
  void DoSomething() { input_type_ptr->DoSomeThing(); }

private:
  std::unique_ptr<InputType> input_type_ptr;
};


Q: What happens after modifying Kafka topic replication factor? According to the docs, you just modify a topic to increase the replication factor.
 > bin/kafka-topics.sh --zookeeper zk_host:port/chroot --create --topic my_topic_name
       --partitions 20 --replication-factor 3 --config x=y
Unfortunately, it doesn't specify what happens then after you modify the topic. Do existing log segments get replicated to the new replicas, or only new messages?

A: For kafka 10 you need to invoke the kafka-reassign-partitions.sh script to change the replication factor of the topic.
Here is a demo of a script that will display the topic before and after the change:
updateTopicReplication() {
    TOPIC_NAME=$1
    REPLICAS=$2

    echo "****************************************"
    echo "describe $TOPIC_NAME"
    bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic $TOPIC_NAME

    JSON_FILE=./configChanges/${TOPIC_NAME}-update.json
    echo $JSON_FILE
    [ -e $JSON_FILE ] && rm $JSON_FILE

    touch $JSON_FILE

    echo -e "{\"version\":1, \"partitions\":[{\"topic\":\"${TOPIC_NAME}\",\"partition\":0,\"replicas\":[${REPLICAS}]}]}" >> $JSON_FILE

    echo "****************************************"
    echo "updateing $TOPIC_NAME"
    bin/kafka-reassign-partitions.sh --zookeeper localhost:2181 --reassignment-json-file $JSON_FILE --execute

    echo "****************************************"
    echo "describe $TOPIC_NAME"
    bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic $TOPIC_NAME
}

A: It seems that kafka actually doesn't support increasing (or decreasing) the replication factor for a topic, according to the same docs I mentioned in the question.


Q: Unit Testing for the following : Tring to set up a unit testing for the following code, but I keep getting this:  Comparing two different types of values. Expected string but received undefined. as an error
 Test :

     import {prepadSigned} from './utils';

  describe('prepadSigned', () => {test('should prepend `00` to the input      <', () => {
  const str = '-10';
  const actual = prepadSigned(str);
  const expected = '00-10';
    expect(actual).toEqual(expected);
    })

Code:
function prepadSigned(hexStr) {
  const msb = hexStr[0];
  if (msb < '0' || msb > '7') {
    return `00${hexStr}`;
  }
  return hexStr;
}

I expect a unit test to pass with some input/output.
I keep getting the following :
expect(received).toEqual(expected)

Expected value to equal:
  "00-10"
Received:
  undefined

A: Unless you deliberately left out export when you wrote,
changing
function prepadSigned(hexStr) {
...
}

to
export function prepadSigned(hexStr) {
...
}

may fix the problem.


Q: Task. How to find out the amount that will remain on the user's wallet after js purchases There are three arrays, the data comes from the back-end and we do not know exactly which names or products will come, we need to calculate how much the user has spent and how much he has left in his wallet. It should be borne in mind that when the user does not have enough money, he can use a loan, this money will go to his wallet additionally.
I tried to solve through a huge number of loops, going through each array and comparing the values, but I need a solution with the algorithmic complexity On.
    var product = [
    {'name':'пряник', 'price':10},
    {'name':'кофе', 'price':2},
    {'name':'мороженное', 'price':4},
    {'name':'макароны', 'price':5},
    {'name':'персик', 'price':6},
    {'name':'ананас', 'price':15},
]
var purse = [
    {'name':'Катя', 'cash':100},
    {'name':'Даня', 'cash':200},
    {'name':'Ваня', 'cash':400},
    {'name':'Саня', 'cash':500},
    {'name':'Маня', 'cash':600},
    {'name':'Кира', 'cash':150},
]

var purchases = [
    {'name':'Катя', 'item':'пряник'},
    {'name':'Даня', 'item':'макароны'},
    {'name':'Даня', 'item':'кофе'},
    {'name':'Даня', 'item':'кофе'},
    {'name':'Маня', 'item':'ананас'},
    {'name':'Катя', 'item':'мороженное','credit': 20},
]

A: Maybe something like this would help? I briefly considered merging the objects into one big set of objects that had all the information, which would make it easier to format. However, I decided instead to re-lookup the information on each loop. This should be a good start, I hope it helps!

var product = [
    {'name':'пряник', 'price':10},
    {'name':'кофе', 'price':2},
    {'name':'мороженное', 'price':4},
    {'name':'макароны', 'price':5},
    {'name':'персик', 'price':6},
    {'name':'ананас', 'price':15},
];
var purse = [
    {'name':'Катя', 'cash':100},
    {'name':'Даня', 'cash':200},
    {'name':'Ваня', 'cash':400},
    {'name':'Саня', 'cash':500},
    {'name':'Маня', 'cash':600},
    {'name':'Кира', 'cash':150},
];
var purchases = [
    {'name':'Катя', 'item':'пряник'},
    {'name':'Даня', 'item':'макароны'},
    {'name':'Даня', 'item':'кофе'},
    {'name':'Даня', 'item':'кофе'},
    {'name':'Маня', 'item':'ананас'},
    {'name':'Катя', 'item':'мороженное','credit': 20},
];

function displayInfo(name, walletVal) {
  const displayArea = document.querySelector("#display");
  const spendSummary = document.createElement("div");
  spendSummary.classList.add("spendSummary");
  const nameEle = document.createElement("div");
  nameEle.classList.add("name");
  nameEle.innerText = name;
  spendSummary.appendChild(nameEle);
  const walletEle = document.createElement("div");
  walletEle.classList.add("wallet");
  walletEle.innerText = walletVal;
  spendSummary.appendChild(walletEle);
  displayArea.appendChild(spendSummary);
}

const names = [...new Set(purchases.map(e => e.name))];
for (const name of names) {
  const filteredPurchases = purchases.filter(e => e.name == name);
  const costs = filteredPurchases.map(
    ({item: itemName}) =>
    product.find(item => item.name == itemName).price
  );
  const creditsArr = filteredPurchases.filter(e => e.credit)
    .map(e => e.credit);
  const totalCredit = creditsArr.reduce((a,b) => a + b, 0);
  const totalCost = costs.reduce((a,b) => a + b, 0);
  const cash = purse.find(e => e.name == name).cash;
  const currentWallet = cash + totalCredit - totalCost;
  displayInfo(name, currentWallet);
}
#display {
  display: flex;
  justify-content: space-around;

  font-family: arial;
}

.spendSummary {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.name {
  box-shadow: 0 2px 2px -2px black;
}
<div id="display">
</div>


Q: How to set default value of select box with non-existed value in Angularjs Maybe this can has duplicated or maybe there's a way to solve this,
but I couldn't find any way to solve this.
So please don't be angry with my silly question and give me some information or way to solve this.
Please see this fiddle.
Set default value of select box
What I want is, when I get array from http call,
how to set default value of select box with the value which is not in array.
I've used ng-init but it didn't work.
I know there are other ways to solve this like using <options> tag and put first value of option or
using selected but I want to use ng-options.
No matter what you give is a link, doc, or something, it'll be great help to me.
I'll wait for your any comments or answers. :)

A: First solution you can add one more option tag for default value
Html Code

        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        <option value=''>Choose Category </option>
        </select>

Controller Code
 var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.resultOpt = '';
}]);

Working code
Second Solution : you just add one more item in your array list after get from http call
Html Code

        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        </select>

Controller Code :
var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.testOpt.splice(0, 0, 'Choose Category');
    $scope.resultOpt = 'Choose Category';
}]);

Working Code
hope this will help you


Q: How to temporarily override import behavior? I am using a module, module_1, that is able to use module_2 if it is installed on the system, but falls back on other implementation if it is not. The way it checks if module_2 is:
# module_1.__init__.py

try:
    import module_2
    _MODULE2 = True
except ImportError:
    _MODULE2 = False

I have module_2 installed in the same environment but I don't want module_1 to use it.
Is there a way to import module_1 but override the import mechanism to make the import of module_2 specifically raise an ImportError?
What I've tried:
import sys
class hide_module_2:
    def __enter__(self):
        class HideModule2(dict):
            def __init__(self, *args, **kwargs):
                self.update(*args, **kwargs)

            def __getitem__(self, key):
                if key == 'module_2':
                    raise ImportError('Module 2 de')
                super().__getitem__(key)
        sys.modules = NoPandas(**sys.modules)

    def __exit__(self, exc_type, exc_value, traceback):
        # revert to regular dictionary
        sys.modules = dict(**sys.modules)

with hide_module_2():
    import module_1

I thought this would work since sys.modules is a dictionary of currently imported modules and I thought it would be referenced in the import.

A: I was able to devise a sort of hacky solution since the import system throws an ImportError if something is imported and sys.modules has a None in it:
class hide_module_2:
    def __enter__(self):
        self.module_2 = sys.modules.get('module_2')
        sys.modules['module_2'] = None

    def __exit__(self, exc_type, exc_value, traceback):
        if self.module_2 is None:
          sys.modules.pop('module_2')
        else:
          sys.modules['module_2'] = self.module_2

with hide_module_2():
    import module_1


Q: RocketMq:how can get RocketMQ topic and tags using Api How can I get all the tags in the topic of RocketMQ

A: it seems cannot be done for now.
when consumeing the topic, consumers would get all tags

A: Tags are only stored in messages, there is no global place to store all tags of a topic, so only consumers can specify tags for filtering and consumption

A: You can't! Since there are no ways to save all tags in the broker.
Actually, you need not know all the tags when you consume. You should only care about the tag you know. If there are some tags that a consumer does not know, which means the messages with that tag should not be consumed by it.


Q: iphone sdk 4.3 - Skip through a list of images by using accelerometer Firstly, I wanted to say hello to the community. I have been a passive reader for a couple of weeks and have to say that stackoverflow is a great resource to learn. Recently, I am playing around with developing small iphone apps for myself in order to learn more about the SDK.
I'm getting familiar with the basic functions right now. One of my first projects was to skip through a list of images by using my finger. I am wondering now if this is possible with the motion sensor/ accelerometer as well.
Let's assume I have 4 distinct images (image1, image2, image3, image4). I want to display the image on my iphone and show the next or previous image by tilting my iphone to the right and left.
How would I start doing that? I am not sure if this is even possible.
Thanks for your help. Have a great day
Rachel

A: You can use an UIScrollView (what you assumably already did for touch control) and control it using acceleration.
In
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

See UIAccelerometer and UIScrollView here on StackOverflow.


Q: find duplicate 1kb chunks from a file TL;DR: How to identify duplicate non overlapping 1kb chunks from a file which is large and can be binary file too?

I recently came across this question in one of the challenges.
 We are given a file name. This file's size will be in multiples of 1kb. We have to perform dedup operation on this file and write the modified content in another file. The dedup operation finds and removes the duplicate, non-overlapping 1kb chunks from the file. The file can be very large file and it can also be a binary file.
 The second part of the question involved reversing the dedup operation and regenerating the original file from the deduped file.
 My approach: I tried to use hashing as suggested in Adam Horwath's this blog. I calculated hash of each 1kb byte of data and stored it in a hashtable with hash as key and index of the chunk in consideration as value. here is my code to calculate the hash for 1kb of data (similar to inithash in the blog):
//implement hashing used in Rabin-Karp algorithm
// sum of p^n * a[x]
//hconst = 69069; //good multiplier for mod 2^32;
 public static long  calculateHash(int [] data, int chunkSize){
    long hash = 1;
    for(int i =0; i < chunkSize; i++)
    {
        int c = data[i];
        hash *= hconst; //multiply with const
        hash += c; //add the byte to hash
    }
    return hash;
}

There is something wrong (obviously) with my understanding or implementation that it didn't give the correct result. My questions are:

*

*Is the hashing approach correct to identify duplicate chunks?(Comparing each byte is costly process)

*Is there any better way to identify duplicate chunks?

A: Is there a better way than an in-core hash table? Yes. Especially if input files are larger than RAM.
You explained that you have a very large number of 1 KiB documents, a large number of file segments. Pre-process them by reading each segment and writing one line per segment to a temporary segments.txt file containing two columns. First column has a copy of segment contents, or SHA224 hash of contents. Second column has segment index number, which is a serial number starting with zero. Feel free to use just the first few bytes of the hash, depending on your sensitivity to hash collisions.
Now use /usr/bin/sort (out-of-core mergesort) to create segments_sorted.txt. At this point, your problem is trivial. Simply read each line, while remembering previous hash. If cur_hash == prev_hash you have identified duplicate chunks. The associated index lets you rapidly seek() to find the original contents in case ruling out potential collisions is important in your application.


Q: How do you integrate the new Google Sign-In on a Xamarin.Android app? I am attempting to follow Google's instructions on how to add the new Google Sign-In (not the old Google+ Sign-In) to my Xamarin.Android app. For the life of me, I cannot find the correct Google Play Services NuGet package or Xamarin component that supports the new sign-in system.
When I add the following code to the activity, I get "The type or namespace 'GoogleSignInOptions' could not be found. Are you missing an assembly reference?" build error.
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();

Here are the Xamarin.GooglePlayServices NuGet packages that are include in the project:
<package id="Xamarin.GooglePlayServices.Ads" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Analytics" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.AppIndexing" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Base" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Basement" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Identity" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Location" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Maps" version="27.0.0.0" targetFramework="MonoAndroid50" />
<package id="Xamarin.GooglePlayServices.Plus" version="27.0.0.0" targetFramework="MonoAndroid50" />

Is the new Google Sign-In system not yet supported on Xamarin or am I missing something?

A: Enable pre-release nugets and search for:
Xamarin.GooglePlayServices.Identity 29.0.0-beta1

packages.config:
<packages>
  <package id="Xamarin.Android.Support.v4" version="23.1.1.0" targetFramework="MonoAndroid44" />
  <package id="Xamarin.GooglePlayServices.Auth" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
  <package id="Xamarin.GooglePlayServices.Base" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
  <package id="Xamarin.GooglePlayServices.Basement" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
  <package id="Xamarin.GooglePlayServices.Identity" version="29.0.0-beta1" targetFramework="MonoAndroid44" />
</packages>

C# version of Integrating Google Sign-In into Your Android App
SignInButton button = FindViewById<SignInButton> (Resource.Id.sign_in_button);
gso = new GoogleSignInOptions.Builder (GoogleSignInOptions.DefaultSignIn)
    .RequestEmail ()
    .Build ();
mGoogleApiClient = new GoogleApiClient.Builder (this)
    .EnableAutoManage(mLoginFragment, failedHandler)
    .AddApi (Auth.GOOGLE_SIGN_IN_API)
    .Build ();
button.Click += delegate {
    signIn();
};


Q: Why is a Segmentation fault (core dumped) happening in my doubly linked list? So from what I've read from other seg fault errors, it deals with accessing memory you shouldn't have access to (bad memory, or didn't use malloc()). For some reason there is no seg fault error when I make 2 nodes, but anything else gets a seg fault error. If someone one could please explain where I am going wrong in this program that would be extremely helpful. Thanks.
    #include "header.h"
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    int main(int argc, char *argv[]) {

        int N;
        //int oddsonly = (BITS_PER_SEG*2) - 1;
        int NSegs;
        int numOfPrimes;

        if (argc == 2) sscanf(argv[1],"%d",&N);
            else scanf("%d",&N);
            NSegs = (int)ceil(N/(float)odds_only);
            printf("This is the number of segments made: %d\n", NSegs);
        //this is how we make a doubly linked list
        //void makelinkedlist(){
        //this is how we make a doubly linked list
        //void makelinkedlist(){
        int i;
        seg *node;
        seg *current;
        //head = (seg*)malloc(sizeof(seg));
        head = NULL;
        for(i = 1; i < NSegs; i++ ) {
            if(i == 1) {
                node = (seg*)malloc(sizeof(seg));

                node->prev = NULL;
                node->next = NULL;
                head = node;
            }//if
            else{
                current = (seg*)malloc(sizeof(seg));
                current = head;
                while(current->next != NULL){
                    current = current->next;
                }//while
                node = current->next;
                node->prev = current;
                node->next = NULL;
                }//else
            }//for
        printf("Done allocating %d nodes\n",i); '

and my header file has this:
    #ifndef EXTERN
    #define EXTERN extern
    #endif

    #define SIZE_OF_SEG      256       // 256 int per segment
    #define odds_only   16383
    #define BITS_PER_SEG     (8*SIZE_OF_SEG*sizeof(int))

    typedef struct _seg {  /* definition of new type "seg" */
        int  bits[256];
        struct _seg  *next,*prev;
          }seg  ;

    EXTERN int NSegs;

    EXTERN seg *head;             // This variable will point to the
                          // start of the linked list of segments !!!

    //EXTERN void clearAll( );            // Uses head to find the "bit array" (list)
    EXTERN void sieveOfE( int N );      // Uses head to find the "bit array" (list)
    EXTERN int  countPrimes( int N );   // Uses head to find the "bit array" (list)
    EXTERN void printPrimes( int N );   // Uses head to find the "bit array" (list)

A: In your for-loop, in the first iteration head is set to a new node.
In the second iteration, something strange is done:
current = (seg*)malloc(sizeof(seg));
current = head;

Now you've allocated some space, but you have overwritten the pointer to it (this is a memory leak). Afterwards it goes wrong:
while(current->next != NULL){
    current = current->next;
}//while

node = current->next;
node->prev = current;

Here, node is set to NULL so you're writing into the null address, hence the core dump.


Q: How to make a view 100% window height? I'm brand new to react native. I'm trying to figure out how to make a box full height.
I have tried to add flex property to both container and view, but the height is not 100%.
export default class LinksScreen extends React.Component {

  render() {
    return (
      <ScrollView style={styles.container}>
        <View style={{ flex: 1, backgroundColor: '#fff', flexGrow: 1 }}>
          <Text>Hallo</Text>
        </View>

      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    padding: 20,
    backgroundColor: 'blue',
  },
});

A: You need to wrap the ScrollView with a View that has height. ScrollViews must have a bounded height in order to work. You can read more details about that here: https://facebook.github.io/react-native/docs/scrollview
Do it something like below:
render() {
    return (
      <View style={styles.container}>
        <View style={{height: 80}} >
          <ScrollView
            ...

EDIT
Your code actually works. Maybe you just want to see if your scrollview works when the whole screen is occupied. Try this below and you will see, I simply multiplied the text contents 80 times:
render() {
    return (
      <ScrollView style={styles.container}>
        <View style={{ flex: 1, backgroundColor: "#fff", flexGrow: 1 }}>
          {Array(80)
            .fill(1)
            .map((item, index) => (
              <Text>Hallo {index}</Text>
            ))}
        </View>
      </ScrollView>
    );
  }

A: Remove flex:1
Give height:"100%"
      width: "100%"


Q: grep'ing the files output from a previous grep I don't know if this is possible, or if grep is the wrong tool, or what, but what I want to do is this:
grep -rsI "some_string" *.c

Then pipe the list of files where were results were found into a second grep:
grep -rsI "second_string" <list of files from first grep>

I know I can pipe the exact lines to a second grep via:
grep -rsI "some_string" *.c | grep "second_string"

but that's not what I'm looking for, I don't want to just search the lines where previous hits were, but the entire file those lines were in. Is that even possible? Any ideas?

A: Use -l option to list files that match then xargs command to apply grep on those files.
grep -l -rsI "some_string" *.c | xargs grep "second_string"

A: grep -rsIl "some_string" *.c | xargs grep -sI "second_string"


Q: Create XML doc with Linq to XML I have an ASP .Net site where i am attempting to create a page to allow the user to create an XML document. New with XML so I'm not sure if im missing something here but all i am trying to do is create an XML document using Linq to XML.
I saw this example as part of my research
Dim xmlDoc As XDocument = _
<?xml version="1.0" encoding="utf-16"?>
<!-- This is comment by you -->
<Employees>
<Employee id="EMP001">
<name>Wriju</name>
<![CDATA[ ~~~~~~~...~~~~~~~~]]>
</Employee>
</Employees>

xmlDoc.Save("somepath\somefile.xml")

but i just dont seem to be able to get it working in VS 2010 or VS 2013. As soon as i enter <?xml and enter to the next line i just get errors that the syntax is incorrect. Reading further i have seen some C# examples but they dont seem to be "readable" in VB .Net.
I've tried using online converters but again no luck in that either. Could anyone guide me or point me to the right direction to create an XML document with elements etc using Linq to XML? I think i can use XDocument but i'm a little confused if that would allow me to use Linq to XML or if this is an old concept.
Thanks

A: Use this
    Dim xmlDoc As XDocument = <?xml version="1.0" encoding="utf-16"?>
                              <!-- This is comment by you -->
                              <Employees>
                                  <Employee id="EMP001">
                                      <name>Wriju</name>
                                      <![CDATA[ ~~~~~~~...~~~~~~~~]]>
                                  </Employee>
                              </Employees>

    'it assume that /youfolder is in the root and it has read and write permission
    xmlDoc.Save(Server.MapPath("/yourfolder/somefile.xml"))


Q: mailboxer mark message as read Using the rails gem mailboxer
I have just started using it but I see that the SocialStream code base is quite heavy and doesnt provide a simple overview
I'd like to know how to properly work with notifications, so that if a message is sent, the receiver user clicks the message (in part of a conversation) so that it marks the message as read, this in turn will show the sender that the message is read by the receiver
Using the examples I cant seem to get it working. If I use
current_user.mailbox.inbox.unread_messages_count

I seem to get a static number that doenst change, even if I mark all my messages as read
Does anyone have a view on how to do this?
Also how do I empty all messages, conversations, receipts etc

A: As per the Mailboxer readme, I saw this as the recommended way:
current_user.mailbox.inbox({:read => false}).count
I think that should update every time you refresh


Q: AndroidStudio 2.1.1 changes made in xml doesn't get updated on run I am now using AndroidSudio 2.1.1 for my android development.
When I make any changes in xml files (layout , color, string, drawable etc) and then run my app, I don't see any changes in my output.
I have to clean or re-build my project to see the changes made in xml files.
I have already turned off instant-run still no use.

A: You should try to clean and Rebuild the project.
Then go to File/InValidate Caches and Restart and select Restart. It should solve your problem.
I've had the same error and I think this happened because of cache memory store value in Android Studio.

A: Try this button :

Or simlpy do clean , rebuild .


Q: Weighted effect coding in R I have a data set with a categorical variable and a continuous dependent variable, and I want to know the effect of deviation of mean of each category from the overall mean.
str(dat)
'data.frame':   380 obs. of  2 variables:
$ Pgene_3X     : num  0 0 0.08 0 0.048 ...
$ CT           : Factor w/ 22 levels "1:ATG1","10:ATC3",..: 15 15 21 21 21 21 21 21 21 15 ...

As the groups in the categorical variable are not balanced I want to use weighted effect coding in R.
I tried the package "wec".
dat$CTatg1 <- contr.wec("dat$CT",ref="1:ATG1")

But it gives me an error:

Error in contr.treatment(n.cat, base = ref) : not enough degrees of freedom to define contrasts

This function works on the dummy BMI data provided with R but not on my data.
Is there any other way to approach this problem. How can I compare the mean of each "CT" level with the overall weighted mean?

A: I just checked the manual of "wec" package.
I suspect that you may need to replace your argument "ref" with "omitted".


Q: Get averages from a dictionary in Python Get averages from a python dictionary for example if i have the next dictionary:
students={'Dan':(5,8,8), 'Tim':(7), 'Richard':(9,9)}

And i would like to print de dictionary in the next form:
results={'Dan':(7), 'Tim':(7), 'Richard':(9)}

is there any function that i can use? Im new coding in python so dictionaries are a bit confusing for me.

A: If you want that the avg values will be a tuple element (I don't see any reason to do so but maybe I don't have enough context), try:
results={k: (sum(v)/len(v),) for k,v in students.items()}

A: I was trying this but realized we had a problem summing a tuple of length 1. So you can do it this way.
results = {}
for k, v in students.items():
    print(v)
    if (isinstance(v, int)):
        results[k] = v
    else:
        results[k] = sum(v) / len(v)

A: I'd do:
result = {}
for k, v in students.items():
  if type(v) in [float, int]:
    result[k] = v
  else:
    result[k] = sum(v) / len(v)

A: A pythonic solution would be to use dictionary comprehension to create the results dictionary.
def avg(l):
    return sum([l]) / len(l)

results = {key: (avg(val)) for (key, val) in students.items()}

You need brackets around the l in sum so the tuple is treated as a list. I would further change the data structure to a list instead of tuple.


Q: Coordinates intersecting with bounding box after forcing right hand rule I am trying to query for locations within a bounding box. The bounding box of the country Russia renders east-to-west, covering basically all of Canada and none of Russia (which is obviously incorrect) and returns cities in Canada, Poland, and Slovakia.
I used ForceRHR (Django 1.11) and ForcePolygonCW (Django 2.2) to force the right-hand-rule, and it appears to order the bounding box coordinates properly, but I get the same query results for the regular bounding box and the RHR bounding box.
Here are the relevant fields in the Location model...
from django.contrib.gis.db import models as gis_models
point = gis_models.PointField(blank=True, null=True, geography=True)
bounding_box = gis_models.PolygonField(blank=True, null=True)

And here's what I've tried...
from locations.models import Location
from django.contrib.gis.db.models.functions import ForceRHR, ForcePolygonCW

russia = Location.objects.annotate(rhr=ForcePolygonCW('bounding_box')).get(pk=1646)
print(russia.bounding_box)
in_russia = Location.objects.filter(point__intersects=russia.bounding_box)
print(in_russia)

print(russia.rhr)
in_russia2 = Location.objects.filter(point__intersects=russia.rhr)
print(in_russia2)

Here are the results of the code above:
SRID=4326;POLYGON ((19.638861 41.185902, 19.638861 81.856903, -168.997849 81.856903, -168.997849 41.185902, 19.638861 41.185902))

<QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: 52.0362, -170.5883>, <Topic: 52.0641, -169.6883>, <Topic: 52.1027, -170.0871>, <Topic: 52.1242, -170.4661>, <Topic: 52.1272, -170.5383>, <Topic: 52.1295, -170.4205>, '...(remaining elements truncated)...']>

SRID=4326;POLYGON ((19.638861 41.185902, -168.997849 41.185902, -168.997849 81.856903, 19.638861 81.856903, 19.638861 41.185902))

<QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: 52.0362, -170.5883>, <Topic: 52.0641, -169.6883>, <Topic: 52.1027, -170.0871>, <Topic: 52.1242, -170.4661>, <Topic: 52.1272, -170.5383>, <Topic: 52.1295, -170.4205>, '...(remaining elements truncated)...']>

I expect to get locations in Russia, so am I doing something wrong or is the entire approach wrong?


Q: Akeneo error after installation / Cache Error My akeneo installation works very fine and without any error. But when I want to start the application, the following error occurs:

Warning:
  require(web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php):
  failed to open stream: No such file or directory in
  web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php
  on line 209
       Fatal error: require(): Failed opening required 'web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php'
  (include_path='.:/usr/local/lib/php') in
  web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php
  on line 209
       Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalErrorException: Compile Error:
  require(): Failed opening required
  'web/akeneo/pim-community-standard/var/cache/prod/doctrine/orm/Proxies/__CG__PimBundleCatalogBundleEntityLocale.php'
  (include_path='.:/usr/local/lib/php') in
  web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php:209
  Stack trace: #0 {main} Next RuntimeException: Failed to start the
  session because headers have already been sent by
  "web/akeneo/pim-community-standard/vendor/doctrine/common/lib/Doctrine/Common/Proxy/AbstractProxyFactory.php"
  at line 209. in
  web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php:141
  Stack trace: #0
  web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoun
  in
  web/akeneo/pim-community-standard/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php
  on line 141

Can someone help me?

A: Did you clean your cache?
With the command
bin/console cache:clear --env=prod (or env=dev)
or the more "hard" way
rm -rf var/cache/*


Q: Display a tool tip on current document I am developing a code editor like VS.  I want to display a tool tip window when mouse cursor lands on a text. The ToolTip.Show() method asks for a IWin32Window parameter...
Please tell me how to display the tool tip in the current document just as Visual Studio Intellisense works.

A: ToolTip.Show Method (String, IWin32Window)
The second argument is the control for which the tool tip is to be shown.
toolTip1.Show("Test 123", button1, Int32.MaxValue);

Visual Studio tracks the word underneath the mouse and displays tooltips/intellisense accordingly. One way for you to do the same could be to:

*

*Track the mouse movements

*Get the text under mouse

*Show tooltip.

A: The ToolTip.Show method also has other more appropriate overloads, like this one.
You can pass the edit control (that is, your text box) that you want to be associated with the tooltip as the IWin32Window parameter.
Then, you can specify the current coordinates of the mouse cursor as the X and Y arguments:

*

*If you're trying to show this tooltip in one of the mouse event handlers (like MouseMove), the current coordinates of the mouse cursor are passed in as part of the MouseEventArgs—just use the e.X and e.Y properties.

*Otherwise, you'll need to use the Control.MousePosition property to get its current location, which will return a Point representing its current location relative to screen coordinates. Another one of the overloads to the ToolTip.Show method accepts a Point parameter that you can use here instead of separate X and Y coordinates


Q: export Intellij project including libraries to Eclipse I have an intellij project which is using log4j and junit libraries (in my external libraries section). I need to export the project to Eclipse project including the libraries. The intellij option for exporting to eclipse is just generating the .project and .classpath files and nothing else. How would I export that project so that it will contain all dependencies and someone using eclipse would be able to compile and run the program without additional work?
Also this is a normal java project (not maven)


Q: Youtube iFrame player in IOS Webview loads very slowly I'm using the standard YouTube iFrame player as defined here within a Webview on IOS. Everything works as it should, except the videos consistently take over 6 seconds to load on a broadband network. When I use Safari to load the exact same video on the Youtbue.com, on the same network, using the same iPad, the video consistently loads in under 3 seconds.
Does anyone know why the IOS Webview videos are taking twice as long to load ?
Or is YouTube (owned by Google) deliberately loading videos on their website faster than apps using their player apis ?
A couple other data points as to my methodology:
1) I'm only measuring the time for a video to load in my app, not the loading of the webview or even the html page within the webview that contains the Youtube iframe. I start measuring after the webview has loaded the Youtube iFrame.
2) The Youtube App performs similarly to the YouTube website using Safari. I assume Youtube App uses a Webview.
3) The results seem to vary on different days. YouTube Website and App videos are always faster on average, but the amount varies by days.

A: I feel the "(owned by Google)" comment suggests some alterer motive which I don't believe exists..
There are several different issues which may be at work here:
1) You seem to be testing Youtube.com using Mobile Safari, and testing the embedded player using a webview:
This is not a fair comparison, as the webview has been shown to be very significantly slower than safari. (e.g. http://www.guypo.com/mobile/ios-browsers-speed-bakeoff/ )
2) You do not make it clear exactly what load time you are measuring
Are you creating the webview in this time and setting up the browser environment?
Are you loading the document which includes the script tag for the embedded player code in this time?
Did Safari have a hot cache for youtube.com at the time you loaded the video?
Many browsers start loading requests in the background as you type, before you tap to load a page - these kind of performance tweaks can significantly reduce apparent time to load a site, but make comparisons difficult.
3) The common user story they are optimising for is different
In almost all situations where the YouTube player API is inserted into a page or a website, the video does not automatically start playing.
By comparison, almost every YouTube watch page load begins playing the video automatically.
One of the optimisations which YouTube have discussed in presentations before is in-lining the first part of the video stream into the page even before the video player loads.
This is a trade-off of extra user bandwidth for faster video playback which makes sense when you know the user is going to definitely play the video: however if they were to do this for embedded videos then it would significantly slow down the loading time for players with videos which did not always start playing - which is a fairly significant percentage of all of the websites in the world!
4) YouTube get involved at different points in the two cases, and can only start optimising the experience later for embedded players.
YouTube is able to do optimisations on youtube.com which it is unable to do on third party sites/apps using their html5 player API.
In the case of watching a video on youtube.com: YouTube are involved right from the first http request - they know which video you are playing, and they know which browser you say you are on (so can optimise the experience as much as possible to pre-load the correct video and/or video player).
In the case of embedding an iframe:

*

*The browser first loads your page, which it then has to parse and extract urls from.

*Then it makes a request for javascript from YouTube (note that if you are using the javascript player API rather than the embedded iframe direct then that needs to be cached on the browser, so YouTube still can't optimise performance of this video at this point)

*Once your entire page has finished loading, it can create an iframe pointing to YouTube (all of this takes time on the CPU and memory management time)

*At this point, YouTube can start optimising things to try to make the experience faster.


Q: Wordpress get_avatar function not correct working My code doing this, listing which author have posted in the current category. But get_avatar function not correct working. Im Using Simple Local Avatar Plugin. It is working author.php don't have any problem. But when i use it my this code, it is listing same and wrong author picture(My latest author picture. You can look this picture)
My Code:
<?php if (is_category()) {?>
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
'numberposts' => -1,
'category_name' => $current_category,
'orderby' => 'author',
'order' => 'ASC'
);
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post) :
if (!in_array($cat_post->post_author,$author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
foreach ($author_array as $author) :
$auth = get_userdata($author)->display_name;
$autid= get_userdata($author)->ID;
echo get_avatar( get_the_author_email(), '32' );
echo "";
echo $auth;
echo "";
echo "
";
endforeach;
?>
<?php }?>

A: change this echo get_avatar( get_the_author_email(), '32' ); to echo get_avatar( $autid, '32' );
get_the_author_email() returns email of the author in the current loop of wordpress and not from your foreach loop.


Q: How / Where does Adonis cache views? I am learning adonisjs. The .env file has an option to set CACHE_VIEWS=true. What exactly does this do? Some frameworks store the cached views in a file, and some in memory, but how does Adonis cache views?

A: This variable is readed in your configuration file. Then it's used in the wrapper around Nunjucks (in View/index.js).
You can find more information about Nunjucks Cache in the documentation of loaders.


Q: Qmake scope syntax with "contains" function I wrote some qmake which looked like this:
contains( DEFINES, SOME_DEF ): DEFINES+=SOME_OTHER_DEF

The result was to ALWAYS execute what I thought was conditional, i.e. DEFINES+=SOME_OTHER_DEF
I changed the line to:
contains( DEFINES, SOME_DEF ){ DEFINES+=SOME_OTHER_DEF }

And it works as I expected now.  The thing is, I don't understand why I could not use the original syntax?
Here's the contains documentation (which doesn't address this detail regarding the use of :)
http://doc.qt.io/qt-5/qmake-test-function-reference.html#contains-variablename-value
Here is the scope documentation which seems to support what I was trying to do:
http://doc.qt.io/qt-5/qmake-language.html#scopes-and-conditions
It says:

You may... use the : operator to perform single line conditional
  assignments.

I've definitely used the : in this manner before (but I guess not with contains?).  What am I failing to understand?

Additional info (responding to comment in a readable manner):
Test ran:
DEFINES+=A
DEFINES+=B
contains( DEFINES, A ) : contains( DEFINES, B ) : message( 1 )
contains( DEFINES, A ) : contains( DEFINES, C ) : message( 2 )
contains( DEFINES, A ):contains( DEFINES, B ):message( 3 )
contains( DEFINES, A ):contains( DEFINES, C ):message( 4 )

Result:
Project MESSAGE: 1
Project MESSAGE: 3

So it's not white space.
I think my question was invalid.

A: Looks like it's about space. Seems following should work but I'm not sure
contains( DEFINES, SOME_DEF ):DEFINES+=SOME_OTHER_DEF

As I got it it's designed to be used as logical AND operator.
conditionA:conditionB {
  ...
}


Q: Process not working I have tried calling a Process(console application) using the following code:
       ProcessStartInfo pi = new ProcessStartInfo();
        pi.UseShellExecute = false;
        pi.RedirectStandardOutput = true;
        pi.CreateNoWindow = true;
        pi.FileName = @"C:\fakepath\go.exe";
        pi.Arguments = "FOO BAA";
        Process p = Process.Start(pi);
        StreamReader streamReader = p.StandardOutput;
        char[] buf = new char[256];
        string line = string.Empty;
        int count;
        while ((count = streamReader.Read(buf, 0, 256)) > 0)
        {
            line += new String(buf, 0, count);
        }

It works for only some cases.
The file that does not work has a size of 1.30 mb,
I don't know if that is the reason for it not working correctly.
  line returns an empty string.
I hope this is clear.
Can someone point out my error? Thanks in advance.

A: A couple thoughts:

*

*The various Read* methods of streamreader require you to ensure that your app has completed before they run, otherwise you may get no output depending on timing issues.   You may want to look at the Process.WaitForExit() function if you want to use this route.
Also, unless you have a specific reason for allocating buffers (pain in the butt IMO) I would just use readline() in a loop, or since the process has exited, ReadToEnd() to get the whole output.  Neither requires you to have to do arrays of char, which opens you up to math errors with buffer sizes.

*If you want to go asynchronous and dump output as you run, you will want to use the BeginOutputReadLine() function (see MSDN)

*Don't forget that errors are handled differently, so if for any reason your app is writing to STDERR, you will want to use the appropriate error output functions to read that output as well.