text:
Q: Haxe & NME: fastest method for per pixel bitmap manipulation This is a small project for testing pixel level manipulation performance of NME for different builds (Windows c++, Flash).
It uses BitmapData.setPixel to modify the pixels one by one (320x240 for every frame). The C++ build runs at 22 FPS, and the flash build around ~100 FPS. Whats the reason for the huge performance drop for the C++ build compared to flash? How could I improve the code to get higher FPS using the C++ build?
Mandelbrot.hx
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.text.TextField;
import nme.events.Event;
import nme.events.TimerEvent;
import nme.utils.Timer;
import nme.geom.Matrix;
import nme.geom.Rectangle;
import nme.utils.ByteArray;

class Mandelbrot
{
    public static function main() : Void
    {
        new Mandelbrot();
    }

    public var pixels:Array<Array<Int>>;

    public var colorModifier:Int;
    private var bitmapData:BitmapData;
    private var bigBitmapData:BitmapData;

    private var fps:TextField;

    private var width:Int;
    private var height:Int;
    private var matrix:Matrix;

    public function new()
    {
        width = 320; //Std.int(flash.Lib.current.stage.stageWidth/2);
        height = 240; //Std.int(flash.Lib.current.stage.stageHeight/2);

        var scale:Float = 2;//flash.Lib.current.stage.stageWidth/width;
        matrix = new Matrix();
        matrix.scale(scale, scale);

        var setBitmap:Bitmap = new Bitmap();
        bitmapData = new BitmapData( width , height , false , 0x000000 );
        bigBitmapData = new BitmapData( nme.Lib.current.stage.stageWidth , nme.Lib.current.stage.stageHeight , false , 0x000000 );

        setBitmap.bitmapData = bigBitmapData;

        nme.Lib.current.addChild( setBitmap );

        var maxIterations:Int = 128;

        pixels = new Array();

        var beforeTime = nme.Lib.getTimer();

        var xtemp;
        var iteration;
        var x0:Float = 0;
        var y0:Float = 0;
        for(ix in 0...width) {
            pixels[ix] = new Array();
            for(iy in 0...height) {
                    x0 = 0;
                    y0 = 0;
                    iteration = 128;

                    while ( x0*x0 + y0*y0 <= 4  &&  iteration > 0 )
                    {
                        xtemp = x0*x0 - y0*y0 + (ix-14*5000)/50000;
                        y0 = 2*x0*y0 + (iy-(height/0.6))/50000;
                        x0 = xtemp;

                        iteration--;
                    }

                    pixels[ix][iy] = iteration;
            }
        }

        var afterTime = nme.Lib.getTimer();

        var tf = new TextField();
        tf.width = 400;
        tf.text = "Generating fractal took "+(afterTime-beforeTime)+" ms";
        nme.Lib.current.addChild(tf);

        fps = new TextField();
        fps.width = 400;
        fps.y = 10;
        fps.text = "FPS: ";
        nme.Lib.current.addChild(fps);

        colorModifier = 2;
        var timer:haxe.Timer = new haxe.Timer(10);

        runLoop();
        timer.run = runLoop;
    }

    public function runLoop() {
        var r:Int=0, b:Int=0, g:Int=0;
        var pixel:Int = 0;

        var beforeTime = nme.Lib.getTimer();

        for(iy in 0...height) {
            for(ix in 0...width) {
                pixel = pixels[ix][iy];
                r = pixel + colorModifier;
                g = pixel + colorModifier + r;
                b = pixel + colorModifier + g;
                bitmapData.setPixel(ix, iy, (r<<16 | g<<8 | b));
            }
        }

        bigBitmapData.draw(bitmapData, matrix, null, null, null, false);
        var afterTime = nme.Lib.getTimer();
        fps.text = "FPS: "+Math.round(1000/(afterTime-beforeTime));

        colorModifier += 2;
        if(colorModifier > 65530)
                colorModifier = 0;

    }
}

Mandelbrot.nmml
<?xml version="1.0" encoding="utf-8"?>
<project>
  <app
     file="Mandelbrot.hx"
     title="Mandelbrot sample"
     package="org.haxe.nme.mandelbrot"
     version="1.0.0"
     company="nme"
     main="Mandelbrot"
  />
  <window
        width="640"
        height="480"
        orientation="landscape"
        fps="60"
        background="0xffffff"
        resizeable="true"
        hardware="true"
    />
  <classpath name="." />
  <haxelib name="nme" />
  <ndll name="std" />
  <ndll name="regexp" />
  <ndll name="zlib" />
  <ndll name="nme" haxelib="nme" />
  <setenv name="SHOW_CONSOLE"/>
</project>

A: Look into the nme.Memory API. The idea is to create a ByteArray with the correct size (or get it from a BitmapData), select it as the current virtual memory space and manipulate its bytes directly.
You'll get an approximately 10x speed boost with Flash and it should be way faster with the CPP target too. Don't forget to compile in Release mode or method inlining will be disabled and performances will suffer a lot.
Basic usage example (untested code) :
var rect:Rectangle = bitmapData.rect;

// 32bits integer = 4 bytes
var size:Int = bitmapData.width * bitmapData.height * 4;

// The virtual memory space we'll use
var pixels:ByteArray = new ByteArray();

// CPP does not support setting the length property directly
#if (cpp) pixels.setLength(size);
#else pixels.length = size; #end

// Select the memory space (call it once, not every frame)
Memory.select(pixels);

// And in your loop set your color
// Color is in BGRA mode, nme.Memory can only be used in little endian mode.
Memory.setI32((y * width + x) * 4, color);

// When you're done, render the BitmapData
// (don't forget to reset the ByteArray position)
pixels.position = 0;
bitmapData.setPixels(rect, pixels);

Keep in mind this is a very basic code example. In your case, you'd need to adapt it and actually use a double sized ByteArray because you need to store the iteration count too. Nested loops can be optimized in your main loop and you can avoid a lot of extra index/address computations :
// Note the size * 2 !
// First part of the ByteArray will be used to store the iteration count,
// the second part to draw the pixels.
#if (cpp) pixels.setLength(size * 2);
#else pixels.length = size * 2; #end

Memory.select(pixels);

// First loop storing iteration count
for (iy in 0...height)
{
    for (ix in 0...width)
    {
        // ... do some stuff ...
        Memory.setI32((iy * width + ix) << 2, iteration);
    }
}

// In your runLoop :
for (i in 0...(height * width))
{
    // Get the iteration count
    var pixel:Int = Memory.getI32(i << 2);

    r = pixel + colorModifier;
    g = pixel + colorModifier + r;
    b = pixel + colorModifier + g;

    // Note that we're writing the pixel in the second part of our ByteArray
    Memory.setI32(size + (i << 2), r | g << 8 | b << 16);
}

// Sets the position to the second part of our ByteArray
pixels.position = size;
bitmapData.setPixels(rect, pixels);

And this is it. If you really don't want to use Alchemy Opcodes on the Flash target, the next fastest way to blit pixels is to use getVector() / setVector() from the BitmapData class. But it's really not as fast.

A: Array itself is not true liner array in flash, more like a map.
For the per-pixel manipulation I can recommend to use getVector/setVector api of the BitmapData class, which can retrieve (and assign) a rectangular area of the image as flat pixel data. In which case you can access individual pixels in the vector as:
pixels[ix + image_width*iy] = <argb32>

Also, instead of constructing an intermediate Array of Arrays it would be faster to assign pixels directly.

A: Try to use ByteArray. It would be faster in Flash and C++, I think.


text:
Q: Python matplotlib using Tkinter as dashboard I'm reading a rasberry shake to read the data of the socket from 4 channels and write the data to 4 individual flat files. Then I need to read the individual flat files and plot the data using matplotlib as below. But I need to use a tkinter to dashboard it. I also need to call an external python code named DropCoverHold.py or display a gif file on another frame that will be triggered on a higher threshold.
Is there a way to show the matplotlib animation code below with tkinter?
%matplotlib notebook
import datetime
import time
import os
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import TextBox
from IPython.core.display import display, HTML

#>conda update conda
#conda update ipython

display(HTML("<style>.container {width:80% !important;} </style>"))

xsEHZ = []
ysEHZ = []
xsENE = []
ysENE = []
xsENZ = []
ysENZ = []
xsENN = []
ysENN = []

inputFilePrefix = 'c:/temp/inputdata'
inputFileSuffix = '.txt'
valid_channels = ["EHZ", "ENE", "ENZ", "ENN"]

#Clear input files
for c in valid_channels:
    inputFileToClear = inputFilePrefix + c + inputFileSuffix
    o = open(inputFileToClear, "w").close()

fig, ((ax1, ax2, ax3, ax4)) = plt.subplots(4, 1, figsize=(8, 8))

def GenerateData(inputFile):
    data = open(inputFile, 'r').read()
    lines = data.split('\n')

    xs = []
    ys = []

    for line in lines[-10:]:
        if len(line) > 1:
            x, y = line.split(',') # Delimiter is comma

            time_formatted = time.strftime('%H:%M:%S', time.localtime(float(x)))
            stringTime = "{:.3f}".format(float(x))

            xs.append(time_formatted + '.' + stringTime[-3:])
            ys.append(round(float(y)))
        if os.path.exists('/temp/Threshold.txt'):
            %run "/temp/DropCoverHold.py"

    return xs, ys

def animate(i):
    dataInputFile = 'c:/temp/inputdataEHZ.txt'
    xsEHZ, ysEHZ = GenerateData(dataInputFile)

    dataInputFile = 'c:/temp/inputdataENE.txt'
    xsENE, ysENE = GenerateData(dataInputFile)

    dataInputFile = 'c:/temp/inputdataENZ.txt'
    xsENZ, ysENZ = GenerateData(dataInputFile)

    dataInputFile = 'c:/temp/inputdataENN.txt'
    xsENN, ysENN = GenerateData(dataInputFile)

    ax1.cla()
    ax2.cla()
    ax3.cla()
    ax4.cla()

    ax1.plot(xsEHZ, ysEHZ, scaley=True, scalex=True, color="red")
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Count')
    ax1.set_title('EHZ')
    plt.setp(ax1.get_xticklabels(), rotation=30);

    ax2.plot(xsENE, ysENE, scaley=True, scalex=True, color="green")
    ax2.set_xlabel('Time')
    ax2.set_ylabel('Count')
    ax2.set_title('ENE')
    plt.setp(ax2.get_xticklabels(), rotation=30);

    ax3.plot(xsENZ, ysENZ, scaley=True, scalex=True, color="blue")
    ax3.set_xlabel('Time')
    ax3.set_ylabel('Count')
    ax3.set_title('ENZ')
    plt.setp(ax3.get_xticklabels(), rotation=30);

    ax4.plot(xsENN, ysENN, scaley=True, scalex=True, color="black")
    ax4.set_xlabel('Time')
    ax4.set_ylabel('Count')
    ax4.set_title('ENN')
    plt.setp(ax4.get_xticklabels(), rotation=30);

    plt.tight_layout()
    plt.show(block=False)

ani = FuncAnimation (fig, animate, interval=500, blit=True, repeat=True)

A: You can set the backend with the following code:
import matplotlib
matplotlib.use("TkAgg")

