text:
Q: Guessing the date format python I am writing a method in a Python module which tries to make live easier to the users. This method implements the creation of events in that calendar.
def update_event(start_datetime=None, end_datetime=None, description=None):
'''
Args:
  start_date: string datetime in the format YYYY-MM-DD or in RFC 3339
  end_date: string datetime in the format YYYY-MM-DD or in RFC 3339
  description: string with description (\n are transforrmed into new lines)
'''

If the user specifies the start_date or the end_date a check up should be made in order to determine if the date is in YYYY-MM-DD format or in the datetime RFC 3339 format.
if (start_date is not None):
    # Check whether we have an date or datetime value
    # Whole day events are represented as YYYY-MM-DD
    # Other events are represented as 2014-04-25T10:47:00.000-07:00
    whole_day_event = False
    try:
        new_start_time = datetime.datetime.strptime(start_date,'YYYY-MM-DD')
        # Here the event date is updated
        try:
            new_start_time = datetime.datetime.strptime(start_date,'%Y-%m-%dT%H:%M:%S%z')
            #Here the event date is updated
        except ValueError:
            return (ErrorCodeWhatever)
    except ValueError:
        return (ErrorCodeWhatever)

Is this a good way of doing this? Can I check what kind of date I am receiving in a nicer way?
Thanks!

A: dateutil.parser.parse can be used to attempt to parse strings into datetime objects for you.
from dateutil.parser import parse

def update_event(start_datetime=None, end_datetime=None, description=None):
    if start_datetime is not None:
        new_start_time = parse(start_datetime)

        return new_start_time

d = ['23/04/2014', '24-04-2013', '25th April 2014']

new = [update_event(i) for i in d]

for date in new:
    print(date)
    # 2014-04-23 00:00:00
    # 2013-04-24 00:00:00
    # 2014-04-25 00:00:00

A: Extending @Ffisegydd answer you can also specify your target datetime format that you want like this :-
from dateutil.parser import parse

def update_event(start_datetime=None, end_datetime=None, description=None):
    if start_datetime is not None:
        new_start_time = parse(start_datetime)

        return new_start_time

d = ['06/07/2021 06:40:23.277000','06/07/2021 06:40','06/07/2021']

new = [update_event(i) for i in d]

for date in new:
    print(date.strftime('%Y/%m/%d %H:%M:%S.%f'))


text:
Q: Como carregar uma view dentro de um layout? Estou tentando carregar uma view dentro de um layout, segue meu controller abaixo:
class IndexController extends BaseController {
    protected $layout = 'admin.layouts.default';

    public function index()
    {
        $this->layout->$this->layoutcontent =  View::make('admin.index');
    }
}

Porém está retornando o seguinte erro:

Attempt to assign property of non-object

A: O Erro está neste trecho:
$this->layout->$this->layoutcontent =  View::make('admin.index');

A propriedade é content mas tu tens $this->layoutcontent, deverás alterar para :
$this->layout->content = View::make('admin.index');

Ver também a documentação em: Laravel - Controller Layouts (Inglês)

A: Para incluir sub-views dentro do layout, pode ser desta forma:
@include('view.name')

Passando valores:
@include('view.name', array('some'=>'data'))

redpajama_set_name: RedPajamaStackExchange


text:
Q: HEX to Base64 converter for JavaScript Anyone know of a good snippet of JavaScript code to convert HEX encoded strings to base64 encoded strings?

A: If you're working in Node or using Browserify, you can use
var base64String = Buffer.from(hexString, 'hex').toString('base64')

or
var hexString = Buffer.from(base64String, 'base64').toString('hex')

A: I liked the approach from @eric-duminil nevertheless the solution below - avoiding regex - is ~2x faster.
Browser:
function hexToBase64(hexStr) {
  return btoa([...hexStr].reduce((acc, _, i) =>
    acc += !(i - 1 & 1) ? String.fromCharCode(parseInt(hexStr.substring(i - 1, i + 1), 16)) : ""
  ,""));
}

OR
// even a bit faster
function hexToBase64(hexStr) {
 let base64 = "";
 for(let i = 0; i < hexStr.length; i++) {
   base64 += !(i - 1 & 1) ? String.fromCharCode(parseInt(hexStr.substring(i - 1, i + 1), 16)) : ""
 }
 return btoa(base64);
}

Node:
const base64 = Buffer.from(hexStr, 'hex').toString('base64');

A: The excellent comment by @dandavis is modified by StackOverflow, and has some weird hidden characters.
Here it is as one liner :
btoa("a6b580481008e60df9350de170b7e728".match(/\w{2}/g).map(function(a){return String.fromCharCode(parseInt(a, 16));} ).join(""))

or :
function hexToBase64(hexstring) {
    return btoa(hexstring.match(/\w{2}/g).map(function(a) {
        return String.fromCharCode(parseInt(a, 16));
    }).join(""));
}

hexToBase64("a6b580481008e60df9350de170b7e728");

Both return :
"prWASBAI5g35NQ3hcLfnKA=="

Note that the hex string should have an even length :
hexToBase64("00");
// => "AA=="
hexToBase64("000");
// => "AA=="

A: if (!window.atob) {
  var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var table = tableStr.split("");

  window.atob = function (base64) {
    if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
    base64 = base64.replace(/=/g, "");
    var n = base64.length & 3;
    if (n === 1) throw new Error("String contains an invalid character");
    for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
      var a = tableStr.indexOf(base64[j++] || "A"), b = tableStr.indexOf(base64[j++] || "A");
      var c = tableStr.indexOf(base64[j++] || "A"), d = tableStr.indexOf(base64[j++] || "A");
      if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
      bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
      bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
      bin[bin.length] = ((c << 6) | d) & 255;
    };
    return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
  };

  window.btoa = function (bin) {
    for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
      var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
      if ((a | b | c) > 255) throw new Error("String contains an invalid character");
      base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
                              (isNaN(b) ? "=" : table[((b << 2) & 63) | (c >> 6)]) +
                              (isNaN(b + c) ? "=" : table[c & 63]);
    }
    return base64.join("");
  };

}

function hexToBase64(str) {
  return btoa(String.fromCharCode.apply(null,
    str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
  );
}

function base64ToHex(str) {
  for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
    var tmp = bin.charCodeAt(i).toString(16);
    if (tmp.length === 1) tmp = "0" + tmp;
    hex[hex.length] = tmp;
  }
  return hex.join(" ");
}

A: Large strings, no btoa
Solution below is good for large strings - if you want to get bytes from base64 then look HERE

function bytesArrToBase64(arr) {
  const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // base64 alphabet
  const bin = n => n.toString(2).padStart(8,0); // convert num to 8-bit binary string
  const l = arr.length
  let result = '';

  for(let i=0; i<=(l-1)/3; i++) {
    let c1 = i*3+1>=l; // case when "=" is on end
    let c2 = i*3+2>=l; // case when "=" is on end
    let chunk = bin(arr[3*i]) + bin(c1? 0:arr[3*i+1]) + bin(c2? 0:arr[3*i+2]);
    let r = chunk.match(/.{1,6}/g).map((x,j)=> j==3&&c2 ? '=' :(j==2&&c1 ? '=':abc[+('0b'+x)]));
    result += r.join('');
  }

  return result;
}

function hexToBytes(hexString) {
  return hexString.match(/.{1,2}/g).map(x=> +('0x'+x));
}

// ---------
// TEST
// ---------
let hexString = "a6b580481008e60df9350de170b7e728";
let bytes = hexToBytes(hexString);
let base64 = bytesArrToBase64(bytes);

console.log(base64);


text:
Q: Programmatically find and replace all multiline strings in Jupyter notebook I am trying to programmatically find all Python multiline strings defined in a Jupyter notebook, and then to find and replace their contents.
Is my best option to do this to parse the notebook using nbconvert and then to find the strings using `ast?


text:
Q: Página resultado de pesquisa não carrega resultados! Não consigo encontrar o erro! Digito o nome no campo de pesquisa e clico em pesquisar a tela fica cortada como na imagem abaixo. Quando atualizo a página o resultado a aparece e some rapidamente. Fiz um gif abaixo mostrando o problema:

Código utilizado no controller (CodeIgniter).
    // Details of searched student
function student_details($param1 = ""){
  if ($this->session->userdata('admin_login') != 1)
      redirect(site_url('login'), 'refresh');

  $student_identifier = html_escape($this->input->post('student_identifier'));
  $query_by_code = $this->db->get_where('student', array('student_code' => $student_identifier));

  if ($query_by_code->num_rows() == 0) {
    $this->db->like('name', $student_identifier);
    $query_by_name = $this->db->get('student');
    if ($query_by_name->num_rows() == 0) {
      $this->session->set_flashdata('error_message' , get_phrase('no_student_found'));
      redirect(site_url('admin/dashboard'), 'refresh');
    }
    else{
      $page_data['student_information'] = $query_by_name->result_array();
    }
  }
  else{
    $page_data['student_information'] = $query_by_code->result_array();
  }
  $page_data['page_name']   = 'search_result';
    $page_data['page_title']    = get_phrase('search_result');
    $this->load->view('backend/index', $page_data);
}


text:
Q: Problems with PHP code or a bug I am having weird issues with my code. I have almost identical code to the one below (I have not provided the actual code b`cuz it is a little big library with a lot of dynamic generation(selecting classes based on path routing etc. i.e. framework)).
The code explained:
ClassA represents the current route object. Contains controller, route string etc.
ScriptAClassAction is the dispatcher, checking if the route has everything that is necessary for the execution and running everything, does the controller exists $!empty(reflection) and does the action exist in the controller $reflection->hasMethod('hello').
In my world the parent if should be triggered if both conditions are meant (and the are not) or the else should get triggered, which is checking to see which of the checks have failed. On execution time I see that the first check passes (which I think it is a bug in PHP) and after it the else gets triggered, and then the second if.
I am thinking that this may be a bug in PHP, but I doubt it a lot. Does anyone see something that I miss @ 1:50AM ?
PHP 5.3.27 with enabled xDebug(No other extensions) & Apache 2.2.25 (I believe Apache is irrelevant here but..), Windows 7 x86 Home Premium
ClassA.php
class A
{
    public function init()
    {
        print 'Init called';
    }

    public function preDispatch()
    {
        print 'Predispatch called';
    }

    public function indexAction()
    {
        print 'Hello world';
    }

    public function postDispatch()
    {
        print "Post dispatch";
    }
}

ScriptAClassAction.php
require 'ClassA.php';