To run code in another file just import it.
And to display gif use:
from PIL import Image
img = Image.open(filename)
plt.imshow(img)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i create a custom object_label without adding a new method to the domain class? I notice that RailsAdmin has an object_label method, but it's unclear how to use it:
config.model Entity do
  object_label do
    # ???
  end
end

A: RailsAdmin.config do |config|
  config.model Team do
    object_label_method do
      :custom_label_method
    end
  end

  def custom_label_method
    "Team #{self.name}"
  end
end

Extracted from the documentation
If you just want to use an attribute from the model, you can just pass it as the method to be called... like :name would return the object.name as the label.


text:
Q: Android work in background I got 3 activities ( A , B ,C ) and a service that I call to check if I got new messages from DB. It's a HTTP request . I need to make the request each 15 sec.
 Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(15000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // Here i call
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };

        t.start();

How to make it work when i am changing activities ?

A: Option: Consider changing setup to have three fragments as your original activities, and a MainActivity that controls the repeat polling for messages to DB, as well as controlling the fragments.

A: @SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {

    private PendingIntent pendingIntent;
    Handler mHandler;
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onCreate() {
    }

    public void f() {
        Toast t = Toast.makeText(this, "Service is still running",
                Toast.LENGTH_SHORT);
        t.show();
  };
}
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
        t.show();

        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        mHandler = new Handler();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                f();
                mHandler.postDelayed(this, 20000);
            }
        };
        mHandler.postDelayed(r, 20000);

    }

}

and in manifest use this
<service android:name="com.example.yourservice"></service>


text:
Q: Wrong PHP date() output in wamp server The problem is that date('r') returns wrong time for my timezone.
php.ini timezone setting:
date.timezone = Europe/Kiev
date_default_timezone_set('Europe/Kiev') in my script solves the problem.
So what's wrong with WAMP?

A: I suggest always using date_default_timezone_set() from script
e.g.
date_default_timezone_set('Europe/Kiev');

or
ini_set('date.timezone', 'Europe/Kiev');

...to avoid PHP guessing timezone.
It comes handy when you transfer code to different server(s), for example, outside of Ukraine. This line should help you to avoid unexpected (wrong) results if date.timezone is not set in php.ini or its setting is incorrect. It's also handy when you can't access and/or modify php.ini (shared hosting).
Also, be sure that you've not used ; at the and of line in php.ini.
Restart server after changing php.ini.

A: Edit php.ini and restart Apache:

*

*left click to WampServer in tray icon

*open php.ini (go to PHP -> php.ini)

*set new date.timezone value

    ;date.timezone = UTC
    date.timezone = Europe/Kiev

*

*restart Apache ( go to Apache -> Service -> Restart Service )

*check value of date.timezone by phpinfo();

A: You need to reload the configuration / restart the server after editing your php.ini file.

A: According to the documentation of date_default_timezone_get, the date.timezone configuration option can be overridden by setting the TZ environement variable (which, in turn, can be overridden by calling date_default_timezone_set). From your description, I suspect that the TZ environement veriable is set.

A: by default it shows GMT time you can change for your region with following code
   date_default_timezone_set("Asia/Bangkok");//set you countary name from below timezone list
    echo $date = date("Y-m-d H:i:s", time());//now it will show "Asia/Bangkok" or your date time

List of Supported Timezones
http://www.php.net/manual/en/timezones.php

A: I know this is an old question.
If you are using a PHP framework, you might want to check the config file of the framework. For example in Laravel, open the config/app.php and you will find timezone there. Set it to your timezone.

A: *

*Open your php.ini with maybe notepad++, sublime text...

*Add this line to the file: date.timezone = "X" Where X is the your time-zone of wish. Get a list of supported timezones here: http://php.net/manual/en/timezones.php
... That should do it.
3. Restart your server


text:
Q: Mapping a 3d Distribution of physical stars in space Stars to a 2d distribution of visible stars in the Sky This question came up as a tangent to another project. I'd appreciate help defining the question more clearly as well as grappling with a solution:
Suppose I want to write an algorithm to generate a "realistic" starfield. That is, the distribution of stars and their magnitudes in my 2d sky should be consistent with the distribution that would result if I populated a large 3d space with stars and then projected those stars onto the sky, accounting for the drop in magnitude with distance.
Assumptions:
All positions of stars can be assumed to have integer coordinates.
The distribution of stars in the 3d space is such that any given integer position has a fixed probability of containing a star.
The distribution of the magnitudes of the stars is a normal distribution (?) Or is there another probability distribution that would be a better choice?
If it makes the calculations easier, the starfield being generated can be assumed to be a rectangle, instead of radiation lines of sight from an observer.
Feel free to ask questions about anything unclear here: my first problem has been trying to rigorously define the question.


text:
Q: Задание по учету сотрудников компании, через Array list Не могу разобраться с пунктом 3, как мне реализовать данный метод?

![3][main]

A: Я предпочитаю функциональное решение:
public static int searchBySurname(String surname, String name, List<Employee> employeeList) {
    return IntStream.range(0, employeeList.size())
        .filter(i -> employeeList.get(i).surname.equals(surname)
                  && employeeList.get(i).name.equals(name)
        )
        .findAny().orElse(-1);
}

Если с этим трудности, то можно старым добрым способом:
public static int searchBySurname(String surname, String name, List<Employee> employeeList) {
    for (int i = 0; i < employeeList.size(); i++) {
        Employee employee = employeeList.get(i);
        if (employee.surname.equals(surname) && employee.name.equals(name)) {
            return i;
        }
    }
    return -1;
}


text:
Q: POST to vsts release api endpoint in C# I want to make a POST request to vsts create release api, sample:
POST https://fabrikam.vsrm.visualstudio.com/MyFirstProject/_apis/release/releases?api-version=4.1-preview.6
with the below request body:
{
  "definitionId": 1,
  "description": "Creating Sample release",
  "artifacts": [
    {
      "alias": "Fabrikam.CI",
      "instanceReference": {
        "id": "2",
        "name": null
      }
    }
  ],
  "isDraft": false,
  "reason": "none",
  "manualEnvironments": null
}

Can anyone please give me some pointers to do the same coding in C#. I am lost at the moment.
Kind Regards.
Edit1:
I have the below code to fetch the response, i want to make a POST to it:
class Program
{
    public async void GetProjects()
    {
        try
        {
            var personalaccesstoken = "PAT";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", "", personalaccesstoken))));

                using (HttpResponseMessage response = client.GetAsync(
                            "https://sample.vsrm.visualstudio.com/MyFirstProject/_apis/release/releases?api-version=4.1-preview.6").Result)

                    //POST to response with Json body

                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    static void Main(string[] args)
    {

        Program prog = new Program();
        prog.GetProjects();
    }
}

A: ok, i was able to do this with the help of RestSharp:
 var client = new RestClient("https://demouser.vsrm.visualstudio.com/MyFirstProject/_apis/release/releases?api-version=4.1-preview.6");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Basic TWFuaXNoX0JpbHVuZ0BhZC5pbmZvc3lzLmNvbTpqbXZzNzQzeTZzcjR2cWFjY3Y0ZnpmbXk1ZTNra2tiYm03aDJjb29wMmZ5bjZ2MjZ1NW9x");
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("undefined", "{\r\n  \"definitionId\": 1,\r\n  \"description\": \"Creating Sample release\",\r\n  \"artifacts\": [\r\n    {\r\n      \"alias\": \"_MyFirstProject\",\r\n      \"instanceReference\": {\r\n        \"id\": \"2\",\r\n        \"name\": null\r\n      }\r\n    }\r\n  ],\r\n  \"isDraft\": false,\r\n  \"reason\": \"none\",\r\n  \"manualEnvironments\": \"PROD\"\r\n}", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);


text:
Q: Java -- Pass variable from class to class I know that to pass from within the Same class, I would do something like this --- but what about between classes?
class TestMe{
    public static void main(String[] args)
    {
        int numberAlpha = 232;
        TestMe sendNumber = new TestMe();
        sendNumber.Multiply(numberAlpha);
    }

    void Multiply(int var)
    {
        var+=40;
    }
}

A: You use getters and setters.
class A {
    private int a_number;
    public int getNumber() { return a_number; }
}
class B {
    private int b_number;
    public void setNumber(int num) { b_number = num; }
}

.. And in your main method, wherever it is:
public static void main(String[] args) {
    A a = new A();
    int blah = a.getNumber();
    B b = new B();
    b.setNumber(blah);
}

You can also use constructors as a means of an "initial setter" so that the object is always created with a minimum set of variables already instantiated, for example:
class A {
    private int a_number;
    public A(int number) { // this is the only constructor, you must use it, and you must give it an int when you do
        a_number = number;
    }
    public int getNumber() { return a_number; }
}


text:
Q: Making a program to find what the longest substring in alphabetical order I want to write a program that prints the longest sub string in alphabetical order from the string s and I don't know what I am doing wrong, I just started coding a few days ago and this is the best I've come up with.
s = 'vvrsmxxlplnawxxcmcvuxrgi'

alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Current_Sequence=''
Max_Sequence=''
runs=0
current_runs = ''
max_runs=''
for I in str(s)[1:]:
    runs +=1
    if alphabet.index(I) >= alphabet.index(s[runs-1]):
        Current_Sequence += str(I)
        current_runs += str(runs)
    else:
        if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
            Max_Sequence = str(Current_Sequence)
            Current_Sequence=''
            max_runs= int(str(current_runs)[0])
            current_runs=''
        else:
            Current_Sequence=''
            current_runs=''

if (len(Max_Sequence)) >= (len(Current_Sequence)):
    print('Longest substring in alphabetical order is: ' + s[max_runs-1] + str(Max_Sequence))

if (len(Current_Sequence)) > (len(Max_Sequence)):
    print('Longest substring in alphabetical order is: ' + s[current_runs[0]-1] + str(Current_Sequence))

* ERROR: Expected 'awxx', got 'vwxx'. *
in another trial where s = 'zyxwvutsrqponmlkjihgfedcba' the result was
* ERROR: Expected 'z', got 'unsupported operand type(s) for -: 'str' and 'int''. *
any input will help, as I am young and very new to code

A: You don't have to change very much.
Just a few lines:
You want to start at the first character
for I in str(s)[0:]:

As soon as the sequence restarts you also want to add the current letter - that broke the chain - to your new sequence. Therefore you don't need max_runs anymore
Current_Sequence=I

Move the runs +=1 to the end of the for loop.
Remove max_runs from the print
print('Longest substring in alphabetical order is: ' + str(Max_Sequence))

Full code:
s = 'kjddbyydx'
alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Current_Sequence=''
Max_Sequence=''
runs=0
for I in str(s)[0:]:
    if alphabet.index(I) >= alphabet.index(s[runs-1]):
        Current_Sequence += str(I)
    else:
        if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
            Max_Sequence = str(Current_Sequence)
            Current_Sequence=I
        else:
            Current_Sequence = I
    runs +=1

if (len(Max_Sequence)) >= (len(Current_Sequence)):
    print('Longest substring in alphabetical order is: ' + str(Max_Sequence))

if (len(Current_Sequence)) > (len(Max_Sequence)):
    print('Longest substring in alphabetical order is: ' + str(Current_Sequence))

Code using enumerate instead of a for loop:
for runs, I in enumerate(s):
    if alphabet.index(I) >= alphabet.index(s[runs-1]):
        Current_Sequence += str(I)
    else:
        if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
            Max_Sequence = str(Current_Sequence)
            Current_Sequence=I
        else:
            Current_Sequence = I

if (len(Max_Sequence)) >= (len(Current_Sequence)):
    print('Longest substring in alphabetical order is: ' + str(Max_Sequence))

if (len(Current_Sequence)) > (len(Max_Sequence)):
    print('Longest substring in alphabetical order is: ' + str(Current_Sequence))

A: you program looks ok.  maybe this will help you to trace what is wrong
    def max_substr(s):
        max_s = s[0:1]
        cur_s = max_s

        for i in range(1, len(s)):
            ch = s[i : i + 1]
            if ch >= cur_s[-1]:
                cur_s = cur_s + ch
                if len(cur_s) > len(max_s):
                    max_s = cur_s
            else:
                cur_s = ch

        return max_s

    print(max_substr("vvrsmxxlplnawxxcmcvuxrgi"))

A: You can use zip to offset the string by one, accumulate the substrings, and select the longest one.
s = 'vvrsmxxlplnawxxcmcvuxrgi'

li = []
st = ""
for c1,c2 in zip(s,s[1:]):
    if c2 >= c1:
        st += c1
    elif st != "":
        li.append(st+c1)
        st =""

print(max(li, key = len))

Output:
awxx


text:
Q: Delete row and delete table lock oracle I have two query
1.delete from x;
2.delete from x where y='a'
what type of lock does oracle 11 g provide to above query?
And suppose we iterate the below query in a program
delete from x where y='$a'
Let a have list of number 1,2,3,4..
Now if the same program is called from 2 server will 1 server delete 1,3... and other server will delete 2,4...?

A: 1) Since there is no where clause, all rows will be locked in the table for that user session. 2) only those rows matching the where clause will be locked. Oracle uses row level locking by setting a lock bit in the data block for that row.
Unless and until a commit is issued - no other session will see these deletions. Oracle will use rollback information - created for each separate delete (or any DML operation) statement to provide a read consistent view to any other session. Meaning: the other sessions will see the table without the deletions. Once the rows are locked - other sessions will be prevented from issuing a delete against those rows and the user will be blocked, waiting for those rows to be committed or rolled back. You can test this with two sqlplus sessions.
If you want to know more about locks, look at Tom Kyte's excellent book, Expert Oracle DB Architecture.
Yes, two different sessions can delete different sets of rows. Oracle does not do full table locking by default (it does lock the table during DML to prevent structural changes to that table while changes are pending), so one session will not block another.

A: No problem. You can delete non existing records. But you mustn't forget commit transaction.


text:
Q: Painting artifacts of QGraphicsProxyWidget with QPlainTextEdit There was a problem of repainting the graphical scene when using elements with a QGraphicsProxyWidget with QPlainTextEdit.
It looks like this, as shown in the picture artifact_demo

The artifact is observed for Qt version 5.9.1 in Windows and Linux.
The minimal compiled example is posted on github
Any ideas how to avoid such behavior?

A: The solution is setCacheMode of proxy widget to QGraphicsItem::DeviceCoordinateCache


text:
Q: how to use dynamic templates in python pyramid i've finished developing a website, it's working fine however i am trying to optimize my website by adding dynamic templates, and want to make sure that if it can be done on pyramid python.
for example, in my jinja template i have the following:
{% block article_detail %}
    <form action="{{request.route_url('Sports_News_Action',action=action)}}" method="post" class="form">
        {% if action =='edit' %}
            {{ form.id() }}

example in my controller:
@view_config(route_name='Sports_News_Action', match_param='action=create',
             renderer='StarAdmin:templates/edit_sports.jinja2')
def general_create(request):
    entry = SportNews()

the request route will have to match the one in my controller in order to run the function. what i want to do is how do i replace the one in jinja with a dynamic variable, to use the one jinja template lets say for different views/controllers with different route_names.

A: I think in your situation the simplest solution is to leave action undefined and the browser will submit the request to the current url. You only need to specify action if you want to submit the form to a different url than the current. That being said, you can use lots of different options in pyramid to generate a url as well. For example, request.url is the current url, or request.matched_route.name is the name of the current matched route.


text:
Q: How to compare the values in two different rows with awk? Given this file:
Variable_name   Value
Aborted_clients 0
Aborted_connects    4
Binlog_cache_disk_use   0
Binlog_cache_use    0
Binlog_stmt_cache_disk_use  0
Binlog_stmt_cache_use   0
Bytes_received  141
Bytes_sent  177
Com_admin_commands  0
Com_assign_to_keycache  0
Com_alter_db    0
Com_alter_db_upgrade    0
Com_alter_event 0
Com_alter_function  0
Com_alter_procedure 0
Com_alter_server    0
Com_alter_table 0
Com_alter_tablespace    0
Com_analyze 0
Com_begin   0
Com_binlog  0
Com_call_procedure  0
Com_change_db   0
Com_change_master   0
Com_check   0
Com_checksum    0
Com_commit  0
Com_create_db   0
Com_create_event    0
Com_create_function 0
Com_create_index    0
Com_create_procedure    0
Com_create_server   0
Com_create_table    0
Com_create_trigger  0
Com_create_udf  0
Com_create_user 0
Com_create_view 0
Com_dealloc_sql 0
Com_delete  0
Com_delete_multi    0
Com_do  0
Com_drop_db 0
Com_drop_event  0
Com_drop_function   0
Com_drop_index  0
Com_drop_procedure  0
Com_drop_server 0
Com_drop_table  0
Com_drop_trigger    0
Com_drop_user   0
Com_drop_view   0
Com_empty_query 0
Com_execute_sql 0
Com_flush   0
Com_grant   0
Com_ha_close    0
Com_ha_open 0
Com_ha_read 0
Com_help    0
Com_insert  0
Com_insert_select   0
Com_install_plugin  0
Com_kill    0
Com_load    0
Com_lock_tables 0
Com_optimize    0
Com_preload_keys    0
Com_prepare_sql 0
Com_purge   0
Com_purge_before_date   0
Com_release_savepoint   0
Com_rename_table    0
Com_rename_user 0
Com_repair  0
Com_replace 0
Com_replace_select  0
Com_reset   0
Com_resignal    0
Com_revoke  0
Com_revoke_all  0
Com_rollback    0
Com_rollback_to_savepoint   0
Com_savepoint   0
Com_select  1
Com_set_option  0
Com_signal  0
Com_show_authors    0
Com_show_binlog_events  0
Com_show_binlogs    0
Com_show_charsets   0
Com_show_collations 0
Com_show_contributors   0
Com_show_create_db  0
Com_show_create_event   0
Com_show_create_func    0
Com_show_create_proc    0
Com_show_create_table   0
Com_show_create_trigger 0
Com_show_databases  0
Com_show_engine_logs    0
Com_show_engine_mutex   0
Com_show_engine_status  0
Com_show_events 0
Com_show_errors 0
Com_show_fields 0
Com_show_function_status    0
Com_show_grants 0
Com_show_keys   0
Com_show_master_status  0
Com_show_open_tables    0
Com_show_plugins    0
Com_show_privileges 0
Com_show_procedure_status   0
Com_show_processlist    0
Com_show_profile    0
Com_show_profiles   0
Com_show_relaylog_events    0
Com_show_slave_hosts    0
Com_show_slave_status   0
Com_show_status 1
Com_show_storage_engines    0
Com_show_table_status   0
Com_show_tables 0
Com_show_triggers   0
Com_show_variables  0
Com_show_warnings   0
Com_slave_start 0
Com_slave_stop  0
Com_stmt_close  0
Com_stmt_execute    0
Com_stmt_fetch  0
Com_stmt_prepare    0
Com_stmt_reprepare  0
Com_stmt_reset  0
Com_stmt_send_long_data 0
Com_truncate    0
Com_uninstall_plugin    0
Com_unlock_tables   0
Com_update  0
Com_update_multi    0
Com_xa_commit   0
Com_xa_end  0
Com_xa_prepare  0
Com_xa_recover  0
Com_xa_rollback 0
Com_xa_start    0
Compression OFF
Connections 375
Created_tmp_disk_tables 0
Created_tmp_files   6
Created_tmp_tables  0
Delayed_errors  0
Delayed_insert_threads  0
Delayed_writes  0
Flush_commands  1
Handler_commit  0
Handler_delete  0
Handler_discover    0
Handler_prepare 0
Handler_read_first  0
Handler_read_key    0
Handler_read_last   0
Handler_read_next   0
Handler_read_prev   0
Handler_read_rnd    0
Handler_read_rnd_next   0
Handler_rollback    0
Handler_savepoint   0
Handler_savepoint_rollback  0
Handler_update  0
Handler_write   0
Innodb_buffer_pool_pages_data   584
Innodb_buffer_pool_bytes_data   9568256
Innodb_buffer_pool_pages_dirty  0
Innodb_buffer_pool_bytes_dirty  0
Innodb_buffer_pool_pages_flushed    120
Innodb_buffer_pool_pages_free   7607
Innodb_buffer_pool_pages_misc   0
Innodb_buffer_pool_pages_total  8191
Innodb_buffer_pool_read_ahead_rnd   0
Innodb_buffer_pool_read_ahead   0
Innodb_buffer_pool_read_ahead_evicted   0
Innodb_buffer_pool_read_requests    14912
Innodb_buffer_pool_reads    584
Innodb_buffer_pool_wait_free    0
Innodb_buffer_pool_write_requests   203
Innodb_data_fsyncs  163
Innodb_data_pending_fsyncs  0
Innodb_data_pending_reads   0
Innodb_data_pending_writes  0
Innodb_data_read    11751424
Innodb_data_reads   594
Innodb_data_writes  243
Innodb_data_written 3988480
Innodb_dblwr_pages_written  120
Innodb_dblwr_writes 40
Innodb_have_atomic_builtins ON
Innodb_log_waits    0
Innodb_log_write_requests   28
Innodb_log_writes   41
Innodb_os_log_fsyncs    83
Innodb_os_log_pending_fsyncs    0
Innodb_os_log_pending_writes    0
Innodb_os_log_written   34816
Innodb_page_size    16384
Innodb_pages_created    1
Innodb_pages_read   583
Innodb_pages_written    120
Innodb_row_lock_current_waits   0
Innodb_row_lock_time    0
Innodb_row_lock_time_avg    0
Innodb_row_lock_time_max    0
Innodb_row_lock_waits   0
Innodb_rows_deleted 0
Innodb_rows_inserted    0
Innodb_rows_read    40
Innodb_rows_updated 39
Innodb_truncated_status_writes  0
Key_blocks_not_flushed  0
Key_blocks_unused   13396
Key_blocks_used 0
Key_read_requests   0
Key_reads   0
Key_write_requests  0
Key_writes  0
Last_query_cost 0.000000
Max_used_connections    3
Not_flushed_delayed_rows    0
Open_files  86
Open_streams    0
Open_table_definitions  109
Open_tables 109
Opened_files    439
Opened_table_definitions    0
Opened_tables   0
Performance_schema_cond_classes_lost    0
Performance_schema_cond_instances_lost  0
Performance_schema_file_classes_lost    0
Performance_schema_file_handles_lost    0
Performance_schema_file_instances_lost  0
Performance_schema_locker_lost  0
Performance_schema_mutex_classes_lost   0
Performance_schema_mutex_instances_lost 0
Performance_schema_rwlock_classes_lost  0
Performance_schema_rwlock_instances_lost    0
Performance_schema_table_handles_lost   0
Performance_schema_table_instances_lost 0
Performance_schema_thread_classes_lost  0
Performance_schema_thread_instances_lost    0
Prepared_stmt_count 0
Qcache_free_blocks  1
Qcache_free_memory  16758160
Qcache_hits 0
Qcache_inserts  1
Qcache_lowmem_prunes    0
Qcache_not_cached   419
Qcache_queries_in_cache 1
Qcache_total_blocks 4
Queries 1146
Questions   2
Rpl_status  AUTH_MASTER
Select_full_join    0
Select_full_range_join  0
Select_range    0
Select_range_check  0
Select_scan 0
Slave_heartbeat_period  0.000
Slave_open_temp_tables  0
Slave_received_heartbeats   0
Slave_retried_transactions  0
Slave_running   OFF
Slow_launch_threads 0
Slow_queries    0
Sort_merge_passes   0
Sort_range  0
Sort_rows   0
Sort_scan   0
Ssl_accept_renegotiates 0
Ssl_accepts 0
Ssl_callback_cache_hits 0
Ssl_cipher
Ssl_cipher_list
Ssl_client_connects 0
Ssl_connect_renegotiates    0
Ssl_ctx_verify_depth    0
Ssl_ctx_verify_mode 0
Ssl_default_timeout 0
Ssl_finished_accepts    0
Ssl_finished_connects   0
Ssl_session_cache_hits  0
Ssl_session_cache_misses    0
Ssl_session_cache_mode  NONE
Ssl_session_cache_overflows 0
Ssl_session_cache_size  0
Ssl_session_cache_timeouts  0
Ssl_sessions_reused 0
Ssl_used_session_cache_entries  0
Ssl_verify_depth    0
Ssl_verify_mode 0
Ssl_version
Table_locks_immediate   123
Table_locks_waited  0
Tc_log_max_pages_used   0
Tc_log_page_size    0
Tc_log_page_waits   0
Threads_cached  1
Threads_connected   2
Threads_created 3
Threads_running 1
Uptime  2389
Uptime_since_flush_status   2389