$class = new A();
$reflection = new ReflectionClass($class);
if (!empty($reflection) && $reflection->hasMethod('indexAction')) {
    if ($reflection->hasMethod('init')) $class->init($request, $response); //Prints 'Init called'
    if ($reflection->hasMethod('preDispatch')) $class->preDispatch(); // 'Predispatch called'
    $class->indexAction();
    if ($reflection->hasMethod('postDispatch')) $class->postDispatch(); // 'post dispatch called'..
} else {
    if (!$reflection) // I know this might not be the best check but..
        print "Not a valid class supplied";

    if (false == $reflection->hasMethod('indexAction')) // True trigger
        print "Supplied class does not have any manners and does not greet you :D";
        // This is the expected output and it should be the only output
}

** Output **

Init called Predispatch called Postdospatch called Supplied class does
  not have any manners and does not greet you :D

A: Adding brackets to your if statements will solve the issue. Also, you don't have to test the $reflection variable is empty or not. It will always be an instance.
Like @traq mentioned, it's better to create interfaces to identify classes with certain behaviors.
interface DispatchAware {
    public function preDispatch();
    public function postDispatch();
}

class A implements DispatchAware { ... }

Now you don't have to check for every method that might exist. You'll know it exists when an class implements an interface.
You dispatch code could now look something like:
$action = 'indexAction';

$a = new A();

if ($a instanceof DispatchAware) {
    $a->preDispatch();
}

try {
    $r = new ReflectionClass($a);
    $method = $r->getMethod($action);
    $method->invoke($a, $request, $response);
} catch (Exception $e) {
    methodNotFoundError();
}

if ($a instanceof DispatchAware) {
    $a->postDispatch();
}

I also removed the init() method. The reason for this is that controller type objects generally don't need to keep state. That is why $request and $response are passed as arguments to the action method.


text:
Q: No se muestran los botones o elementos en android studio Estoy comenzando a crear una aplicación en Android Studio y no consigo que se muestren los botones o elementos en la pre-visualización de imagen.
Adjunto capturas y código actual.
CÓDIGO xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>

<Button
    android:id="@+id/btnagregar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/add"/>

<ListView
    android:id="@+id/lvlista"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></ListView>

</LinearLayout>

Como mencionaba anteriormente, no se muestra nada en la vista previa de la derecha.
Espero me puedan ayudar, quedo atento a sus comentarios.
INFORMACIÓN TÉCNICA:

*

*EQUIPO Nexus 5

*API 28

*Android Studio Version 3.1.4

A: La solución fue la siguiente:
Cambie la versión de la api 28 a la api 26
y configure el archivo build.gradle(module app) dejando esta linea de la siguiente forma:
 implementation 'com.android.support:appcompat-v7:26.0.0'

luego di click en sincronizar en una pestaña que apareció.
y listo.

A: a mi me funcionaba :
1.-Cambiado el dispositivo en el cual estas haciendo la pre-visualizacion
2.- Trata de cambiar la vista a "blueprint" algo asi no recuerdo eso hace que refresque un poco la pre-visualizacion
3.-O la API tambien intenta cambiarla por una inferior


text:
Q: python opencv videoWriter fps rounding I am trying to measure some event in an input video file: "test.mp4". This is done by processing the video in several steps, where each step performs some operations on the video data and writes the intermediate results to a new video file.
The fps of the input video is: 29.42346629489295 fps
Below I have written a script to test the problem. When I write a new file using this script the fps gets rounded in the outputfile to 29.0 fps, and this is the problem.
import cv2
import sys

inputfilepath = "test.mp4"
outputfilepath = "testFps.mp4"

video = cv2.VideoCapture(inputfilepath)

fps = video.get(cv2.CAP_PROP_FPS)
framecount = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

print("original fps: ", fps)
# fps = 29.4
print("writing fps: ", fps)

writer = cv2.VideoWriter(outputfilepath, 0x00000020, fps, (width, height))

for i in range(framecount):
    success, image = video.read()
    if not success:
        break

    writer.write(image)

writer.release()
video.release()

video = cv2.VideoCapture(outputfilepath)
fps = video.get(cv2.CAP_PROP_FPS)

# the next line will not print the same fps as I passed to cv2.VideoWriter(...) above.
print("output fps: ", fps)
video.release()

I have tried to hardcode different values for fps. It seems like everything below 29.5 fps is rounded to zero decimals (29 fps), and everything above gets round to one decimal (29.x fps)
So my questions are:
Is it possible to get any fps with the mp4 format?
Which fps is actually used in the output file?
How can I get the correct fps in the output file?
Additional info
I tried many different values ranging from 28 fps to 31 fps, and plotted the actual output file framerate vs the expected. This displays some kind of fractral behavior, maybe this hint will inspire some math wizard in here :)

A: OpenCV uses some toolkit to do the writing. In my case, on iOS, OpenCV uses the native AVFoundation library. It seems AVFoundation (or the OpenCV api) can't handle well an fps value with many significant digits, like 29.7787878779, and something was being rounded incorrectly either in OpenCV's api or AVFoundation.
To fix the issue, I rounded off some of the significant digits before calling VideoWriter::open
normalizedFPS = round(1000.0 * normalizedFPS) / 1000.0;

Hope it works for you also!
I've seen 30,000 used as a timescale recommendation, so perhaps test out 1000.0 vs 30,000.0

A: Unfortunately there is a bug inside OpenCV.
I read and write an 46 minutes movie and 2 seconds are missing (same number of frames but a diferent FPS written in the header of the file)
For me is a big problem as I tried to join the audio information in another editor and you can see the 2 missing seconds
The original movie is fps = (60/1.001) = 59.94005994... and OpenCv is rounding this fps to 60 no matter if I wrote 59.94005994 in 2 places

*

*videoWriter = new VideoWriter( full_file_name, fourCC, fps, scaled_size, true);

*videoWriter.set(CAP_PROP_FPS, fps);

BAD NEWS - I found this code inside opencv source code
outfps = cvRound(fps);

bool AVIWriteContainer::initContainer(const String& filename, double fps, Size size, bool iscolor){
    outfps = cvRound(fps);
    width = size.width;
    height = size.height;
    channels = iscolor ? 3 : 1;
    moviPointer = 0;
    bool result = strm->open(filename);
    return result;
}

We have to escalate this bug toward OpenCv team (I use opencv-460.jar)
I will try to manualy change the header using other programs - this could save the day
the math computation that explain the missing seconds


text:
Q: Second order nonlinear differential equation $y'' = C/y^{1/2}$ $y'' = \frac{C}{\sqrt{y}}$
How can this differential equation be solved? I would love to add details about an attempt, but I have no idea where to even start.

A: Rewrite as $y'' = Cy^{-1/2}$
$y'' - Cy^{-1/2} = 0$
For variation of parameters assume the solution is in the same family of functions as the given derivative form. Since we are given a very simple power of x, try a simple power of x first.
Suppose $y = x^n$. Then $y'' = (n)(n-1)x^{n-2}$ and $Cy^{-1/2} = Cx^{-n/2}$
So $C = (n)(n-1)$ and $ n - 2 = -n/2$
$2n - 4 = -n$
$3n = 4$
$n = 4/3$

Check: $n-2 = 4/3 - 6/3 = -2/3$ and $-n/2 = (-1/2)(4/3)= -2/3 = n-2$ as required.
Any multiple $K_1 x^{4/3}$ will also satisfy the equation.
$C = n(n-1)K_1 = (4/3)(1/3)K_1 = 4/9K_1$
Part of homogeneous solution $y_h = K_1 x^{4/3}$  and $y'' = 4/9K_1 x^{-2/3} = 4/9 y^{-1/2}$
Going a little further, trying to get a more general case, try a linear expression instead of just x. Suppose $y = (ax + b)^n$
Then $y'' = a^2(n)(n-1) (ax + b)^{n-2}$
So to make $y'' = Cy^{-1/2} = C (ax + b)^{-n/2}$ again we have the solution $n-2 = -n/2, n = 4/3$with $C = 4/9a^2$
$y_h = (ax + b)^{4/3}$
Here the two undetermined constants are a and b, as required for a second-order equation.

Now we need a particular solution
I'm not getting what I need here and am out of time -- going to give you this partial solution as at least a place to start.
Some options for a particular solution might be sin^{4/3}x  or $e^{kix}$. Something to work on,

General solution $ y = y_p + y_h$

A: $$y'' = \frac{C}{\sqrt{y}}$$
This second order ODE is of autonomous kind. The usual method to reduce the order is shown below. The first order ODE obtained is separable.
The integration is easier considering the inverse function $x(y)$ instead of $y(x)$ which leads to :
$$x+c_2=\pm\frac{1}{C^3}(C\sqrt{y}-c_1)\sqrt{2C\sqrt{y}+c_1}$$
Inversing $x(y)$ for $y(x)$ leads to a three degrees polynomial equation. Of course, analytically solvable, but tiresome.


text:
Q: How do I delete a specified number of files in a directory in Python? I want to reduce the number of files in a folder or rather remove a specified number of files from the folder.
I'd appreciate simple solutions likely limited around my code below, which definitely is not working and wrong.
files = os.listdir()
for file in files:
    for file in range(11):
        os.remove(file)

A: You simply have to iterate correctly in the range:
files = os.listdir('path/to/your/folder')
for file in files[:11]:
    os.remove(file)

in this way you are iterating through a list containing the first 11 files.
If you want to remove random files, you can use:
from random import sample

files = os.listdir('path/to/your/folder')
for file in sample(files,11):
    os.remove(file)

A: Thanks everyone, I also did a bit of digging and applying solutions from your contributions. Here is what I got. The sorting was via creation time which was more logical for the task.
import os
import re

filepath = os.getcwd()
files = os.listdir(filepath)
files = sorted(files,key=os.path.getmtime)
for file in files[:11]:
    os.remove(file)

A: import os

files = os.listdir(r'C:/testdeletefolder')
fileslist=[]
for file in files:
    print file
    fileslist.append(file)

for i in range(0,2):
    os.remove(fileslist[i])

But ensure that you if condition to not to delete the python file which has code.this will delete 2 files you can change the counter in range


text:
Q: Durandal Get Started Sample I've tried following the Get Started example from the Durandal homepage, and just get..

I've refreshed the files from the Starter app / example, and followed the Get Started tutorial once a few weeks ago, and twice again today, and just get the numbers as above, not the expected form to type a name into.
Where do I even go to start debugging this issue?

A: I would start by pressing "F12" and opening the browser debugging console, to see if all the files have come down.  There may even be some syntax errors as well.
The HotTowel template by John Papa is also worth a look.
If you are just starting out with Durandal, also have a look at Aurelia, which is effectively the next version of Durandal.