How would one use awk to make this calculation of Queries per second (Queries/Uptime):
1146/2389
And print the result?
I'm grepping 2 results from a list of results and need to calculate items/second where 302 is the total item count and 503 the total uptimecount.
At this moment I'm doing
grep -Ew "Queries|Uptime" | awk '{print $2}'

to print out:
302
503

But here i got stuck.

A: You can use something like:
$ awk '/Queries/ {q=$2} /Uptime/ {print q/$2}' file
0.600398

That is: when the line contains the string "Queries", store its value. When it contains "Uptime", print the result of dividing its value by the one stored in queries.
This assumes the string "Queries" appearing before the string "Uptime".

Given your updated input, I see that we need to check if the first field is exactly "Uptime" or "Queries" so that it does not match other lines with this content:
$ awk '$1 == "Queries" {q=$2} $1=="Uptime" {print q/$2}' file
0.479699

A: I think the following awk one-liner will help you:
kent$  cat f
Queries 302
Uptime 503

LsyHP 13:42:57 /tmp/test
kent$  awk '{a[NR]=$NF}END{printf "%.2f\n",a[NR-1]/a[NR]}' f
0.60

If you want to do together with "grep" function:
kent$  awk '/Queries/{a=$NF}/Uptime/{b=$NF}END{printf "%.2f\n",a/b}' f
0.60


text:
Q: How to encode (.) Dot in url Rails I am having routes like below to delete/list an user.
map.connect 'developer/:user_name/delete',:controller=>"developers",:action=>"delete",:method=>:delete

map.connect 'developer/:user_name/list',:controller=>"developers",:action=>"list",:method=>:get

While listing the user by encoding the Dot with %2E, i can see the success response
http://localhost:3000/developer/testuser%2Ehu/list

But While trying to delete the user who containing the Dot(.), throws 404 error.
http://localhost:3000/developer/testuser%2Ehu/delete, how to fix this issue.

A: I just had a similar problem, my search page url is /search/search_term. When search_term had a dot, Rails interpreted it as the request format. If I tried to search for book.html, it actually searched for book, because Rails interpreted html as the format. An unrecognized format would return an error.
In my case, the first solution from Avdi Grimm didn't work, because my search is paginated, and the page number also goes in the url (/search/book/2). The solution for me was accepting everything but a slash for the search_term (the last solution from Avdi Grimm's post):
resources :users, :constraints => { :id => /[^\/]+/ }

A: The dot is not allowed by default in Rails routing because the dot is considered the extension of the page. You should avoid using dots in URLs.
However, in your case you can instruct Rails to consider the dot for the :user_name parameter passing a regular expression.
map.connect 'developer/:user_name/list', :controller => "developers", :action => "list", :method=> :get, :user_name => /[\w.]+/

PS. Because of map.connect, you are using a very old version of Rails (Rails < 3). You should upgrade your application.

A: Avdi Grimm wrote on this subject: http://avdi.org/devblog/2010/06/18/rails-3-resource-routes-with-dots-or-how-to-make-a-ruby-developer-go-a-little-bit-insane/
You'll want to do something like this (full credit to avdi)
  resources :users, :constraints => { :id => /.*/ } do
    resources :projects
  end

A commenter on the post says you can also do:
resources :users, :id => /.*/

A: Are you doing a DELETE request to the delete url? Note that the route is defined with :method=>:delete, so it expects DELETE request (not GET).


text:
Q: WPF ICommand CanExecute get called even though there is a modal window Let's say I have an user control with a button
<UserControl>
<Grid>
    <Button x:Name="button" Content="Show Dialog" DataContext="{Binding m_btnShowDialog}" Style="{StaticResource ButtonVM}" Command="{Binding Cmd}" HorizontalAlignment="Left" Margin="29,56,0,0" VerticalAlignment="Top" Width="75" >
</Grid>
</UserControl>

The command class implements ICommand interface.
When the focus is on the above dialog, the CanExecute sometimes get called.
That is something to be expected.
The problem is when I click the button, the Execute method get called and a new modal dialog pops up.
The focus should be on the new dialog but for some reasons, the CanExecute still get called when I interract with the new dialog.
Is that behavior normal?
And how can I override that behavior?
I don't want CanExecute method of commands attached to controls of parent dialog to be called when a child modal dialog is showing up.

A: This is expected. Quoting directly from WPF expert Josh Smith :

WPF will automatically ask all of the commands being used in your UI
  if they can execute. This happens at various times, such as when input
  focus shifts to another control, an item is selected in a list, etc.
  You can also programmatically trigger this to happen by calling the
  CommandManager's InvalidateRequerySuggested static method. This all
  seems magical, dreamy, and almost too good to be true.

You can get more detailed and clear explanation here
You can override behavior using CanExecuteChanged event in your command implementation.
class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return maybeTrueOrFalse;
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

public void Execute(object parameter)
{
// Do something awesome.
}
}


text:
Q: How does one get a ListView (GridView) cell's contents when clicked with a mouse I am trying to get the text value of a "cell" inside of a GridView that is set as the view of a ListView. I do not want to get the SelectedItem of the ListView as that just returns my entire View Model (but not which property the cell refers to).
I am able to get the text value by responding to direct mouse events (up down or whatever) and if the value is a textblock, obviously I can use the text. This works great and as of right now this is my only solution, although its currently limited.
I would like to take it a step further and be able to click anywhere with in the cell area, navigate around to find the appropriate textblock and then use that value. I have tried a half million ways to do this but what seems logical doesn't seem to quite work out like it should.
Setup:
I have a dynamic GridView that creates its own columns and bindings based on data models that I pass to it. I am using a programmatic cell template (shown below) to have individual control over the cells, particularly so I can add a "border" to it making it actually separate out each cell. I have named the objects so I can access them easier when I'm navigating around the VisualTree.
Here is the Template Code. (Note that the content presenter originally was a textblock itself, but this was changed for later flexibility)
private DataTemplate GetCellTemplate(string bindingName)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("<DataTemplate ");
        builder.Append("xmlns='http://schemas.microsoft.com/winfx/");
        builder.Append("2006/xaml/presentation' ");
        builder.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
        builder.Append("xmlns:local = 'clr-namespace:XXXXXXXX");
        builder.Append(";assembly=XXXXXXXXX'>");
        builder.Append("<Border Name=\"border\" BorderThickness=\"1,0,0,0\" BorderBrush=\"Gray\" Margin=\"-6,-3,-6,-3\">");
        builder.Append("<Grid Margin=\"6,3,6,3\">");
        builder.Append("<ContentPresenter Name=\"content\" HorizontalAlignment=\"Stretch\" Content=\"{Binding ");
        builder.Append(string.Format("{0}", bindingName));
        builder.Append("}\"/>");
        builder.Append("</Grid>");
        builder.Append("</Border>");
        builder.Append("</DataTemplate>");
        DataTemplate cellTemplate= (DataTemplate)XamlReader.Parse(builder.ToString());
        return cellTemplate;
    }

What I have Tried:
The logical approach for me was to react to a Mouse event. From the object that had the mouse event I would do either
A. Look at its children to find a textblock, or
B. Get its parent then look for child with a textblock.
My assumption is that if I click in white space I'm clicking in a container that has my textblock. So far the two things that come up are a Border and a Rectangle (if I don't click the text itself). A. Returns absolutely nothing except for the recangle and the border. When I do B i can find textblocks but they are every single text block in the entire row.
So what I try to do from that is get all textblocks, then go backwards till I find which one has a IsMouseOver property as true. It turns out none of these objects EVER have a IsMouseOver except the content presenter for the entire row. So this seems to indicate to me is that the whitespace in the cells does not actually contain the textblock.
What I find is that when I click on the Border and start looking at children, I eventually get to a container that has a rectangle (the rectangle I click) and a grid row view presenter. The presenter shows all of the objects inside the row (hence why i would get all textblocks when i do this recursive scan).
Here is some of the code used to do this to get an idea of what i'm doing. I have written about 10 different versions of this same recursive code generally attempting to find who has the Mouse over it and is related to a textbox.
private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        object original = e.OriginalSource;
        if (original is TextBlock)
        {
            this.valueTextBlock.Text = ((TextBlock)original).Text;
        }
        else if (original is FrameworkElement)
        {
            var result = GetAllNestedChildren<Border>(VisualTreeHelper.GetParent((DependencyObject)original)).Where(x => x.Name == "border").Where(x => HasAChildWithMouse(x)).ToList();

        }
        else
        {
            this.valueTextBlock.Text = string.Empty;
        }
    }

    private bool HasAChildWithMouse(UIElement element)
    {
        if (element.IsMouseOver || element.IsMouseDirectlyOver)
            return true;
        var childCount = VisualTreeHelper.GetChildrenCount(element);
        for (int i = 0; i < childCount; ++i)
        {
            var child = VisualTreeHelper.GetChild(element, i);
            if (child is UIElement)
                if (HasAChildWithMouse((UIElement)child))
                    return true;
        }
        return false;
    }
private IEnumerable<T> GetAllNestedChildren<T>(DependencyObject obj) where T : UIElement
    {
        if (obj is T)
            yield return obj as T;
        var childCount = VisualTreeHelper.GetChildrenCount(obj);
        for (int i = 0; i < childCount; ++i)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            foreach (var nested in GetAllNestedChildren<T>(child))
                yield return nested;
        }
    }

    private T GetObjectByTypeParentHasMouse<T>(DependencyObject obj) where T : UIElement
    {
        if (obj is T)
        {
            if ((VisualTreeHelper.GetParent(obj) as UIElement).IsMouseOver )
            {
                return obj as T;
            }
        }
        var childCount = VisualTreeHelper.GetChildrenCount(obj);
        for (int i = 0; i < childCount; ++i)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            var correctType = GetObjectByTypeParentHasMouse<T>(child);
            if (correctType != null)
                return correctType;
        }
        return null;
    }

    private T GetContainedType<T>(DependencyObject obj, bool checkForMouseOver) where T : UIElement
    {
        if (obj is T && ((T)obj).IsMouseOver)
            return obj as T;
        var childCount = VisualTreeHelper.GetChildrenCount(obj);
        for (int i = 0; i < childCount; ++i)
        {
            var child = VisualTreeHelper.GetChild(obj, i);
            var correctType = GetContainedType<T>(child, checkForMouseOver);
            if (correctType != null)
                return correctType;
        }
        return null;
    }

The other approach I took was to start with the TextBlock itself, find its containing parent and find out how i can navigate to the answer. I find the templateparent is the ContentPresenter (named ="content") I find the grid, and then the border. The parent of the border is a content presenter whos content is the data view model for the entire row. The parent of this contentpresenter is the grid column's presenter. This is the same one that i was navigating up to in the other one.
It would appear that the first approach objects while are contain the cell do not actually contain the textblock or the entire cell templated items. It would appear to me there is no way to go from the Border or Rectangle that is clicked, back to the actual text field.
"Long story short" is there ANY way to make this connection?
(Btw I am not willing to give up this ListView/GridView because its payoffs far outweigh this negative and I'd gladly give up on this idea to keep the rest).

A: I think you sjould be able to either
1) Add some kind of (toggle)button to the root of your data template, and either bind to Command and handle it on your viewmodel or bind to IsChecked/IsPressed and handle changes via data triggers or w/e on the view side.
2) Add EventTrigger to your datatemplate at some point, and handle PreviewNouseUp/Down  events there via simple animations.


text:
Q: python how to use dictionary I am trying to read data from some files and save those into dictionary
The file that I am reading looks like below
file_1.txt
line 1: Given Problem1, Incorrect Answer, Correct Answer, Rule
line 2:  ___blank___ , Incorrect_Answer
line 3:  ___blank___ , Incorrect_Answer
line 4: Given Problem2, Incorrect Answer, Correct Answer, Rule
line 5:  ___blank___ , Incorrect_Answer
line 6:  ___blank___ , Incorrect_Answer

So there are one Question, Correct Answer, and Rule but several Incorrect_Answer
The form of dictionary that I want to get looks like below
{Question, Incorrect_Answer[...(array maybe?)], Correct_Answer, Rule }
I got so far this.
for line in open(thatfile.txt,'r').readlines()[2:]: # scan through the file, but skip the first two lines that contain metadata (data headers)
if line[0].startswith('Question '):
    continue:
elif line starts with ' ' #there will be only incorrect_answer in this line
    input line[1] to Incorrect_Answer array
else
    input line[0] to Question
    input line[1] to Incorrect_Answer array
    input line[2] to Correct_Answer
    input line[3] to Rule $

A: You want to start with a main output result container and a question placeholder:
>>> result = {}
>>> question = None

Then you do your normal processing of each line while watching for question changes, appending incorrect responses:
>>> for line in txtfile:
...   pieces = line.split(',')
...   if pieces[0] not in (question, ' ___blank___ '):
...     question = pieces[0]
...     result[question] = {'Incorrect': [pieces[1]],
...                         'Correct': pieces[2],
...                         'Rule': pieces[3]}
...   elif pieces[0].startswith(' '):
...     result[question]['Incorrect'].append(pieces[1])

Which gives you:
>>> pprint(result)
{'Given Problem1': {'Correct': ' Correct Answer',
                    'Incorrect': [' Incorrect Answer',
                                  ' Incorrect_Answer',
                                  ' Incorrect_Answer'],
                    'Rule': ' Rule'},
 'Given Problem2': {'Correct': ' Correct Answer',
                    'Incorrect': [' Incorrect Answer',
                                  ' Incorrect_Answer',
                                  ' Incorrect_Answer'],
                    'Rule': ' Rule'}}

A: I will assume that - as you are writing above - the question and answers are separated by commas.
alldata = []
# scan through the file, but skip the first two lines
# that contain metadata (data headers)
for line in open(thatfile.txt,'r').readlines()[2:]:
    lineparts = line.split(',') # or how else can one separate the parts?
    if len(lineparts) == 4:
        thisset = {'Question': lineparts[0],
                   'Incorrect': [lineparts[1]],
                   'Correct': lineparts[2],
                   'Rule': lineparts[3]}
        alldata.append(thisset)
    # if there are not 4 parts and the data is perfect, this is an incorrect answer
    else:
        thisset["Incorrect"].append(lineparts[1])

print("Incorrect answers to first question:")
print(alldata[0]["Incorrect"])

So in the end, you get a list of dictionaries 'alldata'. Each dictionary corresponds to a problem. The incorrect answers are a themselves again a list of strings.


text:
Q: Trying to make an each method, like in jQuery, with vanilla JS Element.prototype.each = function(fn) {
  for(var i = 0; i < this.length; i++) {
    fn(i);
  }
};

var li = document.getElementsByTagName('li');

li.each(function(i) {
  this.style.borderBottom = '1px solid red';
});

I'm trying to make an each method like in jQuery. I tried many things in the for loop and in the callback but I got errors. I'm sure this is something to do with the 'this' context.

A: You can use call to set context
EDIT : Element was not the right class, it should be NodeList and HTMLCollection
NodeList.prototype.each = HTMLCollection.prototype.each = function(fn) {
  for(var i = 0; i < this.length; i++) {
    fn.call(this, i);
  }
};

When you use Function.prototype.call it allows you to bind a context AKA this to a function
There are 3 ways AFAIK to do this:

*

*call (as said above)

*apply (which works like call except it takes only two arguments, the second being an array)

*bind (which is used for currying)

Also note that as of DOM level 4 (ES6 harmony) there is a new class called Elements which extends Array and is meant to replace NodeList/HTMLCollection, so you wouldn't need to actually extend it in ES6 to add an each method and use Array.prototype.forEach instead (though you won't be able to use this in your callback.

A: document.getElementsByTagName('li') returns HTML Collection object, not Element.
It's quite easy to duplicate jQuery each (the only difference between native forEach and $.each is order of parameters - $.each uses (i,el) tuple, [].forEach uses (el,i) tuple). In modern browsers (all except IE8) you can just use:
document.getElementsByTagName('li').constructor.prototype.each = function(fn,thisArg) {
    [].forEach.call(this, function(el,i,array) {
        fn.call(thisArg, i,el,array);
    });
};

I don't recommend to extend native prototypes, you should use  [].forEach.call(yourNodeList, func) instead. It's possible to do yourNodeList = [].slice.call(yourNodeList); to convert your DOM collection to plain array.

A: I recently had cause to solve a particular problem in a similar manner and was interested to see how others had approached it.  Bearing in mind the caveats posted about extending native prototypes, I'm just logging my solution, implemented in a browser environment only, for posterity.
/* For Arrays, enumerable Objects,
   DOMTokenLists and HTMLCollections etc */
Object.prototype.each = function(fn) {
    (Array.isArray(this) ? this : (this.constructor.name === 'Object' ? Object.keys(this) : [].slice.call(this))).forEach(fn);
};

:)


text:
Q: version control for newbie I'm fairly new to programming and web dev and up until now I haven't worked on any projects that I felt were large enough to warrant using proper version control. However, I am now working on a project that is getting bigger and bigger (very exciting!). I think it would be prudent to use some kind of version control. At the moment I work alone, but if this project gets where I want it to then I expect at some point I am going to need (and want!) some other people to come on board.
My problem is because I've never used version control, I don't really know what it is, how it works etc etc.
I hope this question isn't classed as subjective. I'm not asking for people to tell me which version control they think is best, I'm quite happy to spend some time looking around and trying them out for myself.
I'm really wanting some people to either give me a quick run down of how a standard version control system works (I know they'll all be different, but I'm talking basics here) and if possible, in a non-subjective way, to explain the differences between some of the major players. ie what is the difference between mercurial and git, not which is better - I'll decide that for myself thank you!

A: Wikipedia answers:
http://en.wikipedia.org/wiki/Revision_control
However you should note that reading about VCS's its quite useless until you do it yourself. I never understood this DVCS(Distributed Version Control System) concept until I started using it. I had some similar experience with trying to figure out the benefits of using SVN, Mercurial and Git, it all became clear when I started using its best practices.

A: If you're working alone, can the distributed model work?
I use Subversion for my own work at home.
I think the Subversion red bean book is a great general read about how to use version control: branching, tagging, etc.  It's worth reading a bit even if you don't choose Subversion.


text:
Q: Show a Fragment over everything else currently in view, and then remove it on button click I'm currently trying to make a fragment come into view over everything else in the activity. Then, on a button press, the fragment should disappear and reveal everything that was there previously.
Here is my current attempt:
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
                    .replace(currentFragment.getId(), fragment);
            transaction.addToBackStack(null);
            transaction.commit();

and on the button press, I do:
            getFragmentManager().popBackStack();

But the issue I'm having it the fragment doesn't totally inflate overtop all the other views, and the button press is not having the desired affect. Any suggestions?
EDIT: It's a bottomNavigationView that's still showing, I'd like to inflate overtop of that.

A: You can use Dialog fragment like:
public class PopUpDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Context context = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    builder.setTitle("Your title")
            .setMessage("Your message")
            .setPositiveButton("Button name", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   //Do your stuff here

                   dismiss();
               }
           });
    return builder.create();
}

}
Then you call it from your activity like:
PopUpDialogFragment fragment = new PopUpDialogFragment();
fragment.show(getFragmentManager(), "popUp");

If you want a Fragment with your own custom view then you create one with onCreateView method.
public class PopUpDialogFragment extends DialogFragment {

private Button button;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
           container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.your_layout,
           container, false);
    button = view.findViewById(R.id.your_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Do your stuff here

            getDialog().dismiss();
        }
    });

    return view;
}

}