text:
Q: Serving a .mp4 file with Flask and playing it on an Objective-C app causes Broken pipe and no play I'm trying to play a video that is served by a Flask web application on my iOS application. While I can play any video served with a "conventional" web server (like Apache), I can't play the video served by Flask. Here is the relevant code:
Objective-C
NSURL *videoURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",videourltemp]];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];

playerViewController.player = player;
[self.view addSubview:playerViewController.view];
[self.navigationController pushViewController:playerViewController animated:YES];

Python
from flask import Response, ...

def get_img(imgid):
    # private code hidden - file["path"] contains the path relative to /root/media_assets directory

    return Response(open("/root/media_assets/" + file["path"], "rb"), mimetype="video/mp4")

Sidenote: if I try to reach my URL from a browser, the video is correctly loaded.
How could I solve my problem?
Thank you in advance!

A: I encountered the same problem and eventually found that the real issue is that the video player client (in Objective-C iOS at least) uses the "range" header in the response (you can print out Flask request.headers to check). In other words, the streaming is really implemented using "range" support in HTTP.
I followed examples at https://codeburst.io/the-taste-of-media-streaming-with-flask-cdce35908a50, the Flask server code needs to build response using "partial content" (HTTP status code 206) and needs to process the "range" header in the request.  The related code looks like this:

*

*add "Accept-Ranges" in Flask app after_request so that the client knows "range" is supported:

@app.after_request
def after_request(response):
    response.headers.add('Accept-Ranges', 'bytes')
    return response

*in your function that serving the mp4 file, suppose the file path is "full_path":

    file_size = os.stat(full_path).st_size
    start = 0
    length = 10240  # can be any default length you want

    range_header = request.headers.get('Range', None)
    if range_header:
        m = re.search('([0-9]+)-([0-9]*)', range_header)  # example: 0-1000 or 1250-
        g = m.groups()
        byte1, byte2 = 0, None
        if g[0]:
            byte1 = int(g[0])
        if g[1]:
            byte2 = int(g[1])
        if byte1 < file_size:
            start = byte1
        if byte2:
            length = byte2 + 1 - byte1
        else:
            length = file_size - start

    with open(full_path, 'rb') as f:
        f.seek(start)
        chunk = f.read(length)

    rv = Response(chunk, 206, mimetype='video/mp4', content_type='video/mp4', direct_passthrough=True)
    rv.headers.add('Content-Range', 'bytes {0}-{1}/{2}'.format(start, start + length - 1, file_size))
    return rv

In my testing, the above Flask code works with iOS objective-C client as well as Chrome, Firefox browsers for .mp4 files.

A: You have two options there:

*

*Open the file and read it in chunks instead of reading it as a single blob, like in your code. Follow example from: https://stackoverflow.com/a/24318158/1955346:
from flask import stream_with_context, Response

@app.route('/stream_data')
def stream_data():
    def generate():
        with open("/root/media_assets/" + file["path"], "rb") as f:
            while True:
                chunk = ... # read each chunk or break if EOF
                yield chunk

    return Response(stream_with_context(generate()), mimetype="video/mp4")

*Use direct approach from How do I stream a file using werkzeug?:

return Response(file("/root/media_assets/" + file["path"]), direct_passthrough=True)


text:
Q: Experience with gel-filled junction boxes A lost answer to one of my questions mentioned gel-filling junction boxes for moisture protection. Has anybody worked with this technique before?
I am particularly interested in how difficult it is to remove the gel to change the connection.
The promotional video of the GUROSIL self-healing gel suggests that liquid gel will ooze out if one removes the gel? Is this really the case?
Regarding the products I have found "GUROSIL" and "Spelsberg Abox GT". Can anybody recommend an alternative they find better?

A: Well, there is an entire industry making what you want, so you would think it not too hard to find some solutions. But alas, it is quite difficult. The industry is geared toward large telecom companies with direct advertising to local telephone companies. I worked as a fiber optic tech for four years and have used quite a few different cases like what you're looking for, I'm assuming you're going for the smaller ones. For the most part, as I said, the cases don't get filled with a fluid gel. Most of them just seal incredibly well. The main players (as of six years ago, before I went back to school) were:
Coyote Splice Enclosures, from them I'd recommend the runt, it's quick to assemble and I've seen them sitting in water without taking any. The hardest thing with these is the cable wrapping takes practice to get right.
Tyco Splice Enclosures, they now go by TE, the "A" enclosure from their 450 series is a pretty awesome little dome. Fewer bolts and the entire cable entry gets a big sticky gel ring that seals it up tight. The cables just snap into the end plate and you screw two discs together to make the gel ring squish out around the cables and the dome, sealing them at the same time. They also make a nice line of copper enclosures (some that can be direct buried), which I have much less experience with.
The cases you've linked to seem quite nice too. They do look quite a bit less expensive, but messier. I can't comment on their effectiveness, but I do know a properly built fiber enclosure won't leak. The down side is the cost and the fact that you're not doing fiber in them, so the trays and other accessories likely won't be useful. Keep in mind many of these cases were designed for telecom manholes which, at least whenever I needed to get into them, were completely full of water.
As for acquiring these cases, try asking your local telephone company or look up some local fiber splicers, they might be willing to sell you some at their bulk rate.
I hope this helps. I'd be interested to see what you come up with.
-Samuel


text:
Q: How did Hawkeye know that the Tesseract was able to open portals before he saw it? During Avengers (2012), at the beginning of the movie before Loki activates the Tesseract, Nick Fury and Hawkeye have the following exchange:

Hawkeye: No one's come or gone. And Selvig's clean. No contacts, no I.M.'s. If there was any tampering, sir, it wasn't at this end.
Nick Fury: At this end?
H: Yeah, the cube is a doorway to the other end of space, right? The doors open from both sides.

The simple question is, how did Hawkeye know what the Tesseract actually did, especially given that Fury and SHIELD were trying to use it primarily as a power source for civilian energy needs and military "Phase 2" WMDs? For that matter, did anyone else in SHIELD know for a fact that the Tesseract could generate and sustain wormholes?

A: We don't really know how much SHIELD did or didn't know pre-Avengers, but whatever they knew we can probably assume Hawkeye knew, since he was guarding the device and the researchers. So the question really boils down to, how did SHIELD know?
It's possible SHIELD found out from what happened at the end Captain America, though we never see it explained on-screen. (We'd have to assume Steve Rogers more communication with the SSR than was actually shown.)
Remember, the last thing the Tesseract did before it fell into the sea was open a portal and pull the Red Skull into it. It's possible (likely, even) that Rogers would have relayed this information to his superiors ASAP, but it was just skipped over in the movie to get to the more dramatic parts.
Beyond that, SHIELD had been in possession of the Tesseract for decades, studying it. Howard Stark's notes contain tons of information on the cube. It's also something that the Asgardians have brought to Earth, so Dr. Selvig may already have some inkling of it's power from studying Norse myths. They may have stumbled upon that ability themselves as part of their research. Given that Red Skull did so by accident, it doesn't seem too difficult to do.


text:
Q: A simpel WPS using MVVM and EF I'm on the edge of going nuts.
I have a working WinForms/database application, that I try to rebuild with WPF. My main problem is that I haven't worked with MVVM before and I can't seem to get the grip of the databinding from Entity Framework to the View.
My WinForms is build exclusively using code-behind, which I know is bad praxis, but it works.
I have read about 100 articles, tutorials and examples, downloaded a couples of demo/samples using MVVM. Including "WPF Application Framework (WAF)"
But I haven't found a simple solution/sample how to use EF as the Model or as a dataprovider for the Model. And to pass the information on to to the ViewModel, and lastly bind it from the View.
All the tutorials I have read only describe fetching data from a static list, I need the usual CRUD operations on the database.
I know questions like this are being asked all the time here, but I haven't being able to find an answer to pushing data from EF to the View(Model) and update back through EF. I hope that some of you can help a (must be retarded) person like me with some guiding.

A: The MVVM pattern hinges, a lot, on the INotifyPropertyChanged interface which EF implements so some of the work here is done for you.
I am not too sure on your particular requirement but start off by creating a view mode for your window. Lets assume that you have a entity called Person with an attribute of FirstName as a string and an Id of Int32 (of course), and that all the work for the data layer is taken care of. I will show you how to list the Person entity and allow edit of the person entity as well.
ViewModel
public class Window1ViewModel : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;

  private ObservableCollection<Person> _people;
  private Person _selectedPerson;

  public ObservableCollection<Person> People {
    get { return _people; }
    set { _people = value;
      this.RaisePropertyChanged("People");
    }
  }

  public Person SelectedPerson {
    get { return _selectedPerson; }
    set { _selectedPerson = value;
      this.RaisePropertyChanged("SelectedPerson");
  }

  public Window1ViewModel() {
    // Instead of setting to empty collection populate with data from EF.
    this.People = new ObservableCollection<Person>();
  }

  private void RaisePropertyChanged(string propertyName) {
    if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

Now that you have your ViewModel taken care of it is time to create the UI and bind it.
Binding ListBox
<ListBox ItemsSource="{Binding Source={StaticResource viewModel}, Path=People}" SelectedItem="{Binding Source={StaticResource viewModel}, Path=SelectedPerson, Mode=TwoWay}"/>

Binding TextBox
<TextBox Text="{Binding Source={StaticResource viewModel}, Path=SelectedPerson.FirstName, Mode=TwoWay}"/>

Lastly you could create a button on your Window, bind it to an ICommand on your ViewModel to call the Save() method in the EF layer.
There is a lot you could write to meet your requirement i hope this goes some way to assist. Also recommend the following information. http://www.codeproject.com/Articles/81484/A-Practical-Quick-start-Tutorial-on-MVVM-in-WPF


text:
Q: Verify the entry in the text file using HashMap/HashTablw/2D array I have a text file which will doing fruit discovery and store Fruit name as fruit1 and time as time1. Please refer to the following for the data structure
Banana 12:10:11
Apple 12:10:11
Watermelon 12:16:10
Pineapple 12:16:10
Grape 12:30:16

I want to make sure that the timestamps wrote to the text file is the most updated timestamps with correct fruit and single entry only. For example, if Banana found on 12:31:18, it's will replace the older banana's record which is 12:10:11, so the updated file will look like
Apple 12:10:11
Watermelon 12:16:10
Pineapple 12:16:10
Grape 12:30:16
Banana 12:30:16

 This is my own pseudo code to achieve my purpose.
Read data(fruit1,time1) from text file
Store into HashMap/2D Array/HashTable/
    If HashMap is empty
       write fruit2/time2
    Else if fruit2 = fruit1
       Check the time?
          If time2 = time1
             Ignore
          Else update the time
    Else if fruit2 not equal fruit1
       Check next element ?
         If exsit ?
            If fruit2 = fruit1
                Check the time ?
                   If time2 = time1
                      Ignore
                   else update the time
         Else if fruit1 not equal fruit1
             Back to check next element

 Anyone here can suggest a better way to do this ? Do my own design pseudo code having some insufficient or out of logic ? Please advise any suitable method


text:
Q: Web application - HttpResponseBase.AddHeader I have a web application that uses HttpResponseBase.AddHeader.
I'm using this method to download a .csv file:
.AddHeader("content-disposition", "attachment; filename=" + fileName64)

The problem is that this method stops my code flow. All code after this call is not running.
I need to be able to download this file and show the client a success message, I can't because this request stops everything.
Any suggestions please?


text:
Q: Why client.UploadFile not available in tlsharp I use TLSharp v-1.0.0.0
I want send photo and file by this but client.UploadFile not available!
my code is:
var fileResult = (TLInputFile) await client.UploadFile(
                                        filename,
                                        new StreamReader(directory));

Here is what I see in the IDE.

A: missing namespace:
using TLSharp.Core.Utils;


text:
Q: Disabling Camera via Regedit I'm attempting to just disable a few features for laptops in my company.  I managed to disable the microphone but I can't find the right reg setting to shut off the camera.  I have Windows 10 build 1079.  This is for enterprise type stuff so I can't change to a different build or anything like that.
I have it currently to HKLM\SYSTEM\ControlSet001\Enum\USB\VID_0BDA&PID_573C&MI_00\ there's no setting to change the camera value.  I assume I could do something like deny access to the camera which is what I would do in the settings but I need to do this via registry.
Can anyone help out?

A: To Turn Off Allow Windows and Apps Access to Camera for All Users:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam]
"Value"="Deny"

It's also useful to physically disable the camera by using a single hole punch and brightly colored painters tape (low stickiness glue) to make an adhesive disk to stick over the lens. That prevents programs from activating the camera. A written policy warning employees not to remove the tape rounds out a cautious security policy.


text:
Q: Can't get function load jquery to work I've create a two tester html files to get this working but i'm getting nothing so far.
This is the jQuery I'm using:
$(function(){
  $("#header").load("2.html");
});

This is my body:

My 2.html contains:
test

Why won't 2.html load into 1.html?

A: Answer found thanks to RoryMcCrossan.
I was testing the file locally and it would not work.
As soon as I hosted the file it worked.

A: $.get('2.html', function (data) {
  $('#header').html(data);
});

This should work fine


text:
Q: GridView with tempelate TextFields i have a grid view with textfields as tempelates.
i have connected it to a DB so 'm able to perform Insert operation when entred in a textfield for the checked column. now i have to update the DB so i want to display what is present in the DB and 'm only able get the 1st Column that is the Customer_Name the rest will be empty so how do i do it??
this is what i have been tring
                SqlCommand search2 = new SqlCommand("select * from OtherCostData", con);

                SqlDataAdapter da = new SqlDataAdapter(search2);
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds;
                GridView1.DataBind();

i'm not able to put my gridview aspx code its giving me some indentation error however i try to format it


text:
Q: How to know parent of leaf item in NestedList? Is there a method which allows to know parent item of leaf tapped item?
that is like I have a Store with structure like this:
root: {
        items: [
            {
                text: 'Parent1',
                items: [
                    { text: 'Child1', leaf: true },
                    { text: 'Child2', leaf: true },
                    ............

When I tap on leaf item I need to know which parent has this leaf item. I can't find anything about special method for this.

A: In the itemtap & leafitemtap, the record gets passed to the listener.
From here, you can grab the parent record by using:
record.parentNode


text:
Q: start instance with persistent disk and specific disk name I have a persistent disk named foo that I would like to attach to an instance I create. I run the following command
gcloud beta compute --project=myproject instances create myinstance --machine-type=n1-standard-4 --disk=device-name=foo,name=foo

However, when I look at the instances and run sudo lsblk the disk appears under name sdb instead of foo. What am I doing wrong?

A: The device special is set by Linux and will always be sd# something. But it can change depending on the sequence that persistent disks are attached to the instance.
Setting an ID will cause a persistent link to be added in /dev/disk/by-id using that name that always refers to the disk. For instance, if you name the disk foo then you will get a link /dev/disk/by-id/google-foo which always points to the correct sd# device special. You can then use that link (and/or the corresponding partition links, after the disk is partitioned) to refer to the disk.


text:
Q: Can someone explain why the effective potential should be IR cutoff independent? I'm studying renormalization in my bachelor but there is something I don't understand:
In $\phi^4$ scalar field theory, What does it mean that effective potential is depending on the cutoff? and Why should it be independent from the infrared cutoff?


text:
Q: How to make custom cache for spring cloud config server Spring cloud config server caches files in tmp directory.
How can one implement own storage, hence hashmap, hazelcast cache or local db instead of file system?


text:
Q: What is the optimal position of a sentry gun? Often, maps feature alcoves or corners in which one can comfortably fit a sentry gun, usually with a nice inviting ammo box with it. I wonder, however: what's the optimal sentry placement?
The main threats to sentries are demomen grenades and sticky bombs, spy sappers and übers of all kinds. I don't think much can be done about the second and the third; perhaps the former and the firing range can be worked upon however.
Certainly, some positions are better than others. Assuming enemies come from the left:
--- XXXXX----X    X-----XXXXXX----- ???  ---
  |   XXX|  |X    X|   |XXXXXX|   |   ?  |
  |    XX|  |X    X|   |XXXXXX|   |  ?   |
  |     X|  |XXXXXX|   |XXXXXX|   |  .   |
  --------  --------   --------   --------
  easy to   easy to    easy to    easy to
  grenade   sticky     über       sap
  (or hit)

How can I optimally place a sentry?

A: I assume that there is a corridor of sorts leading to the alcove and not a wide open space (otherwise placing a sentry in the alcove would make little sense to begin with).
What I usually do is place the sentry in the following location:
---      ---
  |   *  |
  |     S|
  |      |
  --------
  sentry at
  S, looking
  at *

Assuming both walls are not too far apart, this would allow the sentry to cover a slice of the hallway leading to its location, which is perfect since it would force your foes to a specific portion of the hallway if they hope to get the jump on the sentry. This, in turn, would allow your teammates or yourself to dispose of them with greater ease.
If the walls are far apart, however, I would go for the following placement:
---       ---
  |   *   |
  |   S   |
  |       |
  ---------
  sentry at
  S, looking
  at *

This would probably be the safest position to avoid grenades ricocheting off of the walls, and should make it harder to nail the sentry with stickies. I prefer to have the sentry looking forward so that it covers the entire access gap.

A: Wow, I forgot I never answered this question.
There are several criteria to take into account:

*

*Soldier & Demoman: Build away from walls opposite an archway or from where your sentry can be hit by splash damage.  Demoman can be a particular problem if they can arc stickies from below or above you.  Don't forget you can destroy sticky bombs with your pistol or shotgun.  Grenades also bounce around corners, so build on the near side of the corner rather than the far side.

*Sniper: Don't build in front of an area with really long sight lines.  While the Wrangler can mitigate this problem, controlling your sentry makes it much easier for the other team to sneak behind you.

*Spy: Build somewhere where you can have your back to a wall.  Listen for decloak sounds or your gun spotting something and turning towards you.

*Uber: Well, there's really nowhere good to build a sentry to counter an Uber.  Ubercharge was intended to be a hard counter to sentry guns when used effectively.  Instead, it helps to have assistance from your teammates, particularly Pyros for their airblast ability.  Also repair, repair, repair.

So, taking all this into account, your best bet is to build somewhere near two corners where the corners are a sufficient distance apart, but not to the point where you sentry can't see the other corner.  A good example of this is Badwater Point D, which has two such areas like this for the RED team to put sentry guns.  The one away from the tracks is more vulnerable to Demomen and Soldiers, the one closer to the tracks is more vulnerable to Spies and Ubers.
Now, there are some places where this just isn't possible, such as Granary Point B.  In this case, your best bet is likely upstairs near the middle across from the point.  In this position, your biggest problem will be enemies approaching from the right.  A trick here is to place your dispenser behind the gun, and have the Engineer stand to its left (which is a dead end).  This gives you some protection from Soldiers, Demomen,meaning that your main problem with be Spies and Ubers.

A: The best place to locate a sentry is where the enemy doesn't know it is.  However, that only works once at most if you're lucky and they didn't hear it for some reason.
When strategizing with your sentry placement, remember to rely on yourself and your team to back it up.  SGs are phenomenally accurate and can mow down most classes in 1-2 seconds. One of the most effective locations to place sentries is where enemies coming around a corner will be unable to see and hit it before they are well in your team's field of fire.  Most people will get caught up on shooting whoever's shooting them, and be an excellent distraction while your sentry's mowing them down.
In your alcove case, I would try to place it against the wall towards the enemy, as if they walk by,

*

*their field of view will either

*

*not allow them to see it, so they will have to spend a split second aiming at it, all the while being laid into by it, or

*if they are looking at it, then your team, further down the hall giving you support, will be able to fire at the enemy without challenge

*the force from the bullets will drive the enemy further into the sentry's field of view, rather than in the "safe" retreating direction, towards the rest of their team

Here it is in ASCII because I'm too lazy to make it in paint.exe
Enemy ->           <- Your team
       ---       ---
         |       |
         |X      |
         |       |
         ---------

As the occasional soldier, whenever the second point is violated and there is insufficient support being given to the sentry, it's as good as dead because I can peek around the corner and peck it to death (or blow it all up at once as demo).

A: best place would be at a choke point like this:
----     -----
  |*      |    sentry at * and looking at s
  | s     |
  |       |
  ---------

Or if you are feeling sporty you could just place in a room/control point and keep a look out for the turret range (the gigantic red circle when holding the turret) and make sure the turret can cover all non-friendly entrences to the room/control point.

A: When you defend against ubers, you should wrangle the sentry and switch to your rescue ranger or wrench immediately after the shield comes up. You do this because there are abou two seconds when the sentry is disabled but the shield is still up. You can keep doing this for as long the sentry is up.


text:
Q: Fit text to a div width regardless of text content I have a div, width:400px;.
The div contains text, which greets a user, e.g Hello, John Smith. I want the text to be dynamically sized to always fit the maximum width of the div, regardless of the text.
So, if the user's name is Hubert Blaine Wolfeschlegelsteinhausenbergerdorff Sr., I want the text to be formatted to not overflow the 400px, with no line break (longer name = smaller text).
I can only find examples of how to do this when the name does not change (just changing the size... is it possible to do it the way I'd like?


text:
Q: How to choose a "good" 3V3 LDO and FET for low power applications I am trying to design my first low-power PCB using an ESP32 to switch a 12V 1.2A LED Strip.
I purchased this module that charges a Lithium battery using a solar panel here. Hence that is where the 5V comes from. The 12V comes from boosting the 5V out o
f the module.
My two questions are:

*

*How do I choose the 3V3 LDO for maximum efficiency?

I decided to with the SPX3819M5-L-3-3/TR. It has a Quiescent Current of 8uA, what other stuff do I need to consider when deciding?

*How do I choose the FET M1 for maximum efficiency?

Do I look at the Rds(ON) only or are there other stuff to take into account?

simulate this circuit – Schematic created using CircuitLab
EDIT 2:

simulate this circuit

A: The LDO will have to dissipate almost 0.45W nominal with a 260mA load (not including the dissipation due to Iq). It will be more if the 5V supply happens to be at the higher end of the tolerance range. That's a bit much for an SOT23 to be safe even with an ideal sea of copper around it. The DFN8 package is more reasonable, particularly with a good thermal connection to the exposed pad and a fair bit of copper around it.
You're also wasting 14mW in R1 when the LED strip is off. Increasing it will reduce static dissipation but runs the risk of the MOSFET dying during turn-on when it might be dissipating several watts for a time while switching, depending on the internals of the LED strip.
In general "maximum efficiency" is not a good goal. You can almost always increase efficiency (or any other parameter) by throwing money and parts at it.
The static (when not switching) "on" power dissipation in the MOSFET is governed by Rds(on) with 12V Vgs. Once it's small enough that the MOSFET runs cool, further increases have limited benefit and add to cost etc., since almost all the power dissipation will be in the LED strip. More efficient LEDs would yield much higher returns.
Does the Iq of the regulator actually matter in this application? It might if you plan on putting the MCU to sleep and it's a battery powered application. If it's powered off of the mains, the difference between 8uA and 5mA Iq is often not a big concern. Nor does it matter if it's an LDO or not. There's a fixed 1.7V drop (nominal) required, which is not exactly low.


text:
Q: How do platforms present to users their Api Keys in a secure way? I'm not talking about showing them a popup upon api key generation, where the user is specifically warned about the fact that

This is the only time you will see it. Make sure to save this to a safe place.

Instead, I'm talking about platforms, like RapidApi, where the ApiKey is automatically filled-in for each Api in the platform, whether the user is subscribed to an Api or not.

(example from RapidApi)
Putting aside the fact that on RapidApi you can even use just a single ApiKey for each subscribed Api, instead of generating a new and unique ApiKey for a specific Api, how do they do that?
If the frontend is able to fill automatically the X-RapidApi-Key field, (I suppose) it means that the frontend is asking their backend what is my ApiKey.
Also that means that the ApiKey itself could not be hashed in their databases, but at least it is encrypted and decrypted upon demand.
Alternatively it is just plain text in their database or I'm missing something.
On other API platforms, the ApiKey is exposed only upon generation and it is up to the user to save it and use it. Which is pretty much secure, but of course it's not that handy if a user is able to use multiple API/ApiKeys.


text:
Q: IsolatedStorageSettings.ApplicationSettings not able to save UserData.Contact object I'm making my first Windows Phone App
As per this tutorial [ http://msdn.microsoft.com/en-us/library/gg680266(v=pandp.11).aspx ],
 "To save a serializable object to isolated storage using a dictionary, you just assign the object to IsolatedStorageSettings.ApplicationSettings and specify a key."
In my app, I tried to save a Microsoft.Phone.UserData.Contact object in the dictionary.
appSettings["con"] = myContactObject

And then retrieve it later in another page using
savedContactObject = (Contact)appSettings["con"];

This code works in the emulator and the device as long as the app is open.But when the app is closed, this dictionary pair gets erased.
The dictionary is working perfectly for strings and custom objects. It only gets erased when a Microsoft.Phone.UserData.Contact object is saved and the app is closed.
Please tell me if you have any ideas to solve this problem. Thanks for your help.

A: Call
Settings.Save()

To make it save those settings.

A: Microsoft.Phone.UserData.Contact objects are not serializable, so application setting will silently ignore those objects. You have to write a custom logic to serialize those objects. Create a MyContact class, transfer all information you want to store there, and save these MyContact objects.


text:
Q: customizing heatmap using data stored in pandas dataframe I have a dataframe z1 with entries as follows:
z1.ix[1:10,1:3]
            2017-04-01  2017-05-01
2017-01-04         NaN    0.993549
2017-01-05         NaN         NaN
2017-01-06    0.830973    0.978463
2017-01-09    0.926456         NaN
2017-01-10    0.998371    0.997590
2017-01-11    0.997539    0.999364
2017-01-12    NaN         0.989801
2017-01-13    0.999701    0.998526
2017-01-16    0.995119    0.998891

Both index and column names are datetime objects.
I am trying to create heat map for the above dataframe so I am doing the following:
from io import StringIO
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

s = StringIO("""
            2017-04-01  2017-05-01
2017-01-04         NaN    0.993549
2017-01-05         NaN         NaN
2017-01-06    0.830973    0.978463
2017-01-09    0.926456         NaN
2017-01-10    0.998371    0.997590
2017-01-11    0.997539    0.999364
2017-01-12    NaN         0.989801
2017-01-13    0.999701    0.998526
2017-01-16    0.995119    0.998891""")
z1 = pd.DataFrame.from_csv(s, sep='\s+')
sns.heatmap(z1, annot=True)

I have the following questions:
(1) By default it uses red and black scale, how do I use green and red scale?
(2) How do I control the display of x and y axes ticks. I want to tilt them at an angle as I have about 100 columns and hence I want to use only 10 ticks aligned at an angle.
(3) How do I control the display of y axis ticks? Right now I am not sure what it displays. I want it displayed in the format '%Y-%m-%d'

A: For your first question, you need to use the "cmap" parameter.
For your second question, you need to use set_xticklabels() with the rotation parameter or the set_yticklabels() depending on what axis you want.
For your third question you need to do z1.index.strftime('%Y-%m-%d')
from io import StringIO
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

s = StringIO("""
            2017-04-01  2017-05-01
2017-01-04         NaN    0.993549
2017-01-05         NaN         NaN
2017-01-06    0.830973    0.978463
2017-01-09    0.926456         NaN
2017-01-10    0.998371    0.997590
2017-01-11    0.997539    0.999364
2017-01-12    NaN         0.989801
2017-01-13    0.999701    0.998526
2017-01-16    0.995119    0.998891""")
z1 = pd.DataFrame.from_csv(s, sep='\s+')
# Change the date format of index column
z1.index =  z1.index.strftime('%Y-%m-%d')
g = sns.heatmap(z1, annot=True,cmap="RdYlGn")
g.set_xticklabels(g.get_xticklabels(),rotation=30)

You could try other parameters for cmap based on the colors you want like:
Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Vega10, Vega10_r, Vega20, Vega20_r, Vega20b, Vega20b_r, Vega20c, Vega20c_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, icefire, icefire_r, inferno, inferno_r, jet, jet_r, magma, magma_r, mako, mako_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, rocket, rocket_r, seismic, seismic_r, spectral, spectral_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, viridis, viridis_r, vlag, vlag_r, winter, winter_r


text:
Q: php read large text file log I have a text log file, about 600 MB.
I want to read it using php and display the data on a html page, but I only need the last 18 lines that were added each time I run the script.
Since its a large file, I can't read it all in then flip the array as I would have hoped.  Is their another way?

A: Loading that size file into memory would probably not be a good idea. This should get you around that.
$file = escapeshellarg($file);
$line = 'tail -n 18 '.$file;
system($line);

A: Use fopen, filesize and fseek to open the file and start reading it only near the end of the file.
Comments on the fseek manual page include full code to read the last X lines of a large file.

A: you can stream it backwards with
$file = popen("tac $filename",'r');

while ($line = fgets($file)) {
  echo $line;
}

A: The best way to do this is use fread and fgets to read line by line, this is extreamly fast as only one line is read at one time and not the while file:
Example of usage would be:
$handle = fopen("/logs/log.txt", "r")
if ($handle)
{
    fseek($handle,-18,SEEK_END); //Seek to the end minus 18 lines
    while (!feof($handle))
    {
        echo fgets($handle, 4096); //Make sure your line is less that 4096, otherwise update
        $line++;
    }
    fclose($handle);
}

A: For the record, had the same problem and tried every solution here.
Turns out Dagon's popen "tac $filename" way is the fastest and the one with the lowest memory and CPU loads.
Tested with a 2Gb log-file reading 500, 1000 and 2000 lines each time. Smooth. Thank you.


text:
Q: Path issues in google colab I am having trouble getting google collab to accept a path I specified for a folder.
data_dir = "/content/drive/MyDrive/Traffic_sign/TSF/Traffic_sign_classification"
!ls
train_path = 'Train'
test_path = 'Test'
# Resizing the images to 30x30x3
IMG_HEIGHT = 30
IMG_WIDTH = 30
channels = 3

this is the output:
Meta  Meta.csv  output  Test  Test.csv  Train  Train.csv

so it is clearly getting the contents in the directory, but when I run this
NUM_CATEGORIES = len(os.listdir(train_path))
NUM_CATEGORIES

I get this error
NotADirectoryError                        Traceback (most recent call last)
<ipython-input-55-215493947f82> in <module>()
----> 1 NUM_CATEGORIES = len(os.listdir(train_path))
      2 NUM_CATEGORIES

NotADirectoryError: [Errno 20] Not a directory: 'Train'

I have no clue why I am getting this problem as Train is a folder in Traffic_sign_classification. Does anyone know how to fix it?


text:
Q: MySQL fetching comma separated values I am working on a project developed by a developer who left the company. There is a book table which a column theme_id. theme_id store in comma separated value such as
id  theme_id
50  14,15

Currently the previous developer created another table book_theme_list with column book_id and theme_id to do the searching.
For example:
book_id theme_id
50      14
50      15

It works but data is duplicated and the two table need to sync on every CRUD.
What is the point on having this? I delete book_theme_list and use %LIKE% in my query and it also work.

A: You can get the theme_ids in a single column by using below code
SELECT book_id, GROUP_CONCAT(DISTINCT theme_id SEPARATOR ',')
FROM book_theme_list
GROUP BY book_id

then if any update or insert on book_theme_list, it triggers an update on other table as ;
CREATE TRIGGER theme_Id_check
AFTER INSERT OR UPDATE
ON book_theme_list
FOR EACH ROW

UPDATE  book
SET theme_id = (
   SELECT GROUP_CONCAT(DISTINCT theme_id SEPARATOR ',')
   FROM book_theme_list
   WHERE book_id = new.book_id
   GROUP BY book_id )
WHERE book_id =  new.book_id
END;

A: Search on book table using %like% will work but will be slower because b-tree index can't be used when search happens only on book.theme_id column. If you search by both book.id and book.theme_id column then it would be ok as long as index is present on book.id. If this table is not searched as much and functionally not very important then you should be fine with this solution, but if it is a heavy traffic table then I will suggest keeping book_theme_list.


text:
Q: How to read multiple images and create a 3D matrix with them? I have a bunch of images (300 images of 400 X 400 pixels) with filenames like:

*

*001.bmp

*002.bmp

*003.bmp

*...

First, I tried reading one of them, e.g. using imread I get a (400L, 400L, 3L) matrix, the problem is the 3L (I think is RBG format), so the question here is: how can I read them and get a (400L, 400L, 1L) matrix that I need to proccess them?
Second, I tried to read the 300 images using a loop like the following:
data = np.zeros((400,400,300))
for i in range(300):
    data[:,:,i] = imread('{0}.bmp'.format(i))

but it doesn't work, very probably my code is wrong. Actually doing this, I want to concatenate each (300) image data (400 X 400) into a matrix of (400 X 400 X 300).
When trying to use:
data[:,:,i] = imread('{0}.bmp'.format(i))

search for '1.bmp' and not '001.bmp', but due to the list go from 000 to 299, I got a problem with that and I cant write '00{0}.bmp'.format(i) to complete the filename, because for two- and three digits numbers I got '0012.bmp' or '00123.bmp'
Well, after hours, I got to do this
arrays = []
for number in range(0, 299):
    numstr = str(number).zfill(3)
    fname = numstr + '.bmp'
    a = imread(fname, flatten=1)
    arrays.append(a)
data = np.array(arrays)

This code its work well. Thankyou, for give me clues!

A: First, you are right that the last dimension are the color channels. I assume you want a grayscale image, which you can get with:
data = imread(fname, flatten=1)

That comes from the imread documentation here.
Second, your issue with the loop can be due to a couple of things. First, I don't see indentation in the code in your post, so make sure that is there on the loop body in the code that you are actually trying to run. Second, the code has a ".txt" extension. Are you sure you don't actually want ".bmp"?


text:
Q: Convert JSON query parameters to objects with JAX-RS I have a JAX-RS resource, which gets its paramaters as a JSON string like this:
http://some.test/aresource?query={"paramA":"value1", "paramB":"value2"}

The reason to use JSON here, is that the query object can be quite complex in real use cases.
I'd like to convert the JSON string to a Java object, dto in the example:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") DataTransferObject dto ) {
    ...
}

Does JAX-RS support such a conversion from JSON passed as a query param to Java objects?

A: Adding to Jason's solution, using http://www.json.org/java/ (courtesy of Crockford):
import org.json.JSONObject;

public class JSONParam {
    private DataTransferObject dto;

    public JSONParam(String json) throws WebApplicationException {
        try {
            // convert json string DataTransferObject and set dto
            JSONObject jo = new JSONObject(json);
            dto.setParamA(jo.getString("paramA"));
            dto.setParamB(jo.getString("paramB"));
            // There are other get methods for Integer, Double, etc.
            // You can also build JSON from Java objects.
        }
        catch (JSONException e) {
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                    .entity("Couldn't parse JSON string: " + e.getMessage())
                    .build());
        }
    }

     public DataTransferObject getDTO() {
        return dto;
    }
}

Don't re-invent the wheel :-)

A: JAX-RS supports the use of JAXB (Java API for XML Binding) to bind a JavaBean to XML or JSON and vise versa. More details can be found here, for example: http://www.ibm.com/developerworks/web/library/wa-aj-tomcat/index.html
You need to

*

*Add @XmlRootElement annotation on DataTransferObject

*Create it an empty default constructor in DataTransferObject

*Add @Consumes(MediaType.APPLICATION_JSON) annotation to your WebService

A: Yes, you can do this, but you will need to write the conversion code yourself. Fortunately, this is easy, you just need to write a class that has a public String constructor to do the conversion. For example:
public class JSONParam {
    private DataTransferObject dto;

    public JSONParam(String json) throws WebApplicationException {
        try {
            // convert json string DataTransferObject and set dto
        }
        catch (JSONException e) {
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                    .entity("Couldn't parse JSON string: " + e.getMessage())
                    .build());
        }
    }

    public DataTransferObject getDTO() {
        return dto;
    }
}

Then you can use:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") JSONParam json) {
    DataTransferObject dto = json.getDTO();
    ...
}

A: As mentioned, you do need to explicitly convert from String parameter to JSON. But there is no need to use something as primitive as org.json's parser; Jackson or Gson can do data binding (String to JSON, JSON to POJO) in a line or two. With Jackson:
MyValue value = new ObjectMapper().readValue(json, MyValue.class);

(for production code, just create ObjectMapper once as static member, reuse)
Jackson is what most JAX-RS implementations use to implement data-binding for POST data, so this is quite similar.

A: If you're interested in generating your DTOs, can I suggest jsonschema2pojo? You can define your objects using JSON Schema and have your DTOs automatically generated.
Once you've written the schema, you can also give it to your consumers so that they understand exactly how requests should be formatted.

A: Maybe you could use
http://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/beans/BeanUtils.html
BeanUtils.copyProperties(source, target)


text:
Q: Three.js method for adding high resolution textures for planets So I found out that texturing planets can be really hard. I created a 4096k image and wrapped it around a high poly sphere. Apart from the possible memory management performance issue that comes with a 3-4 mb image, the texture looks bad / pixelated on a close up (orbital) view.
I was thinking that I could maybe increase the resolution significantly by splitting up the picture. Then create a low, medium and high version of each section. If the camera viewport is very close to that particular section then render the high resolution image. If far away remove image from memory and apply low or medium version.

To be honest I am not sure what strategy to use to render high quality planets. Should I maybe avoid textures and just use height maps and color the planet with Javascript? Same thing for the clouds. Should I create a sphere with an alpha map or should I use shaders?
As you can see this is the issue im having and hopefully you could enlighten me. Performance with Webgl / three.js has significantly improved over time but since this is all done within the browser I assume thinking about the right solution is vital in the long term.

A: You're going to need to implement a lod system. lod = "level of detail" and in 3d it means generally means switching from high-polygon to low-polygon models but in general it means doing anything to switch high detail to low-detail
Because you can't make textures 1000000x100000 which is pretty much what you'd need to do to get the results you want you'll need build a sphere out of multiple sections and texture each one separately. How many sections depends on how close you want to be able to zoom in. Google Maps has millions of sections. At the same time, if you can zoom out to see the whole planet (like you can in Google Maps) you can't draw millions of sections. Instead you'd switch to a single sphere. That process is called "LODing"
There is no "generic" solution. You generally need to write your own for your specific case.
In the case of something like Google Maps what they most likely do is have several levels of detail. A single sphere when you can see the whole planet. A sphere made of say 100 pieces when slightly closer. A sphere made of 1000 pieces when closer, A sphere made of 10000 pieces when closer, etc etc. They also only show the pieces you can see. Deciding and managing which pieces to show with a generic solution would be way to slow (look at millions of pieces every frame) but you, as the application writer know what pieces are visible so you can make sure only those pieces are in your scene.
Another thing that people often do is fade between LODs. So when Google Maps is showing the single mesh sphere when all the say zoomed out and they transition to the 100 piece or 1000 piece sphere they crossfade between the two.
Some examples of lodding
http://acko.net/blog/making-worlds-1-of-spheres-and-cubes/
http://vterrain.org/LOD/spherical.html

A: You could create a sphere with different topology.
Say you create 6 square planes, arranged in such a way that they form a box. You can tesselate these planes to give the sphere enough resolution. These planes would have UV mapping that would work similar to cube-mapping, each will hold a cubemap face.
Then you loop through all the vertices, take the position vector and normalize it. This will yield a sphere.
You can convert an equirectangular panorama image into a cubemap. I think it will allow you to to get more resolution and less stretching for cheap.
For starters, the 4096 x 4096 should be 4096x2048 on the default sphere with equirectangular, but the newly mapped sphere can hold 6 x 4096 x 4096 with no stretching, and can be drawn in 6 draw calls.
Further splitting these could yield a good basis for what gman suggests.


text:
Q: Angular2 - Unit Testing Form Submit I've a simple component which contains two input fields inside a form element. On clicking the submit button, it calls the addUser function on the component.
Component template is given below:

  <form [formGroup]="signupForm" (submit)="addUser($event)" role="form" class="form-horizontal">
      Firstname:
      <input type="text" formControlName="firstName">
      Lastname:
      <input type="text" formControlName="lastName">
      <input type="submit" id="btnSubmit" class="btn btn-primary btn-lg" value="Register" />
  </form>

Component definition is given below:
@Component({
  moduleId: module.id,
  templateUrl: 'user.component.html'
})
export class UserComponent {

  registered = false;

  constructor(
    private router: Router,
    private fb: FormBuilder,
    public authService: AuthService) {

      this.signupForm = this.fb.group({
            'firstName': ['', Validators.required],
            'lastName': ['', Validators.required]
        });
  }

  addUser(event: any) {
      event.preventDefault();
      this.addUserInvoked = true;
      ......
      ......
      this.authService.register(this.signupForm.value)
        .subscribe(
        (res: Response) => {
            if (res.ok) {
                this.registered = true;
            }
        },
        (error: any) => {
            this.registered = false;
        });
  }
}

It works fine. However, in my unit test when I try to test that when click is invoked on submit button then the call to the addUser is made. But unfortunately the addUser function is not invoked.
Below is my sample unit test
class RouterStub {
  navigateByUrl(url: string) { return url; }
}

let comp: UserComponent;
let fixture: ComponentFixture<UserComponent>;

describe('UserComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ UserComponent ],
      schemas:      [NO_ERRORS_SCHEMA]
    });
  });

  compileAndCreate();
  tests();
});