text:
Q: new android project share/copy the same string.xml file I am new to the android development as well as eclipse IDE, but I do have some experience in using Java (Used to work with C# in vs2008 before). Right now I have both Eclipse and Android SDK up and running. I did manage to do the "Hello, world" in android. But when ever I am making a new project it shows up in the solution explorer next to the previous project "Hello, World" and it shares/copy the string.xml, so when ever I run it, it give me Hello World previous project result.
Please tell me what to do and thank you.

A: Are you sure it is sharing the file? Whenever you create a new Android project in Eclipse, it will make a default strings.xml for you, containing:
<resources>
<string name="hello">Hello World, [...]!</string>
<string name="app_name">[...]</string>
</resources>

And your new projects will simply appear below your old ones in the Eclipse Navigator/Package Explorer (if you are using the same workspace). You can switch workspace or remove the old HelloWorld project if you don't want it to be there.
If you try to 'run' a particular file in a project it will only run the associated project, so there is no harm in having multiple projects in a workspace.


text:
Q: Desktop app opening a server-side Blazor page protected by AD auth I have a server-side Blazor app running on Azure AppService protected by AAD auth. Authorized AD users (admins) are able to access and use the app.
What I'm want to achieve is to allow other users to access only a specific page of the Blazor app. Users would access the app from WPF app, themselves not necessarily being AD users, but AD application user (daemon app). WPF app gets the token (v2.0) and opens the page in a browser with the Authorization header (bearer token), however Blazor doesn't not interpret the auth header in request and threats the user as unauthenticated.
App registrations should have been setup properly as I'm able to access API when using this approach.
It this scenario possible? If so, any ideas what I could be doing wrong?

A: This scenario sounds like it is going quite a lot against general recommendations.
You really should not be doing "daemon app" authentication from a WPF app as it is not a confidential client application (and neither a daemon app). It runs on a user device, exposing the application's credential to any user.
Authentication flows that use secrets should never be used from a user device.
Secondly, a Blazor application is not generally one that can accept requests from an application.
Your WPF application should be calling an API, not a UI application.
What you should instead have is:

*

*WPF app authenticates the user and acquires a token on their behalf to your API

*WPF app calls the API with the access token

*API validates the access token, authorizes access for the user and app, returns data

The Blazor app could be using this same API in its front-end code in a similar manner.
But I don't think you are going to be able to put it in the middle of your client app and the API.


text:
Q: apns payload message json format directly shown we have implemented apple apns push notification. Configured pem file and device tokens in python. They trigger json payload like this

{"aps" : {
   "alert" : "got 1 new offer. To view, please tap here."
  },"notification_type":"New Offer
  history","redirect_link":"offers"}.

we got notification, but the full json shows in message. we need to display only alert message only on notification message

A: I think for notification to display data instead of json in push try below json
{
   "aps":{
      "alert":"This is your message to be displayed",
      "sound":"default",
      "badge":1
    },
   "Data":{"key1":"val1", "key2":"val2"}
}

The alert content will be displayed in push and the Data Key/Val pairs is your custom data that you can pass in payload and access it in your code.
The code shared above is the working code I have used in most of my API projects.

A: Here while you are generating payload you need to create Array in Python and than need to apply json encode and than pass that json string to APNS server.
In PHP generally developer are doing below code:
//Create Payload body with array.
$body['aps'] = array(
     'alert' => $message,
     'sound' => 'default'
     );

//Convert Payload array to JSON
    $payload = json_encode($body);

//Pass message to APNS
    $msg = chr(o) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

By This we can achieve APNS message in iPhone.
Hope this will help you.

A: you need to get the data out from dictionary object like
NSDictionary *aps = [payload objectForKey:@"aps"];
NSString *alert  = [aps objectForKey:@"alert"]

A: plz use this
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
        {
           if(application.applicationState == UIApplicationStateInactive)
        {
               NSLog(@"Inactive");

           //do your things when you click on notification
        }
        else if (application.applicationState == UIApplicationStateBackground)
         {

                        NSLog(@"Background");

        }
          else if (application.applicationState == UIApplicationStateActive)
          {
          NSLog(@"Active");
     NSDictionary *aps = [userInfo objectForKey:@"aps"];
NSString *alert  = [aps objectForKey:@"alert"]

        UIAlertController *alertController = [UIAlertController
                                                              alertControllerWithTitle:nil
                                                              message:alert
                                                              preferredStyle:UIAlertControllerStyleAlert];

                        UIAlertAction *okAction = [UIAlertAction
                                                   actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                                                   style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action)
                                                   {
                                              //do on ok press
                                                   }];

                        [alertController addAction:okAction];

                        UIViewController *ob = [self  getTopViewController];
                        [ob presentViewController:alertController animated:YES completion:nil];

          }
        }

    -(id)getTopViewController{

               UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

                while (topController.presentedViewController) {
                    topController = topController.presentedViewController;
                }
                if (![topController isKindOfClass:[NSNull class]]) {

                    return topController;
                }

        }

here i am getting top viewcontorller and show alert msg

A: You need to get the data from dictionary object and message show on alertview
 - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

                if (userInfo) {
NSString *message = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"];
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Info" message: message preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {

                [alert dismissViewControllerAnimated:YES completion:nil];

            }];
            [alert addAction:ok];
            [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        }
    }

A: This is an old question, but I feel the responses didn't answer the question. The whole JSON is showing because the payload is not formatted correctly I think. It should look like this:
{
   "aps" : {
      "category" : "NEW_MESSAGE_CATEGORY"
      "alert" : {
         "body" : "Acme message received from Johnny Appleseed", //the message
      },
      "badge" : 3,//This is the little number icon
      "sound" : "chime.aiff" //The sound that will make on the device
   }
}

You can find more information here: Apple Docs

A: Resurrecting old post, but I had to post this!
After 4 years, no one noticed that the problem in characters! That json is invalid because last 3 double-quotation marks are italic (left/right)! ASCII code of normal double-quotation is 34, while the italic-quote is Unicode char with 3 bytes in UTF8 (0xE2 0x80 0x9D). Moreover, that json is also not valid because it ends with '.'.
So this means that json is written by hand. Generate it through a class or dictionary or any other ways you prefer and you'll be fine, just don't write any form of markups/markdowns by hand. Or at least you can validate your hand-written json by using an online json validator.


text:
Q: Bootbox is not working when calling a modal form I am using bootbox modal for calling a  modal form but form is not appeared as a modal.  Nothing happens when we click compose.  I want to open a form in a model after clicking the compose button but its not working.
 Compose Mail

<form id="loginForm" method="post" class="form-horizontal" style="display: none;">

        To

            <input type="text" class="form-control" name="to" />

        Subject

            <input type="text" class="form-control" name="ssubject" />

        Message

            <textarea name="smessage" class="form-control"></textarea>

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

</form>

This is html form and the java script file are placed in same page inbox.php
$(document).ready(function() {
$('#loginForm').formValidation({
    framework: 'bootstrap',
    icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        to: {
            validators: {
                notEmpty: {
                    message: 'Please type destination bo'
                }
            }
        },
        ssubject: {
            validators: {
                notEmpty: {
                    message: 'Please type subject'
                }
            }
        },
        smessage: {
            validators: {
                notEmpty: {
                    message: 'Please type some message'
                }
            }
        }
    }
});

// Login button click handler
$('#loginButton').on('click', function() {
    bootbox
        .dialog({
            title: 'Compose Message',
            message: $('#loginForm'),
            show: true // We will show it manually later
        })
        .on('shown.bs.modal', function() {
            $('#loginForm')
                .show()                             // Show the login form
                .formValidation('resetForm', true); // Reset form
        })
        .on('hide.bs.modal', function(e) {
            // Bootbox will remove the modal (including the body which contains the login form)
            // after hiding the modal
            // Therefor, we need to backup the form
            $('#loginForm').hide().appendTo('body');
        })
       .modal('show');

 });
});
</script>

and here's the test/send.php code.
<?php
$from="0";
$to=$_POST["to"];
$subject=$_POST["ssubject"];
$message=$_POST["smessage"];
//echo $to.$message;
//validate before insert
if(strlen($subject)>50){
    echo "Subject was too long";
    die();
}
if(strlen($message)>150){
    echo "Message was too long";
    die();
}
include('../dbsource.php');
$mysqli=connect();
if(insert($mysqli,$from,$to,$subject,$message)>0)
    echo "Message was sent";
else
    echo "Message was not sent";
?>

<?php
function insert($mysqli,$from,$to,$subject,$message){
    $mdate=date('Y-m-d');
    $mtime=date('H:i:s');

    $query = "INSERT INTO messages (mfrom,mto,subject,message,mdate,mtime)".
        "VALUES ('$from','$to','$subject','$message','$mdate','$mtime')";
    if($mysqli->query($query)>0)
        return($mysqli->insert_id);
    else
        return 0;
}
?>

The modal does not appear.
I dont know why is the modal is not appearing in this project.
Can anybody help me ?
 error in console:


text:
Q: Chess Engine - Represent bitboard in 32bit Nasm I'm trying to write a chess engine in 32bit nasm. I read up on bit boards and I want to represent the board using bit boards, however the fact i'm working with 32bit registers is an inconvenience. What I did is divide each bit board into 32bit sections. But would it be better to just define qWords and split them up on the fly?
This is my board data section
                    ;bitboards for white
    whiteLowerPawns     dd  0xff00
    whiteLowerBishops   dd  0x24
    whiteLowerKnights   dd  0x42
    whiteLowerCastles   dd  0x81
    whiteLowerQueens    dd  0x8
    whiteLowerKing      dd  0x10

    whiteUpperPawns     dd  0x0
    whiteUpperBishops   dd  0x0
    whiteUpperKnights   dd  0x0
    whiteUpperCastles   dd  0x0
    WhiteUpperQueens    dd  0x0
    WhiteUpperKing      dd  0x0

                    ;bitboards for black
    blackUpperPawns     dd  0xff0000
    blackUpperBishops   dd  0x24000000
    blackUpperKnights   dd  0x42000000
    blackUpperCastles   dd  0x81000000
    blackUpperQueens    dd  0x8000000
    blackUpperKing      dd  0x10000000

    blackLowerPawns     dd  0x0
    blackLowerBishops   dd  0x0
    blackLowerKnights   dd  0x0
    blackLowerCastles   dd  0x0
    blackLowerQueens    dd  0x0
    blackLowerKing      dd  0x0


text:
Q: A variant of Dominated Convergence Theorem Let $(a_1,a_2,\ldots)$ be a sequence of nonnegative numbers summing up to $1$.
Given a measurable space $(X,\mathscr{F})$, assume also the $f:X\to \mathbb{R}$ is a measurable function, and let $(\mu_1,\mu_2,\ldots)$ be a sequence of probability measures $\mathscr{F} \to \mathbb{R}$.
Then, is it true that
$$
\int_X f \mathrm{d}\left(\sum_{i\ge 1} a_i\mu_i\right)=\sum_{i\ge 1}a_i \left(\int_X f \mathrm{d}\mu_i\right)\,\,\,?
$$

A: Since $(a_1,a_2,\ldots)$ be a sequence of nonnegative numbers summing up to $1$ and $(\mu_1,\mu_2,\ldots)$ be a sequence of probability measures $\mathscr{F} \to \mathbb{R}$, it is easy to see that $\sum_{i\ge 1} a_i\mu_i$ is in fact a (probability) measure.
Note that, for each $j$, $\mu_j \ll \sum_{i\ge 1} a_i\mu_i$. Since both measures are finite, we can apply Radon-Nikodym Theorem. So there is $h_j$ a measurable finite non-negative function such that
$$ \int_X f \mathrm{d}\mu_j = \int_X f h_j \mathrm{d}\left(\sum_{i\ge 1} a_i\mu_i\right) \tag{1}$$
Since $\sum_{i\ge 1} a_i\mu_i \ll \sum_{i\ge 1} a_i\mu_i$, we can use Radon-Nikodym Theorem again (uniqueness a.e. of Radon-Nikodym derivative) to conclude that
$$\sum_{i\ge 1} a_j h_j = 1 \textrm{ a.e. }$$
Then, from $(1)$, either using Dominated Convergnece Theorem (if $f$ is integrable) or Monotone Convergence Theorem (if $f$ is non-negative), we have
$$ \sum_{j\ge 1} a_j\int_X f \mathrm{d}\mu_j = \sum_{j\ge 1} a_j\int_X f h_j \mathrm{d}\left(\sum_{i\ge 1} a_i\mu_i\right) = \int_X f \left(\sum_{j\ge 1} a_j h_j\right) \mathrm{d}\left(\sum_{i\ge 1} a_i\mu_i\right) = \\=\int_X f  \mathrm{d}\left(\sum_{i\ge 1} a_i\mu_i\right)$$

A: There are many ways to prove that. Ramiro's solution is beautiful, but, in fact, Radon-Nikodym theorem is not needed.
This alternative solution resembles (one possible) proof of the Dominated Convergence theorem and relies on absolute continuity of Lebesgue integral.
Denote $\sum_{i \ge 1} a_i \mu_i$ by $\mu$ and suppose $f$ is $\mu$-integrable. Also, in $\int_X$ letter $X$ is omitted.
Let us estimate
$$ \left| \int f\,\mathrm{d}\mu - \sum_{i=1}^N a_i \int f\,\mathrm{d}\mu_i \right| = \left| \int f\,\mathrm{d} \!\left( \sum_{i \ge N+1} a_i \mu_i \right) \right| \le \int \lvert f \rvert \,\mathrm{d} \!\left( \sum_{i \ge N+1} a_i \mu_i \right) \tag{1}$$
Take $\varepsilon > 0$. By absolute continuity of the integral, there exists $\delta > 0$, s.t. $\int_A \lvert f \rvert \,\mathrm{d}\mu < \varepsilon$, whenever $\mu(A) < \delta$.
Sets $A_M =  \{ x\in X : \lvert f(x) \rvert > M \}$ decrease to $\varnothing$ as $M\rightarrow \infty$. So we can find $M$, s.t. $\mu(A_M) < \delta$. Therefore,
\begin{align*}
\int \lvert f \rvert \,\mathrm{d} \!\left( \sum_{i \ge N+1} a_i \mu_i \right) &= \int_{A_M} \lvert f \rvert \,\mathrm{d} \!\left( \sum_{i \ge N+1} a_i \mu_i \right) + \int_{X \setminus A_M} \lvert f \rvert \,\mathrm{d} \!\left( \sum_{i \ge N+1} a_i \mu_i \right) \le \\ &\le \int_{A_M} \lvert f \rvert \,\mathrm{d} \mu + M \!\left( \sum_{i \ge N+1} a_i \mu_i(X \setminus A_M) \right) < \varepsilon + M \sum_{i \ge N+1} a_i
\tag{2}
\end{align*}
Combining $(1)$ with $(2)$, we conclude that for sufficiently large $N$
$$
\left| \sum_{i=1}^N a_i \int f\,\mathrm{d}\mu_i - \int f\,\mathrm{d}\mu \right| < 2\varepsilon,
$$
hence the series $\sum_{i \ge 1} a_i \int f\,\mathrm{d}\mu_i$ converges to $\int f\,\mathrm{d}\mu$.

If $f$ is positive but its integral is infinite you may approximate $f$ by $f^M (x) = \max\{f(x), M\}$ and exchange summation with the limit as $M \rightarrow \infty$, using uniformness of the latter, to show that the series
$\sum_{i \ge 1} a_i \int f\,\mathrm{d}\mu_i$ diverges to infinity. Though I would call this «a variant of Monotone Convergence theorem».
Alternatively, you may begin with simple functions, as was suggested in other answers.

Note, that your claim is formally not true for all measurable functions. If the series $\sum_{i \ge 1} a_i \int f\,\mathrm{d}\mu_i$ converges, even absolutely, $\mu$-integrability does not follow: you may have $\int f \,\mathrm{d} \mu_i = 0$, but $a_i \int \lvert f \rvert \,\mathrm{d} \mu_i$ summing up to infinity. For instance, this is possible when $\mu_i$ are supported on disjoint sets, you may think of a counterexample on $\mathbb R$.

A: Here's another approach. One minor but important detail to verify is that $\mu$ is indeed a measure. As will be shown below, once this is verified, the result immediately follows.
We begin by simplifying notation. Suppose that $\nu_1,\nu_2,\dots$ are measures on $(X,{\cal F})$. Define
$$ \nu: {\cal F}\to [0,\infty)$$
by letting
$$\nu(A) = \sum_{i} \nu_i(A).$$
We will show that $\nu$ is a measure on $(X,{\cal F})$.
Indeed, $\nu(\emptyset)=0$.
Now suppose that $A_1,A_2,\dots$ are disjoint elements of ${\cal F}$.
Then
$$ \nu(\cup A_j) = \sum_i \nu_i(\cup A_j) =\sum_i \lim_{n\to\infty} \nu_i (\cup_{j\le n}  A_j)=(*)$$
Therefore by the monotone convergence theorem,
$$ (*) = \lim_{n\to\infty} \sum_i \nu_i (\cup_{j \le n} A_j)= \lim_{n\to\infty} \sum_{j \le n} \sum_i \nu_i(A_j)= \lim_{n\to\infty} \sum_{j\le n} \nu(A_j)=\sum_{j} \nu(A_j).$$
Now we can integrate with respect to $\nu$:
$$ \int_A d \nu = \nu (A) = \sum_{i} \nu_i(A) = \sum_i \int_A d \nu_i .$$
This clearly extends to any simple function:
$$ \int \phi d\nu  = \sum_i \int \phi d\nu_i,$$
Now for a nonnegative measurable function $f$, we have a sequence of nonnegative simple functions $\phi_n$ such that $\phi_n \nearrow f$. It the follows from monotone convergence that
$$ \int f d \nu = \lim_{n\to\infty} \int \phi_n d \nu = \lim_{n\to\infty} \sum_i \int \phi_n d \nu_i=(**)$$
Now apply monotone convergence to the righthand side to obtain
$$(**) = \sum_i \lim_{n\to\infty} \int \phi_n d \nu_i =\sum_i \int f d\nu_i.$$

A: I like Ramiro's elegant answer, but this one is more basic. First, define $\mu:=\sum_ia_i\mu_i$. By definition, we have that $\int f\mathrm d\mu=\sum_ia_i\int f\mathrm d\mu_i$ when $f=\mathbf1_A$, and so this extends by linearity to simple functions. If $(f_n)$ is an increasing sequence of simple functions with $0\le f_n\uparrow f$ then $0\le a_i\int f_n\mathrm d\mu_i\uparrow a_i\int f\mathrm d\mu_i$ for each $i$ by the monotone convergence theorem, so by two more applications of the monotone convergence theorem
$$
\int f\ \mathrm d\mu=\lim_{n\to\infty}\int f_n\ \mathrm d\mu=\lim_{n\to\infty}\sum_{i\ge1}a_i\int f_n\ \mathrm d\mu_i=\sum_{i\ge1}a_i\int f\ \mathrm d\mu_i.
$$
For general $f\in L^1(\mu)$, split into positive and negative parts and we are done.


text:
Q: How to stop android studio from running How to I stop my code from running in Android Studio? I have tried selecting the program under the Java folder, but the "Terminate Application" button is grayed out. It's really annoying how the long is going crazy even though I have ended the app on my phone...
Here is a screenshot of my screen if it helps:

A: If you are referring to the lines in the logcat that keep appearing even when you app is stopped, this is normal, your phone keeps running other apps and logging status messages.
To suppress this output try selecting you application in the drop down menu on the right to show only your app's output

A: From this answer:
You need to select the process com.mycompany.myfirstapp and then press the Terminate Application button.


text:
Q: How to crop the difference of two images? I'd like to take these 2 images:

And essentially produce this:

I've gotten as far as using compare with fuzz to define the part that has changed. Is it possible to then get the bounding box of this area and crop the second frame?

A: I would do something along these lines:
convert a.jpg b.jpg -colorspace gray -blur 0x2 \
       -compose difference -composite          \
       -threshold 20% out.jpg

Convert to greyscale and blur a little to hide small differences, then calculate the difference and threshold to make a binarised image like this:

Then I would go for a Connected Components Analysis to find the biggest object in the image, like this:
convert a.jpg b.jpg -colorspace gray -blur 0x2     \
   -compose difference -composite -threshold 20%   \
   -define connected-components:verbose=true       \
   -define connected-components:area-threshold=100 \
   -connected-components 8 out.jpg

Objects (id: bounding-box centroid area mean-color):
  0: 1029x1079+0+0 515.0,538.4 1102870 srgb(0,0,0)
  17: 76x147+326+564 366.5,641.4 5827 srgb(252,252,252)
  22: 18x50+358+612 365.1,635.3 568 srgb(0,0,0)
  11: 34x31+810+345 825.5,361.1 317 srgb(255,255,255)
  16: 57x97+25+539 52.3,587.2 286 srgb(255,255,255)
  14: 46x65+120+414 144.0,444.3 203 srgb(255,255,255)
  18: 27x49+23+579 36.9,601.0 118 srgb(255,255,255)
  24: 16x8+703+641 710.6,644.5 102 srgb(255,255,255)

The -define connected-components:verbose=true causes the individual blobs to be output as text for parsing.
The -define connected-components:area-threshold=100 says to only output blobs larger than 100 pixels in area.
The -connected-components 8 says to allow pixels that are 8-connected to be considered as belonging to the same object. 8-connected means North-East, South-East, South-West and North-East neighbours in addition to the normal North, East, South and West. By default, ImageMagick only considers 4-connected pixels as belonging to the same object - it's faster ;-)
And your player is item id 17 - the second row and you can see the bounding box, and cut that out of the orignal with
convert b.jpg -crop 76x147+326+564 player.jpg

Note: You will need ImageMagick 6.8.9-10 or better for Connected Components Analysis.


text:
Q: Make an Input act liked a Class I have created a class say for eg. fruit. And I have made preset classes for example.
Apple = Fruit("Apple","red","small")

so where I can do Apple.color so that it returns red.
How can I ask the user for a fruit and it would be linked to the class?
my_fruit = input("Choose a fruit.")
my_fruit = Apple #but only as a string