function compileAndCreate() {
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: Router,      useClass: RouterStub },
        { provide: AuthService, useValue: authServiceStub },
        FormBuilder
      ]
    })
    .compileComponents().then(() => {
      fixture = TestBed.createComponent(UserComponent);
      comp = fixture.componentInstance;
    });
  }));
}

function tests() {
    it('should call addUser when submitted', () => {
        const spy = spyOn(comp, 'addUser');

        //*************below method doesn't work and it refreshes the page***************
        //let btnSubmit = fixture.debugElement.query(By.css('#btnSubmit'));
        //btnSubmit.nativeElement.click();

        let form = fixture.debugElement.query(By.css('form'));
        form.triggerEventHandler('submit', null);
        fixture.detectChanges();

        expect(comp.addUser).toHaveBeenCalled();
        expect(authServiceStub.register).toHaveBeenCalled();
        expect(comp.registered).toBeTruthy('user registered');
    });

}

I've tried
fixture.debugElement.query(By.css('#btnSubmit')).nativeElement.click()

and
fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null)

but I am still unable to invoke addUser function. I've seen a question already posted on SO here but it's not helpful either.

A: Here is sample code: 1 : Replace Xcomponent with your component name 2 : Replace formID with id of your form.
import {async, ComponentFixture, TestBed} from '@angular/core/testing';

    import {FormsModule} from '@angular/forms';
    import {By} from '@angular/platform-browser';

    describe('Xcomponent', () => {
      let component: Xcomponent;
      let fixture: ComponentFixture<Xcomponent>;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [FormsModule],
          declarations: [Xcomponent]
        })
          .compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(Xcomponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });

      it('should create', () => {
        expect(component).toBeTruthy();
      });

      it('should call save() method on form submit', () => {
        /*Get button from html*/
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
        // Supply id of your form below formID
        const getForm = fixture.debugElement.query(By.css('#formID'));
        expect(getForm.triggerEventHandler('submit', compiled)).toBeUndefined();
      });

    });