How can I make my_fruit.color return red, similar to the created class of Apple. Would I need to convert this as a strong to a class?

A: In Python 2, the following would work as I believe you intend:
class Fruit(object):

    def __init__(self, name, color, size):
        self.name = name
        self.color = color
        self.size = size

Apple = Fruit('Apple', 'red', 'small')

fruit_class = input('Choose type of fruit: ')
print(fruit_class.color)

However, the function input in Python 3 behaves like raw_input does in Python 2. The is no function in Python 3 like Python 2's input. However, effectively the same functionality can be achieved using eval(input()) in Python 3 as described in this post.
The code would look like this:
Apple = Fruit('Apple', 'red', 'small')

fruit_class = eval(input('Choose type of fruit: '))
print(fruit_class.color)

However, use of eval is dangerous as the user can execute arbitrary code against the system. A mapping between the input string values you expect and the user to input and the class instances to which they should map could serve the same use case. For example:
Apple = Fruit('Apple', 'red', 'small')

fruits = {
    'Apple': Apple,
}

fruit_class_type = input('Choose type of fruit: ')
print(fruits[fruit_class_type].color)

A: Creating an istance of a class through input
I wish this code is what you intended. I understood that you wanted to create an istance of a class Fruit with attributes for color etc. with the input function. So I think this could be a possible solution.
class Fruit:
    def __init__(self, type, color, size):
        self.type, self.color, self.size = type, color, size

fruit1 = Fruit(
    input("Choose a type of fruit: "),
    input("Choose the color: "),
    input("Choose the size: "))

print("This is your fruit:")
print(fruit1.type, fruit1.color, fruit1.size)

OUTPUT
Choose a type of Fruit: Ananas
Choose the color: orange
Choose the size: big
This is your fruit:
Ananas orange big


text:
Q: in rails using will_paginate and partials I have a collection of people that is paginated with will_paginate
@people = Person.paginate :page => params[:page],
                :limit => 10,
                    :conditions =>   ['company_id = ? ' , @company.id ]

The people are shown on the company/view page and rendered with a partial. Note that the partial is in the views of 'people'
<%= render :partial => "people/person" , :locals => { :people => @people }%>

in the partial ...
<% for person in @people %>

     ...

<%end%>

<%= will_paginate @people %>

Now the partial does work, it renders all of the people and shows the paginate links on the bottom. However it doesn't not actually paginate the collection and instead it shows everything on the first page.
I am clearly missing something rather basic.
Thanks in advance.

A: Are you missing per_page?

A: Per_page should be the problem.
Also make :page => params[:page] look like :page => params[:page] || 1 so that will_paginate will stop complaining on blank page parameters.


text:
Q: List of all tables across all databases with row count of each table I want to get the list of ALL tables across ALL databases in a server along with row count of EACH table.
For now, I have developed a code that gives the list of all tables with all databases. However, I need help in adding row count of each of these tables.
CREATE  PROCEDURE [dbo].[List_of_tables_in_All_Databases]
    (@clean BIT = 1,
     @debugEnabled BIT = 0)
AS
BEGIN
    DECLARE @message  NVARCHAR(MAX)
    DECLARE @procName NVARCHAR(250) = object_name(@@procid);

    DECLARE @processingProcStart DATETIME = GETDATE()
    DECLARE @processingprocTime  INT = 0

    SET @message = 'List_of_tables_in_All_Databases START: ' + CONVERT(VARCHAR(23), GETDATE(), 121);

    EXEC [dbo].[usp_KREOInsertLog] @type = 'INFO', @source = 'Analysis', @storedProcedure = @procName, @debugLevel = 1, @message = @message, @show = @debugEnabled

IF OBJECT_ID (N'tempdb.dbo.#AllTables ') IS NOT NULL
     DROP TABLE #AllTables

SET NOCOUNT ON

CREATE TABLE #AllTables
(
    ServerName NVARCHAR(200),
    DBName NVARCHAR(200),
    SchemaName NVARCHAR(200),
    TableName NVARCHAR(200),
    [RowCount] INT
)

DECLARE @SearchSvr NVARCHAR(200),
        @SearchDB NVARCHAR(200),
        @SearchS NVARCHAR(200),
        @SearchTbl NVARCHAR(200),
        @SQL NVARCHAR(4000)

SET @SearchSvr = NULL  --Search for Servers, NULL for all Servers
SET @SearchDB = NULL   --Search for DB, NULL for all Databases
SET @SearchS = 'dbo'   --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL  --Search for Tables, NULL for all Tables

SELECT @SQL = 'SELECT @@SERVERNAME
        ,''?''
        ,s.name
        ,t.name
        FROM sys.tables t
         JOIN sys.schemas s on t.schema_id=s.schema_id
         WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
         AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
         AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
         AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
         AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
           '
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables

INSERT INTO #AllTables (ServerName, DBName, SchemaName, TableName)
    EXEC sp_MSforeachdb @SQL

SELECT * FROM #AllTables

Can someone help with writing the code that gives the row counts for these tables?

A: There's a quick way to get row counts using SQL Server metadata. You could add this into your query in @SQL:
SELECT [Rows] = SUM(row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=@YourObjectId
AND (index_id=0 or index_id=1);

I believe that would make the full @SQL as follows. Untested, but should at least be pretty close:
SELECT @SQL = 'SELECT @@SERVERNAME
        ,''?''
        ,s.name
        ,t.name
        ,SUM(p.row_count) as [rows]
        FROM sys.tables t
         JOIN sys.schemas s on t.schema_id=s.schema_id
         LEFT JOIN sys.dm_db_partition_stats p
           ON p.object_id = t.object_id
             and (p.index_id = 0 or p.index_id = 1)
         WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
         AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
         AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
         AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
         AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
        GROUP BY s.name, t.name
           '

A: You could also show the size in MB along with that info, I always use this query for that
select t.NAME AS TableName,
       i.name as indexName,
       sum(p.rows) / count(a.total_pages) as RowCounts,
       count(a.total_pages) as page_count,
       sum(a.total_pages) as TotalPages,
       sum(a.used_pages) as UsedPages,
       sum(a.data_pages) as DataPages,
       (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB,
       (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB,
       (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
from   sys.tables t
  inner join sys.indexes i ON t.OBJECT_ID = i.object_id
  inner join sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
  inner join sys.allocation_units a ON p.partition_id = a.container_id
where  t.NAME NOT LIKE 'dt%'
and    i.OBJECT_ID > 255
and    i.index_id <= 1
group by t.NAME, i.object_id, i.index_id, i.name
order by sum(p.rows) / count(a.total_pages) DESC

A: Complete example combining the work done by Jeff and the original question. I also fixed an issue where database names have '.'s in them, generated the pivot columns:
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#ServerTablesPivot') IS NOT NULL
    TRUNCATE TABLE #ServerTablesPivot
ELSE
    CREATE TABLE #ServerTablesPivot
    (
        DBName NVARCHAR(200),
        SchemaName NVARCHAR(200),
        TableName NVARCHAR(200),
        [RowCount] INT
    )

DECLARE @SearchSvr NVARCHAR(200),
        @SearchDB NVARCHAR(200),
        @SearchS NVARCHAR(200),
        @SearchTbl NVARCHAR(200),
        @SQL NVARCHAR(4000)

SET @SearchDB = 'UAT.Tenant00'   --Search for DB, NULL for all Databases
SET @SearchS = 'dbo'   --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL  --Search for Tables, NULL for all Tables

SELECT @SQL = 'USE [?]; SELECT
        ''?''
        ,s.name
        ,t.name
        ,SUM(p.rows) as [rows]
        FROM sys.tables t
         INNER JOIN sys.partitions p
         ON p.OBJECT_ID = t.OBJECT_ID
         INNER JOIN sys.schemas s
         ON t.schema_id = s.schema_id
         WHERE t.is_ms_shipped = 0 AND p.index_id IN (1,0)
         AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
         AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
         AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
         AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
         GROUP BY s.name,t.name'
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables

INSERT INTO #ServerTablesPivot (DBName, SchemaName, TableName, [RowCount])
    EXEC sp_MSforeachdb @SQL

--SELECT * FROM #ServerTablesPivot

--Declare necessary variables
DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

--Get unique values of pivot column
SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME([DBName])
FROM (SELECT DISTINCT [DBName] FROM #ServerTablesPivot) AS PivotExample

--SELECT   @PivotColumns

--Create the dynamic query with all the values for
--pivot column at runtime
SET   @SQLQuery =
    N' -- Your pivoted result comes here
    SELECT [TableName], ' + @PivotColumns + '
    FROM
    (
        -- Source table should in a inner query
        SELECT [DbName], [TableName], [RowCount]
        FROM #ServerTablesPivot
    )AS P
    PIVOT
    (
          -- Select the values from derived table P
          MIN([RowCount])
          FOR [DbName] IN (' + @PivotColumns + ')
    )AS PVTTable'

--SELECT   @SQLQuery
--Execute dynamic query
EXEC sp_executesql @SQLQuery


text:
Q: Drupal 8 Custom Form managed_file multiple upload field restrict limit number of upload files I have a custom form in Drupal 8. Form has managed_file field with multiple true. I am facing challenge regarding the limit of number of files upload to this field.
I have to make this managed_file field to upload only 3 images.
Can someone help me regarding this?
I have tried below code.
    public function buildForm(array $form, FormStateInterface $form_state) {

    $form['upload_doc'] = array(
          '#type' => 'managed_file',
          '#title' => 'File Upload',
          '#upload_location' => 'public://upload_document/',
          '#required' => TRUE,
          '#multiple' => TRUE,
          '#upload_validators' => array(
            'file_validate_extensions' => array('jpg jpeg png'),
            'file_validate_size' => 2000,
          ),
        );

    // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Submit'),
        ];

        return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
      $fileObj = $form_state->getValue('upload_doc');
      if (count($fileObj) > 3) {
        drupal_set_message('File limit exceed'.count($fileObj), 'error');
        return false;
      } else {
          return true;
      }
  }

The problem is, i am not able to validate file upload limit. It's allow to upload more than limit. Please help me
Thank you

A: public function validateForm(array &$form, FormStateInterface $form_state) {
$fileObj = $form_state->getValue('upload_doc');
if (count($fileObj) >= 4) {
  $form_state->setErrorByName('upload_doc', $this->t("Only 3 images are allowed per run."));}}

A: There is currently an opened issue to get this feature out of the box.
In the meanwhile, you can implement "element_validate" in your form:
$form['file_managed'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Files'),
  '#multiple' => TRUE,
  '#cardinality' => 3,
  '#element_validate' => [
    'your_module_max_files_validation',
  ],
];

Then in your_module.module:
/**
 * Custom validation handler. Validate number of files.
 */
function your_module_max_files_validation($element, FormStateInterface &$form_state, $form) {
  $is_removal = strpos($form_state->getTriggeringElement()['#name'], 'remove_button') !== FALSE ? TRUE : FALSE;
  if (!empty($element['#cardinality']) && count($element['#files']) > $element['#cardinality'] && !$is_removal) {
    $form_state->setErrorByName($element['#name'], t('Only max @limit files allowed.', [
      '@limit' => $element['#cardinality'],
    ]));
  }
}