A: *

*You need to spyon the function you wanna check and the functions it depends on.

*Second call fixture.detectChanges after you dispatch the event.

*Also make sure your form is visible on the dom otherwise the query will return null

I could do it like this:
let yourService: YourService;
beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    store = TestBed.get(YourService);
    fixture.detectChanges();
});

it('should call the right funtion', () => {
    spyOn(yourService, 'yourMethod');// or spyOn(component, 'yourMethod');
    const fakeEvent = { preventDefault: () => console.log('preventDefault') };
    fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', fakeEvent);
    expect(yourService.yourMethod).toHaveBeenCalledWith(
      //your logic here
    );
});

A: I had the same problem and the solution for me was that I had to import the 'FormsModule' into the configuration of my testing module.
TestBed.configureTestingModule({
            imports: [FormsModule]
});

Maybe this can help ?


text:
Q: Plugin usage with nested subdocuments in mongoose I have a schema in mongoose like this:
var subtopicSchema = new schema({
    name:String
})

var topicSchema = new schema({
   name:String,
    subtobpics:[subtopicSchema]
});

var subjectSchema = new schema({
    name:String,
    topics:[topicSchema]
})

var courseSchema = new schema({
    name:{type:String,unique:true},
    subjects:[subjectSchema]
});

And then I am using a 'unique validator plugin' like this:
courseSchema.plugin(uniqueValidator, { message: 'unique' });

So here is what i want to achieve:

*

*All courses should be unique

*All subjects within a particular course needs to be unique

*All topics within a particular subject to needs be unique

*All subtopics within a particular topic to needs be unique

So the question is: Is the current setup gonna work for the above four requirements?
If yes, why?
If not, How?


text:
Q: cxf: wsdl2java created a class that extends Service (javax.xml.ws.Service) I am new to java WS and WSDL.
I used wsdl2java to create java classes for my web service client and there was a class created with <Service Name>Service extends javax.xml.ws.Service
Please let me know what is the use of the class

A: I think of this as a 'locator' or 'factory' which can be used for making client-side (proxy) instances of the service. For example (where 'Example' is the Service Name):
ExampleService locator = new ExampleService();
locator.addPort( ExampleService.Example, SOAPBinding.SOAP11HTTP_BINDING
    , "http://myserver:8080/myapp/services/example" );
// now get the instance
Example example = locator.getExample();

Though with CXF you can use utilities such as the JaxWsProxyFactoryBean and ignore the <Service Name>Service class. Eg:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(Example.class);
factory.setAddress("http://myserver:8080/myapp/services/example");
factory.setUsername("user");
factory.setPassword("password");
Example example = (Example) factory.create();


text:
Q: Is there a simple way of setting up rethinkdb mirrors? For example this will start two servers in a cluster
() rethinkdb -n A --directory DATA_A
() rethinkdb -n B --directory DATA_B --port-offset 1 --join localhost:29015

However they aren't mirrors/replicas as DATA_A and DATA_B aren't equivalent.
So, essentially I'm wondering if there's a way to start a cluster or server that would mirror databases and/or tables, whereby a new mirror could be added at any time and it would essentially catch up with another database or table and then continue syncing in real time.
Then, at any time any mirror could be dumped and the archives would be equivalent.
Any info would be much appreciated, thanks!!

A: Looks like this can be done for each table by setting the replica key on reconfigure () or tableCreate ().
e.g.
() rethinkdb -n A --directory DATA_A --bind all
() rethinkdb -n B --directory DATA_B --port-offset 1 --join localhost:29015
() rethinkdb -n C --directory DATA_C --port-offset 2 --join localhost:29015

(JS) After Connecting and Creating up a Database
    var db = "";
    var table = "";
    r.db (db).tableCreate (table, {
        replicas: 3
    }).
    run (connection, (err, res) => {
        if (err) throw err;
    });

Afterwards all documents inserted in table should be present in all three data directories.
() rethinkdb-dump -c localhost:28015 -f A.tar.gz
() rethinkdb-dump -c localhost:28016 -f B.tar.gz
() rethinkdb-dump -c localhost:28017 -f C.tar.gz


text:
Q: jQuery ListView control not available in jQuery UI? For use with ASP.NET MVC I have been checking the jQuery UI for a listview control and one doesn't seem to exist.
Of course I can't use the asp.net control because I am using MVC.
Is there an alternative?  Or another recommended plugin?
There doesn't seem to be any available unless I am missing something.

A: Web Grid will work for your problem. You could also just render a table with rows in it, iterating over the model. I usually go with the latter since I have complete control over how and what gets rendered.


text:
Q: Properties of a continued fraction convolution operation Usually the partial numerators of a continued fraction are all 1s.
Has anyone considered the operation where you convolve 1 continued fraction with another, in other words, make a new continued fraction formed by replacing the partial numerators of continued fraction $b$ with the terms of continued fraction $a$ (with $a$ being truncated or repeated as necessary to cover the length of $b$) ? Is there any neat way to express the result of this in terms of the original real numbers ?
I am asking this before I have done any work or by-hand examples of this myself. I will probably run something on the computer or by hand over the weekend and will possibly update if it's interesting.


text:
Q: Why does the H2 console in Spring Boot show a blank screen after logging in? I'm using Spring Boot 1.4.1 with the H2 database.  I have enabled the H2 console as described in the reference guide by adding the following lines to my application.properties file:
spring.h2.console.enabled=true
spring.h2.console.path=/h2

When I go to the H2 console in Chrome 53 for Windows, I can see the login page and clicking the "Test Connection" button results in "Test successful":

But when I click on the "Connect" button, the screen turns completely blank.  When I view the source, I see "Sorry, Lynx not supported yet" (see the full source).  The same thing happens in Firefox.
Why is that happening?  I believe I am using the correct JDBC URL, as 4 different people posted on this question that you should use jdbc:h2:mem:testdb.

A: According to a blog post, a line needs to be added to
the configure method of the SecurityConfig class if you have the spring-boot-starter-security dependency in your project, otherwise you will see an empty page after logging into the H2 console:
http.headers().frameOptions().disable();

I added that line and it solved the problem.
Alternatively, the following line can be used (as mentioned here):
http.headers().frameOptions().sameOrigin();

A: I can resolve the same problem using the following code in my SecurityConfig class
@Override
protected void configure(HttpSecurity http) throws Exception {
    bla();
    bla();
    http.headers().frameOptions().sameOrigin();
}

I don't know what this line does, maybe someone with more experience can explain it.

A: Add this to your application.properties
 security.headers.frame=false

A: Along with the answer by @pacoverflow note the following:
As of Spring Boot 2.3.4. The DB Name is printed in the console:

Connect using that DB name:


text:
Q: How can I create a program that determines the first day of any 4 digit year by python Given a 4 digit year, return the number of the day on which January 1st falls. 0 is Sunday, …, 6 is Saturday

A: You can use the datetime library
import datetime

d = datetime.date(year, 1, 1)
weekday = d.isoweekday() % 7

The datetime library starts all weeks on Monday, so you need to do a bit of a conversion to get Sunday to be 0


text:
Q: What is the Best Input Array for Quick Sort I am working to find the best performing input array for quicksort.  My array is to be 100 elements long consisting of integers 1 thru 100.  I am choosing the last element as the pivot value.
I know I want the last element to be 50 so that I get two subarrays of equal length.  I then know I want element 49 to be 25 so that I get another event split.
I am a little confused as to where to put that original 25 so that after the first split it is in position 49.  Can anyone help me understand the algorithm a little better?
I am not necessarily looking for an example, but an explanation on how to achieve the positions.  I would like the answer for 10,100,1000... length array.

A: The best case for Quicksort using last element as pivot is the post-order traversal of the balanced binary search tree. For example:
     5
   /   \
  3      7
 / \    / \
1   4  6   8

The post-order traversal of this binary tree is
1 4 3 6 8 7 5


text:
Q: Kusto: How Do I Find all Databases which have a Table by its name within a Kusto Server I have a Kusto server. The server has multiple Databases.
I have a Table name, let's say Table1. But I don't know which database or databases have that table.
Is there a Kusto query to achieve this?

A: .show databases schema
.show databases schema
| where isempty(ColumnName)
| where TableName == "Customers"

DatabaseName
TableName
ColumnName
ColumnType
IsDefaultTable
IsDefaultColumn
PrettyName
Version
Folder
DocString

ContosoSales
Customers

false
false

Fiddle

Following the OP question:
.show databases schema
| take 5

*

*The 1st row describes the database

*The 2nd row describes the table

*The other rows describe the columns

DatabaseName
TableName
ColumnName
ColumnType
IsDefaultTable
IsDefaultColumn
PrettyName
Version
Folder
DocString

Samples

false
false

v3333.3

Samples
StormEvents

false
false

Storm_Events
US storm events. Data source: https://www.ncdc.noaa.gov/stormevents

Samples
StormEvents
StartTime
System.DateTime
false
false

Samples
StormEvents
EndTime
System.DateTime
false
false

Samples
StormEvents
EpisodeId
System.Int32
false
false

Fiddle


text:
Q: Answer prompts in bash I am often in the need of running a bash script that needs inputs from me and im trying to improve my workflow by automating this.
In my case my bash script is in need of 3 inputs from me:
What interface should i use?
1

Enter the password:
mypass

Please restart the program:
sudo bash restart

How can i make my bash script file auto input theses values? I have tried figuring this out but all the answer are about inputing yes or no.

A: If that is all the input your program needs, then you can simply put the inputs, one per line, in a text file, then run it like this:
$> ./yourscript.sh < yourtextfile.txt
For your example, the text file would contain
1
mypass
sudo bash restart

A: If you have such a script.sh:
#!/bin/bash
read -p "What intergace should i use?"$'\n' interfacenum
echo
read -p "Enter the password:"$'\n' pass
echo
read -p "Please restaart the program:"$'\n' prog
echo

echo "Values:"
for i in interfacenum pass prog; do
        echo $'\t'"$i=\"${!i}\""
done

You can 'input' the values into the script using echo or printf:
 echo -ne "1\nmypass\nsudo bash restart\n" | ./script.sh

A: You can use expect and autoexpect to achieve your task.
Let's say this is your file:
cat hello.sh
#!/usr/local/bin/bash

read -p "Select the interface: " interface
echo "interface selected: $interface"

read -p "Enter the username: " username
echo "username: $username"

You don't have to even write the scripts. You can you autoexpect to generate the script for you.
autoexpect ./hello.sh
autoexpect started, file is script.exp
Select the interface: 1
interface selected: 1
...(more input and output to generate the script)

Examine the generated script.
tail -n7 script.exp
expect -exact "Select the interface: "
send -- "1\r"
expect -exact "1\r
interface selected: 1\r
Enter the username: "
send -- "vivek\r"
expect eof

Now sit back and run the generated script
./script.exp
spawn ./hello.sh
Select the interface: 1
interface selected: 1
Enter the username: vivek
username: vivek


text:
Q: Difficulty display data as different column bootstrap I am trying to display 3 columns 1. Information
              2.HomeTeam vs AwayTeam
              3.Line
I am able to display Information and HomeTeam vs AwayTeam column properly. But 3rd column Line is not being displayed as new column but its data is displayed in 2nd column.
Here is the code that I tried
x.component.ts
import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {forkJoin} from 'rxjs';
import {map} from 'rxjs/operators';

@Component({
  selector: 'app-mlb-api',
  templateUrl: './mlb-api.component.html',
  styleUrls: ['./mlb-api.component.css']
})
export class MlbApiComponent  {
 loadedCharacter: {
 homeTeamName:string,
 awayTeamName:string,
 line:string,
 EventId:string,
 visitorTeam:string,
 homeTeam:string} = <{homeTeamName:string, awayTeamName:string, line:string, EventId:string, visitorTeam:string,homeTeam:string}>{};
    allhomeTeamName;
  allawayTeamName;
  allline;
  constructor(private http: HttpClient) {

  }

ngOnInit() {

    let character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json')
    .pipe(map((re: any) => re.events));
    let characterHomeworld = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17');

    forkJoin([character, characterHomeworld]).subscribe(([draftkingsResp, fantasylabsResp]) => {

      //this.allNames = draftkingsResp.map(r => r.name);
      //console.log(this.allNames);

      this.allhomeTeamName = draftkingsResp.map(r => r.homeTeamName);
      //console.log(this.allhomeTeamName);

       this.allawayTeamName = draftkingsResp.map(r => r.awayTeamName);
      //console.log(this.allawayTeamName);

       this.alllabel = draftkingsResp.map(r => r.offers).flat().map(o => o.label);
      //console.log(this.alllabel);

      this.allline = draftkingsResp.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line);
       console.log(this.allline);
      //this.allline will have 'undefined' as well
      //if you want then you can filter
      this.allline = this.allline.filter(l => !!l);
      console.log(this.allline);
    });
  }}

x.component.html

              Information
              HomeTeam vs AwayTeam
              Line

              Name

                  <ng-container *ngFor="let n of allhomeTeamName">

{{n}}

                  </ng-container>

                  <ng-container *ngFor="let n of allawayTeamName">

{{n}}

                  </ng-container>

                  <ng-container *ngFor="let n of allline">

{{n}}

                  </ng-container>

How can I display Line as separate column so that it does not merge with my second column?

A: It may be because of using *ngfor for columns.
You should create rows by ngfor.
In this way, rows are created based on an array of objects including your defined properties like Information, HomeTeam vs AwayTeam, Line and etc.
Your table body should be like this:

    {{ score.Information }}
    {{ score.HomeTeam }} vs {{ score.AwayTeam }}
    {{ score.Line }}

I don't know what is these properties for but the table is created by an array of objects with view of binded values from each object of the array in each row.

A: Try the below to display table and iterate table rows tr
HTML

                    Information
                    HomeTeam vs AwayTeam
                    Line

                       {{n}}

TS (app.component.ts)
export class AppComponent {
  allhomeTeamName = ["Yellow", "Blue", "Green"];
}

stackblitz demo


text:
Q: Material-ui Data Grid columns rendering Does anyone know how to get dropdown fields in DatGrid showing properly? Setting the TextField height doesn't work as expected for me.
Example: https://codesandbox.io/s/prod-leftpad-eixec?file=/src/App.js

A: Change the value of property box-sizing to inital:
.MuiSelect-select.MuiSelect-select {
  box-sizing: initial;
}

https://codesandbox.io/s/amazing-microservice-ner57?file=/src/styles.css:0-120

A: Just add an inputProps like this to your textfield:

      <TextField
        select
        SelectProps={{
          native: true
        }}
        inputProps={{
          style:{height: '100%'}
        }}
        size="small"
      >
        <option>Sel1</option>
        <option>Sel2</option>
      </TextField>


text:
Q: Property of $n$th Lucas number We have defined (in class) the Lucas number by $L_n = F_{n-1} + F_{n+1}$, where $F_i$ is the $i + 1$th Fibonacci number ($F_0 = 0, F_1 = 1$).
I have to prove that if $2 \mid n$ and $3\not\mid n$, then $L_n$ has a prime factor congruent to $3 \mod 4$. I have absolutely no idea on how to start this: I first thought about using induction, but I have no idea in this case how to prove my induction step, since I don't see how to write $L_n$ in function of some $L_k$'s on which I can use my induction hypothesis.
A second thought was that I could prove the contraposition, so assuming all possible prime factors are congruent with $2 \mod 4$ or $1 \mod 4$. However, in this case I am stuck on how to link this to the number $n$ and its divisors.
Any hints would be appreciated.

A: It is enough to prove that $L_{6n+2}$ and $L_{6n+4}$ are numbers of the form $4k-1$: in such a case they are odd numbers, hence they only have odd prime factors, and it is not possible that every prime factor is $\equiv 1\pmod{4}$, because otherwise $L_{6n+2}$ (or $L_{6n+4}$) would be $\equiv 1\pmod{4}$ too.
The Lucas numbers $\!\!\pmod{4}$ exhibit the following pattern:
$$\begin{array}{|c||c|c|c|c|c|c|c|c|}\hline n & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7  \\
\hline L_n & 2 & 1 & 3 & 4 & 7 & 11 & 18 & 29 \\
\hline L_n\pmod{4} & 2 & 1 & \color{red}{3} & 0 & \color{red}{3} & 3 & 2 & 1 \\ \hline\end{array} $$
with period $6$. Since $L_2\equiv L_4\equiv 3\pmod{4}$, the claim follows.

A: Since you're asked about the factorizations mod 4, start by looking at the Lucas numbers themselves mod 4.  You get the repeating sequence
$1, 3, 0, 3, 3, 2, 1, 3, 0, 3, 3, 2, \ldots$
Can you prove this pattern holds?  What does this imply about $L_n$ when $n$ is divisible by 2 but not by 3?


text:
Q: SQL query gives too many results I am trying to write a PostgreSQL query for the problem:
How many products have been bought in 2011? (Bought in 2011 means that the orderdescription is 'Completed' in 2011).

So far I've got this query:
    SELECT
      COUNT(product.id)
    FROM
      product
    JOIN orderitem ON
      productid = product.id
    JOIN "order" ON
      "order".id = orderitem.orderid AND
      EXTRACT(year FROM orderplaced) = 2011
    JOIN orderstatus ON
      orderstatus.orderid = "order".id
    JOIN orderstatusdescription ON
      orderstatusdescription.id = orderstatusdescriptionid AND
      orderstatusdescription.description = 'Completed';

But this results in 231410 products while the database only contains 1000. Using DISTINCT(product.id) logically results in a count of 1000.
I have no idea what I am doing wrong.

A: Slightly modified query from Andres Olarte:
SELECT
  COUNT(orderitem.productid)
FROM
  orderitem
JOIN "order" ON
  "order".id = orderitem.orderid
JOIN orderstatus ON
  orderstatus.orderid = "order".id
JOIN orderstatusdescription ON
  orderstatusdescription.id = orderstatusdescriptionid
WHERE
  EXTRACT(year FROM orderplaced) = 2011
AND  orderstatusdescription.description = 'Completed';

A: Try something like this:
SELECT
  COUNT(product.id)
FROM
  product
JOIN orderitem ON
  productid = product.id
JOIN "order" ON
  "order".id = orderitem.orderid
JOIN orderstatus ON
  orderstatus.orderid = "order".id
JOIN orderstatusdescription ON
  orderstatusdescription.id = orderstatusdescriptionid
WHERE
  EXTRACT(year FROM orderplaced) = 2011
AND  orderstatusdescription.description = 'Completed';

A: You're getting a larger number because you have multiple records being match by one or more of your join conditions.
For example, when you join the product table to orderitem you probably have more than one orderitem record that gets matched. So you get that product.id in your result set more than once.
Try COUNT(distinct product.id) -- that should give you the count of distinct products that were purchased.

A: This will tell you which products were bought in 2011 (untested -- not at computer with PG):
     select distinct OI.productid, P.description
     from orderitem OI inner join products P on OI.productid=P.id
     inner join
     (
     select order.id as orderid from order
     inner join orderstatusdescription OSD
     on order.orderstatusdescriptionid = OSD.id and OSD.description = 'COMPLETED'
     where extract(year from order.orderplaced)=2011
     ) as Orders2011
     on Orders2011.orderid = OI.orderid


text:
Q: Laravel 5.1 local server deployement I have a project developed with laravel 5.1 and it successfully run on localhost:8000/. I want to make this project accessible by other users who are on the same network. Can any one help how to do this. I am using windows 10 currently.

A: first, you check your IP address of network then
for example, we consider IP = 192.162.2.5
now you check open you site passing url = 192.162.2.5:8000 or 192.162.2.5
if site not open then --
try the following command on cmd
method 1
php artisan serve --host 192.162.2.5 --port 80
now  you open browser and pass URL = your IP (192.162.2.5)
method 2
if you want to your site run on port 8000
then run following command
php artisan serve --host 192.162.2.5 --port 8000
now  you open browser and pass URL = your IP (192.162.2.5)