text:
Q: git: add file history of other repository to existing file I made a mistake and copied files from a git repository to a new one. The files were changed and I noticed too late that I lost the original file history.
Consider the example script below. It creates a file, modifies it and commits the changes to a git repository. The file is copied to another repository afterwards and changed again. As the file was just copied, the other repository doesn't know about the first one. Is there any way to restore its file history? Could that be done with a whole repository that is based on another one (including deleted files)?
#!/bin/bash
# create first repository
mkdir repo1
cd repo1
git init
# create file and add it to git
echo foo > test.txt
git add test.txt
git commit -m "init" test.txt
# update file and commit
echo bar >> test.txt
git commit -m "update" test.txt
# replace content and commit
echo baz > test.txt
git commit -m "replacement" test.txt
cd ..
# create new repository
mkdir repo2
cd repo2
git init
# get a copy of latest fileversion
cp ../repo1/test.txt .
# add it to new repository
git add test.txt
git commit -m "init 2" test.txt
# modify it
echo sometext >> test.txt
git commit -m "update 2" test.txt
# do some magic here to include
# the whole file history in the next commands result
git log -p test.txt

A: First, git doesn't maintain "file history," it tracks the file names and contents as they change from one commit to the next. When you ask for file history, it is reconstructed (in some cases guessed) from the above.
You can copy the new files to the original repository, commit them there, and thus get the old history back. If you have new history on the new respository, you could ask git format-patch (see the manual page!) to create a series of patches to be applied with git am (again, refer to the manual!) to recreate the changes step by step.
Do such experiments on a scratch branch (or just a full copy of the repository), fooling around could damage it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: making a page and getting error: MethodNotAllowedHttpException in RouteCollection.php line 218 I am making a signup page and continuously I am getting this
MethodNotAllowedHttpException in RouteCollection.php line 218:

when I try to submit data.
what it should do, is to just submit it to the database. but it's not doing it.
welcome blade:
@extends('layouts.master')
@section('title')
Welcome!!
@endsection
@section('content')

Sign Up

        <form action="{{route('signup')}}" method="post">

                Your E-Mail
                <input class="form-control" type="text" name="email" id="email">

                Name
                <input class="form-control" type="text" name="name" id="name">

                Password
                <input class="form-control" type="password" name="password" id="password">

            <button type="submit" class="btn btn-primary">Submit</button>
            <input type="hidden" name="_token" value="{{Session::token()}}">
        </form>

Sign In

        <form action="#" method="post">

                Your E-Mail
                <input class="form-control" type="text" name="email" id="email">

                Password
                <input class="form-control" type="password" name="password" id="password">

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

@endsection

User controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\User;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
    $email = $request['email'];
    $name = $request['name'];
    $password = bcrypt($request['password']);

    $user = new User();
    $user -> email = $email;
    $user -> name = $name;
    $user -> password = $password;

    $user->save();

    return redirect()->back();
}

routes.php:
Route::group(['middleware' => ['web']], function(){

Route::get('/', function () {
return view('welcome');

});
Route::post('/signup',[
    'uses' => 'UserController@postSignUp',
    'as' => 'signup'
]);

});
Header blade:

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-bsexample-navbar-collapse-1" aria-expanded="false">
      Toggle navigation

    </button>

master blade:
<!DOCTYPE html>

<title>@yield('title')</title>
<link href="css/bootstrap.min.css" rel="stylesheet">

@include('includes.header')

@yield('content')

A: This Exectiption you are facing
either because you dont have that signup route in routes.php
OR
you are doing post but you have written route::get('signup')
So you need to write route::post there.

A: Since you are using PATCH in your form, you have to add a method field helper to spoof the PUT HTTP verb.
Add this in your form or use post as the verb in routes and form.
{{ method_field('PUT') }}

A: We have following HTTP methods - get, post, put, patch etc.
When you are trying to insert a record in the database table, we need to use POST method instead of the PATCH method in HTML form.

A: You forgot to specify route name
route('signup')
Route::post('/signup', 'UserController@postSignUp')->name('signup');

If your route like this then action should be '/signup' like this
Route::post('/signup',[
    'uses' => 'UserController@postSignUp',
    'as' => 'signup'
]);


text:
Q: Android ssh not returing anything On Buttonclick I recently made an app that executes a small ssh command on my pc when a button is pressed , however when I run it nothing seems to happen.
Im kinda new to android development - so I'm not too sure If i Used jsh properly.
My main activity is as follows:
package com.amex.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

public static String executeRemoteCommand(
        String username,
        String password,
        String hostname,
        int port) throws Exception {

    JSch jsch = new JSch();
    Session session = jsch.getSession("exiatron00", "192.168.0.10", 22);
    session.setPassword("password");

    // Avoid asking for key confirmation
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setConfig(prop);

    session.connect();

    // SSH Channel
    ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    channelssh.setOutputStream(baos);

    // Execute command
    channelssh.setCommand("touch /home/exiatron00/Desktop/sshtest.txt");
    channelssh.connect();
    channelssh.disconnect();

    return baos.toString();

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void Button(View view) {
    try {
        executeRemoteCommand("exiatron00", "NvidiaGtx1!", "192.168.1.10", 22);
    } catch (Exception e) {
        e.printStackTrace();
    }

 }
}

and my manifest is  :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.amex.myapplication">
  <uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
     </activity>
  </application>
</manifest>

But nothing happens when I press the button , the logcat is returns this:
2020-07-20 12:12:10.342 3461-3461/com.amex.myapplication V/AudioManager:    querySoundEffectsEnabled...
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:  com.jcraft.jsch.JSchException: android.os.NetworkOnMainThreadException
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at com.jcraft.jsch.Util.createSocket(Util.java:258)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at com.jcraft.jsch.Session.connect(Session.java:186)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at com.jcraft.jsch.Session.connect(Session.java:145)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at com.amex.myapplication.MainActivity.executeRemoteCommand(MainActivity.java:29)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at com.amex.myapplication.MainActivity.Button(MainActivity.java:56)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflat  er.java:397)
2020-07-20 12:12:10.346 3461-3461/com.amex.myapplication W/System.err:     at  android.view.View.performClick(View.java:7213)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.view.View.performClickInternal(View.java:7187)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.view.View.access$3500(View.java:828)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.view.View$PerformClick.run(View.java:27675)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.os.Handler.handleCallback(Handler.java:900)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:103)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:219)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:8347)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err: Caused by: android.os.NetworkOnMainThreadException
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
2020-07-20 12:12:10.347 3461-3461/com.amex.myapplication W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.Socket.connect(Socket.java:621)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.Socket.connect(Socket.java:570)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.Socket.<init>(Socket.java:450)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at java.net.Socket.<init>(Socket.java:218)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:     at com.jcraft.jsch.Util.createSocket(Util.java:252)
2020-07-20 12:12:10.348 3461-3461/com.amex.myapplication W/System.err:  ... 17 more

A: The problem: you are trying to run network operation on main/UI thread, which is forbidden by JSch.
The reason: Main (UI) thread is responsible for displaying user interface and handling user's interactions with application's visual elements. Network operation, or any other work that can take long time period to execute, can freeze UI thread and lead to ANR (Android Not Responding crash, which is fired when UI freezes for some time). So JSch prevents it by checking its execution thread. You should perform your operation on another thread.
You can use handler for that
private Handler mHandler;

private HandlerThread mHandlerThread;

public void startHandlerThread(){
    mHandlerThread = new HandlerThread("HandlerThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());
}

// Then in your button method
mHandler.postDelayed(
    new Runnable() {
        public void run() {
            executeRemoteCommand(yourParameters);
        }
    }
);

OR You can try to run it on another thread using oldschool Java Thread
Thread worker = new Thread(
    new Runnable() {
        public void run() {
            executeRemoteCommand(yourParameters);
        }
    }
);
worker.start();


text:
Q: How do you change the name of a root element in JSON with javascript? Is it possible to change the variable name of this:
var grid = {
    "name": "test",
    "columns":
    [
        {"name":"col1"},
        {"name":"col2"}
    ],
    "rows":
    [
         {"name":"col1", "value":"text1"},
         {"name":"col2", "value":"text2"}
    ]
}

I want to change grid to grid1.  Is this possible? Thanks for your guidance here. I did research this and did not find any solutions out there.

A: This isn't really JSON; it's just a JavaScript object. So "grid" is just a JavaScript variable. You can copy it to a variable with a different name, and delete the original, like this:
var grid1 = grid;
delete grid;


text:
Q: Using UIColor with CAShapeLayer I'm passing an RGB color to shapeLayer.fillColor and shapeLayer.strokeColor, and my code is crashing. Here's what I tried:
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = (UIColor(red: 57, green: 65, blue: 101, alpha: 1) as! CGColor)
shapeLayer.strokeColor = (UIColor(red: 57, green: 65, blue: 101, alpha: 1) as! CGColor)

If I write my RGB color as:
UIColor(red: 57, green: 65, blue: 101, alpha: 1)

Xcode gives me a warning to change it to:
(UIColor(red: 57, green: 65, blue: 101, alpha: 1) as! CGColor)

When I run Xcode's suggested fix, my app crashes. Why?

A: First of all the parameters red,green, blue and alpha must be in range from 0.0 to 1.0
Secondly, you must pass the cgColor to CGLayer, e.g.
let color = UIColor(red: 57.0/255.0, green: 65.0/255.0, blue: 101.0/255.0, alpha: 1)
shapeLayer.fillColor = color.cgColor
shapeLayer.strokeColor = color.cgColor

A: You are type casting UIColor as CGColor that is wrong. And RGB values must be the range from 0.0 to 1.0, Check the below code.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: bounds.origin.x+60,y: bounds.origin.y+107), radius: CGFloat(6), startAngle: CGFloat(0), endAngle:CGFloat(7), clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
circlePath.lineCapStyle = .round

let color = UIColor(red: 57.0/255.0, green: 65.0/255.0, blue: 101.0/255.0, alpha: 1).cgColor

shapeLayer.fillColor = color
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 3.0
self.layer.addSublayer(shapeLayer)

A: Fixing Your Code
You want something like this:
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor(red: 57, green: 65, blue: 101, alpha: 1).cgColor
shapeLayer.strokeColor = UIColor(red: 57, green: 65, blue: 101, alpha: 1).cgColor

How it Works
A Warning About Inheritance
Xcode warning you about something for that assignment is correct, because you're assigning a UIColor to a CGColor property, but the "fix-me" suggestion is wrong. (Xcode might be doing this because it sees that the class names are similar, but not identical. It might be worth filing a radar.)
One place you'll see this a lot is typecasting a custom UITableViewCell subclass to the basic cell class, but that won't work here. CGColor does not inherit from UIColor, nor does UIColor inherit from CGColor. CGColor is a CFTypeRef and UIColor inherits from `NSObject.
One of These Is Not Like the Other
Now, why are these colors different?
CG stands for "Core Graphics" and is at a lower level than UIKit which defines the UIColor class. One color object is part of UIKit and the part of Core Graphics.
The documentation says that UIColor is:

An object that stores color data and sometimes opacity (alpha value)."

A little further down, the overview says that UIColor represents itself internally as a CGColor within the predetermined color space.
CGColor, on the other hand, is:

A set of components that define a color, with a color space specifying how to interpret them."

Conceptually, very similar, but not exactly the same thing. UIColor is defined in the sRGBA space (as noted here) but CGColor will contain info about what color space it's in.
Now, the animation layer you're using is part of Core Animation, which is yet another Apple framework. Core Animation isn't part of UIKit, and it's not "on top of" UIKit either, so its classes don't use UIColor. Core Animation uses CGColor for its representations of colors.
UIColor is so easy to instantiate, though, and we're in UIKit-land much of the time anyway. How can we customize CALayer and friends while working in our UIViews and UIViewControllers? Luckily, UIColor exposes the CGColor version of itself, with the .cgColor property.
A Note About Color Spaces
Some of the other answers note that you need to pass values between 0.0 and 1.0.  This is true, but it's relevant to note that as of iOS 10, Apple has added some wider-color capabilities to iOS.
This means that it's actually possible to pass in values less than 0.0 and greater than 1.0. From the UIColor documentation:

When working in an extended color space, color values are not clamped to fit inside the color gamut, meaning that component values may be less than 0.0 or greater than 1.0. When displayed on an sRGB display, such colors are outside the gamut and will not be rendered accurately.

You probably won't need to worry about color spaces right now, but it's important to understand the fundamentals if you want to do things beyond showing a color onscreen. (Generating inverted or complementary colors are some examples.)
Session 712 from WWDC 2016 (link) covers this new API in depth, and I'd recommend that you take a look at it once you're more comfortable with the basics.
Finally, there's an Apple Tech Note (TN2313) that discusses this in more depth than I could ever imagine. If you want to learn a lot about colors and color spaces on iOS and macOS, read the tech note, entitled "Best Practices for Color Management in OS X and iOS."


text:
Q: Performance Optimization of scraping code I am studying web scraping for big data, so I wrote the following code to take some information from a local server on our campus. It works fine but I think the performance is very slow; each record takes 0.91s to get stored in the database. What the code does is open a web page, take some content and store it on disk.
My goal is to lower the time elapsed for scraping a record to something near 0.4s (or less, if possible).
#!/usr/bin/env python

import scraperwiki
import requests
import lxml.html
for i in range(1, 150):
    try:
        html = requests.get("http://testserver.dc/"+str(i)"/").content
        dom = lxml.html.fromstring(html)
        for entry in dom.cssselect('.rTopHeader'):
            name = entry.cssselect('.bold')[0].text_content()

        for entry in dom.cssselect('div#rProfile'):
            city = entry.cssselect('li:nth-child(2) span')[0].text_content()

        for entry in dom.cssselect('div#rProfile'):
            profile_id = entry.cssselect('li:nth-child(3) strong a')[0].get('href')
        profile = {
                'name':name,
                'city':city,
                'profile_id':profile_id
            }
        unique_keys = [ 'profile_id' ]
        scraperwiki.sql.save(unique_keys, profile)
        print jeeran_id
    except:
        print 'Error: ' + str(i)

A: It is very good, you have clear aim at how far you want to optimize.
Measure time needed for scraping first
It is likely, the limiting factor is scraping the urls.
Simplify your code and measure, how long it takes to scrape. If this does not meet your timing criteria (like one request would take 0.5 seconds), you have to go do scraping in parallel. Search StackOverflow, there are many such questions and answers, using threading, green threads etc.
Further optimization tips
Parsing XML - use iterative / SAX approach
Your DOM creation can be turned into iterative parsing. It need less memory and is very often much faster. lxml allows methods like iterparse. Also see related SO answer
Optimize writing into database
Writing many records one by one can be turned into writing them in bunches.


text:
Q: Where does znc keeps its channel logs and how do they interact with the client? So I am trying out znc, a popular IRC bouncer and hexchat. Apparently znc keeps the logs and sends to hexchat each time.
What I don't get is, how does hexchat know not to show me duplicate logs (its own local logs + the ones that just got sent)?
Where are the logs stored? I have tried deleting the local logs (the ones in appdata) as well as rebooting the server, but hexchat still shows me the logs.


text:
Q: Is it possible to exclude template member variables by conditions on template arguments? I am currently writing a class which should specialize depending on a template argument.
I am now wondering whether it is possible to leave out certain member variables for specific specializations to be more exact depending on whether a numeric template argument is larger than X.
So for example:
template<int N>
class Test
{
   int a;
   int b;
}

template<N > X>
class Test
{
  int a;
}

I was thinking about the use of std::conditional but that seems to result in at least one type being picked. I could of course the D-Pointer method and std::conditional and put the specialization into different objects that are pointed at but I wondered whether there was a better way.
An alternative I see is to use an abstract base class and have two implementations one for N < X and one for N >= X but I'm not sure that this would be better.

A: Just use SFINAE.
template<int N, typename = void>
class Test
{
   int a;
   int b;
};

template<int N>
class Test<N, typename std::enable_if<(N > X)>::type>
{
  int a;
};


text:
Q: Returning a DataTable using Entity Framework ExecuteStoreQuery I am working with a system that has many stored procedures that need to be displayed. Creating entities for each of my objects is not practical.
Is it possible and how would I return a DataTable using ExecuteStoreQuery ?
public ObjectResult<DataTable> MethodName(string fileSetName) {
using (var dataContext = new DataContext(_connectionString))
{
var returnDataTable = ((IObjectContextAdapter)dataContext).ObjectContext.ExecuteStoreQuery<DataTable>("SP_NAME","SP_PARAM");
return returnDataTable;
}

A: This method uses the connection string from the entity framework to establish an ADO.NET connection, to a MySQL database in this example.
using MySql.Data.MySqlClient;

public DataSet GetReportSummary( int RecordID )
{
    var context = new catalogEntities();

    DataSet ds = new DataSet();
    using ( MySqlConnection connection = new MySqlConnection( context.Database.Connection.ConnectionString ) )
    {
        using ( MySqlCommand cmd = new MySqlCommand( "ReportSummary", connection ) )
        {
            MySqlDataAdapter adapter = new MySqlDataAdapter( cmd );
            adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            adapter.SelectCommand.Parameters.Add( new MySqlParameter( "@ID", RecordID ) );
            adapter.Fill( ds );
        }
    }
    return ds;
}

A: Yes it can easily be done like this:
var table = new DataTable();
using (var ctx = new SomeContext())
{
    var cmd = ctx.Database.Connection.CreateCommand();
    cmd.CommandText = "Select Col1, Col2 from SomeTable";

    cmd.Connection.Open();
    table.Load(cmd.ExecuteReader());
}

A: By the rule, you shouldn't use a DataSet inside a EF application. But, if you really need to (for instance, to feed a report), that solution should work (it's EF 6 code):
    DataSet GetDataSet(string sql, CommandType commandType, Dictionary<string, Object> parameters)
    {
        // creates resulting dataset
        var result = new DataSet();

        // creates a data access context (DbContext descendant)
        using (var context = new MyDbContext())
        {
            // creates a Command
            var cmd = context.Database.Connection.CreateCommand();
            cmd.CommandType = commandType;
            cmd.CommandText = sql;

            // adds all parameters
            foreach (var pr in parameters)
            {
                var p = cmd.CreateParameter();
                p.ParameterName = pr.Key;
                p.Value = pr.Value;
                cmd.Parameters.Add(p);
            }

            try
            {
                // executes
                context.Database.Connection.Open();
                var reader = cmd.ExecuteReader();

                // loop through all resultsets (considering that it's possible to have more than one)
                do
                {
                    // loads the DataTable (schema will be fetch automatically)
                    var tb = new DataTable();
                    tb.Load(reader);
                    result.Tables.Add(tb);

                } while (!reader.IsClosed);
            }
            finally
            {
                // closes the connection
                context.Database.Connection.Close();
            }
        }

        // returns the DataSet
        return result;
    }

A: In my Entity Framework based solution I need to replace one of my Linq queries with sql - for efficiency reasons.
Also I want my results in a DataTable from one stored procedure so that I could create a table value parameter to pass into a second stored procedure. So:

*

*I'm using sql

*I don't want a DataSet

*Iterating an IEnumerable probably isn't going to cut it - for efficiency reasons
Also, I am using EF6, so I would prefer DbContext.SqlQuery over ObjectContext.ExecuteStoreQuery as the original poster requested.
However, I found that this just didn't work:
_Context.Database.SqlQuery<DataTable>(sql, parameters).FirstOrDefault();
This is my solution. It returns a DataTable that is fetched using an ADO.NET SqlDataReader - which I believe is faster than a SqlDataAdapter on read-only data. It doesn't strictly answer the question because it uses ADO.Net, but it shows how to do that after getting a hold of the connection from the DbContext
    protected DataTable GetDataTable(string sql, params object[] parameters)
    {
        //didn't work - table had no columns or rows
        //return Context.Database.SqlQuery<DataTable>(sql, parameters).FirstOrDefault();

        DataTable result = new DataTable();
        SqlConnection conn = Context.Database.Connection as SqlConnection;
        if(conn == null)
        {
            throw new InvalidCastException("SqlConnection is invalid for this database");
        }
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddRange(parameters);
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                result.Load(reader);
            }
            return result;
        }
    }

A: Yes it's possible, but it should be used for just dynamic result-set or raw SQL.
public DataTable ExecuteStoreQuery(string commandText, params Object[] parameters)
{
    DataTable retVal = new DataTable();
    retVal = context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();
    return retVal;
}

Edit: It's better to use classical ADO.NET to get the data model rather than using Entity Framework because most probably you cannot use DataTable even if you can run the method: context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();
ADO.NET Example:
public DataSet GetResultReport(int questionId)
{
    DataSet retVal = new DataSet();
    EntityConnection entityConn = (EntityConnection)context.Connection;
    SqlConnection sqlConn = (SqlConnection)entityConn.StoreConnection;
    SqlCommand cmdReport = new SqlCommand([YourSpName], sqlConn);
    SqlDataAdapter daReport = new SqlDataAdapter(cmdReport);
    using (cmdReport)
    {
        SqlParameter questionIdPrm = new SqlParameter("QuestionId", questionId);
        cmdReport.CommandType = CommandType.StoredProcedure;
        cmdReport.Parameters.Add(questionIdPrm);
        daReport.Fill(retVal);
    }
    return retVal;
}

A: No, I don't think that'll work - Entity Framework is geared towards returning entities and isn't meant to return DataTable objects.
If you need DataTable objects, use straight ADO.NET instead.

A: The easiest way to return a DataTable using the EntityFramework is to do the following:
MetaTable metaTable = Global.DefaultModel.GetTable("Your EntitySetName");

For example:
MetaTable metaTable = Global.DefaultModel.GetTable("Employees");

A: Maybe your stored procedure could return a complex type?
http://blogs.msdn.com/b/somasegar/archive/2010/01/11/entity-framework-in-net-4.aspx


text:
Q: D3 samples in a Microsoft Stack We're trying to get familiar with D3 (http://d3js.org/), in particular samples such as http://bl.ocks.org/mbostock/3306362 and http://bl.ocks.org/mbostock/2206590. It seems all these samples use local file IO to load geolocation info. The following code snippets are common:
queue()
.defer(d3.json, "/mbostock/raw/4090846/us.json")
.defer(d3.tsv, "unemployment.tsv")
.await(ready)

while other samples often use this signature to load data:
d3.json("someJSONFile.json", function(error, uk) {
console.log(uk);
});

We've created several local html files to test out the samples, but we're running into security issues. It's apparent the script is accessing a local file, which is really giving us problems in a Microsoft stack (Apple or Linux isn't an option at this time, though we have tried Chrome, with no success). How can we enable the html file or refactor the script to have access to the local files?

A: You need to host the files through a web server since web browsers restrict what types of files can be accessed locally. The simplest way to do this on a windows machine:

*

*Install python

*Navigate to the directory holding your example with cmd.exe. Holding down shift, right clicking on the folder with the example and selecting Open Command Window Here is the easiest way to do this.

*On the command prompt, enter python -m SimpleHTTPServer 8000, or python -m http.server 8000, on newer versions to start a web server.

*Open a web browser (I would really suggest chrome, the dev tools are way ahead of ff and ie), go to 127.0.0.1:8000. The example should show up.


text:
Q: How to get url from webview whenever user move to other pages How can I get a URL from webView whenever the URL is changed?
I want to change the button color when current URL is changed. So I need to check the current URL all the time.
And I also would like to get URL value as a String.
I tried the below code but it doesn't work at all.
NotificationCenter.default.addObserver(self, selector: #selector(urlChecker), name: NSNotification.Name.NSURLCredentialStorageChanged, object: webView)

A: you can use:
1. Solution
UIWebViewDelegate
https://developer.apple.com/reference/uikit/uiwebviewdelegate/1617945-webview
optional func webView(_ webView: UIWebView,
  shouldStartLoadWith request: URLRequest,
       navigationType: UIWebViewNavigationType) -> Bool

UIWebViewNavigationType:
https://developer.apple.com/reference/uikit/uiwebviewnavigationtype
don't forget to return true

case linkClicked
User tapped a link.
case formSubmitted
User submitted a form.
case backForward
User tapped the back or forward button.
case reload
User tapped the reload button.
case formResubmitted
User resubmitted a form.
case other
Some other action occurred.

2. Solution
Inject Javascript JavaScript MessageHandler
(credit to Vasily Bodnarchuk)
Solution is here: https://stackoverflow.com/a/40730365/1930509

Swift 3 example.
Description
The script is inserted into page which will displayed in WKWebView.
  This script will return the page URL (but you can write another
  JavaScript code). This means that the script event is generated on the
  web page, but it will be handled in our function:
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {...}

Full Code example
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView = WKWebView()
    let getUrlAtDocumentStartScript = "GetUrlAtDocumentStart"
    let getUrlAtDocumentEndScript = "GetUrlAtDocumentEnd"

     override func viewDidLoad() {
             super.viewDidLoad()

            let config = WKWebViewConfiguration()
            config.addScript(script: WKUserScript.getUrlScript(scriptName: getUrlAtDocumentStartScript),
 scriptHandlerName:getUrlAtDocumentStartScript, scriptMessageHandler:
 self, injectionTime: .atDocumentStart)
            config.addScript(script: WKUserScript.getUrlScript(scriptName: getUrlAtDocumentEndScript),
scriptHandlerName:getUrlAtDocumentEndScript, scriptMessageHandler:
self, injectionTime: .atDocumentEnd)

             webView = WKWebView(frame:  UIScreen.main.bounds, configuration: config)
            webView.navigationDelegate = self
             view.addSubview(webView)
        }

     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         webView.loadUrl(string: "http://apple.com")
    }
}

extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {

            case getUrlAtDocumentStartScript:
                print("start: \(message.body)")

            case getUrlAtDocumentEndScript:
                print("end: \(message.body)")

            default:
                break;
        }
    }
}

extension WKUserScript {
    class func getUrlScript(scriptName: String) -> String {
        return "webkit.messageHandlers.\(scriptName).postMessage(document.URL)"
    }
}

extension WKWebView {
    func loadUrl(string: String) {
        if let url = URL(string: string) {
            load(URLRequest(url: url))
        }
    }
}

 extension WKWebViewConfiguration {
        func addScript(script: String, scriptHandlerName:String, scriptMessageHandler: WKScriptMessageHandler,injectionTime:WKUserScriptInjectionTime) {
             let userScript = WKUserScript(source: script, injectionTime: injectionTime, forMainFrameOnly: false)
             userContentController.addUserScript(userScript)
             userContentController.add(scriptMessageHandler, name: scriptHandlerName)
        }
    }

Info.plist
add in your Info.plist transport security setting
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Result

Resources ##

Document Object Properties and Methods


text:
Q: Determining the dimensions of subspaces of M? Let $M$ be the space of three by three matrices.  Let $A = \begin{bmatrix}1&0&-1\\-1&1&0\\0&-1&1\end{bmatrix}$.
Interpreting $A$ as a linear operator from $M$ to $M$ (rather than as a linear operator from $\Bbb R^3$ to $\Bbb R^3$), determine the dimensions of the nullspace and columnspace.

In problem 11.2 c), how did we determine the dimensions of "nullspace" and "column space"?
Why are the values 3, and 6, when they should be 2 (pivot columns), and 1 (free variable)?

A: Hint: If all that is giving you difficulty in understanding the problem is the fact that the domain and codomain of our linear transformation is not of the form $\Bbb R^n$, but is instead a space of matrices $M$, we can redescribe the problem.
Reinterpreting a matrix $\begin{bmatrix}a&b&c\\d&e&f\\g&h&i\end{bmatrix}$ in $M$ instead as a vector $\begin{bmatrix}a\\b\\c\\d\\e\\f\\g\\h\\i\end{bmatrix}$ in $\Bbb R^9$, we would have our transformation $A$ as:
$$A\left(\begin{bmatrix}a\\b\\c\\d\\e\\f\\g\\h\\i\end{bmatrix}\right) = \begin{bmatrix}a-g\\b-h\\c-i\\d-a\\e-b\\f-c\\g-d\\h-e\\i-f\end{bmatrix}$$
From here you can describe $A$ using a matrix (it won't be $3\times 3$ anymore, do you see what size it will be?) and then use your familiar techniques of row reduction or whatever else.


text:
Q: Swift naming conventions for booleans, constants and @IBAction selectors? I have been reading the API Design Guidelines for Swift and some posts regarding naming those entities I said in the title of the question, but I am still not clear about that.
I am developing in Swift 3.

*

*Boolean variables should be prefixed with is-, with has-, or both prefixes are appropriate?

*Methods returning Bool selectors should also be prefixed is/has?

*Constant variables that, for example, you define to avoid magic numbers, should start with a k? (for example, kMaxLength). I think this was a convention for Objective-C, is it for Swift as well?

*The name for an @IBAction selector, should refer to the control that triggers the action, or the task it does? (For example: doneButtonTapped vs validateInput)

A: Swift general naming conventions are available here https://swift.org/documentation/api-design-guidelines/#general-conventions

*

*Uses of Boolean methods and properties should read as assertions about
  the receiver when the use is nonmutating, e.g. x.isEmpty,
  line1.intersects(line2).

*The names of other types, properties, variables, and constants should read as nouns.


text:
Q: unity game crashes if I press home button on game circle layout screen I have made a game on unity and added amazon game circle leaderboards in it. My leaderboards work fine but if I press android home button while on leaderboard screen and then reopen after opening other applications my game crashes...
A way out I tried was to use application.quit if home button is pressed but I cannot access android home button from unity either.

A: I would suggest you also post this question on Unity answers as that site gets a lot more Unity specific users and content.
http://answers.unity3d.com/index.html
As for your question, do you get any error messages through logcat? I had similar issues with a different library and it ended up being a handset specific issue which could not be solved due to the closed nature of the library.
Application.quit() may not be called if the application has crashed.


text:
Q: Obtaining a HERE Maps Embed code for reuse Can someone tell me how I get a simple embed code from here maps? I simply can't find the Embed button which in my opinion should be there on any map website. Ironically I'm making a website for here so I'm not allowed to get a google map.

A: For a simple static HERE Map you should look at the Map Image API - this will embed a simple image. However if you want a moveable map, you can use the HERE Maps API for JavaScript in an IFrame and pass the latitude, longitude and zoom level of your choice e.g. something like:
<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, width=device-width" />
  <link rel="stylesheet" type="text/css"
    href="http://js.api.here.com/v3/3.0/mapsjs-ui.css" />

The Iframe can be called specifying the height and width:

The result is something like this:

Of course you could then add in all the usual other stuff as well, such as adding markers and so on, to make the map do what you want, not just what the provider offers. Why should you be restricted to a single look-and-feel as offered by the map provider?


text:
Q: Position Background Image I was wondering if there is any possible way to position a background image on a button in C# windows forms? I am using Visual Studio 2013, and  I noticed that you can use the BackgroundImageLayout but that is very limited. I would like to move the background image around by pixel position, or relative to the button. Kind of like this:

I have been on google for a while now with no luck. If anyone could point me in the right direction, or show my an article to read it would be greatly appreciated. Thank you.

A: You could use the Paint event (or subclass Button to override OnPaint) to draw the image yourself:
private void myButton_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(myImage, myButton.ClientRectangle);
}

You could then use the TextAlign and Padding properties to control the location of the text.
Note that you should not assign the image to the Button's Image or BackgroundImage properties, otherwise .NET will also render the image.


text:
Q: Issues on printing DataGridView in asp.net I have a DataGridViewin my asp.net project as below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" EmptyDataText="No List Yet" EnableModelValidation="True" CssClass="table table-hover" Width="100%">
    <Columns>
    .....
        <asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="DataDetails.aspx?ID={0}"
               HeaderText="View Details" SortExpression="ID" Text="View Details" HeaderStyle-BackColor="#CCCCCC">
            <ItemStyle HorizontalAlign="Center" Width="150px" />
        </asp:HyperLinkField>
    </Columns>
</asp:GridView>

When I print this page, I get resuls as expected for other columns. But for this last column, I get results as below:

I am trying to remove the text inside the parenthesis. Why is this text visible for printing? And how can I remove it for printing? Any help would be appreciated.


text:
Q: Drag Segue To Self in Storyboard I want to drag a segue from my viewcontroller, to itself. So I can push "infinite" instances of that particular view controller.
I know how to do this in code (I.e instansiate the view controller programmatically). However, I want to use segues as far as possible.
I've found a few "hacks" for making segue to self in storyboard, but I don't like hacks, so my question is;
Is there a clean way to make a segue back to self in the Storyboard? I dont want to drag it from a button or such, I just want a generic segue that i can use with:
[self performSegueWithIdentifier:@"segueIdentifier"]

Thanks.

A: You can do this in the storyboard itself. Drag a Storyboard Reference from the Object Library, and then control drag from your view controller to the storyboard reference to create a segue, and select the type of transition. Then with the storyboard reference selected, make sure it's attributes in the inspector are set to the same storyboard file, and the same view controller referenced by it's storyboard ID.

A: You can drag the segue from the trigger to the same view controller. You'll need to drag it to the the yellow box in the top left, on top of the view controller in Xcode 6.
If you try to drag it onto the VC itself Xcode will think that you're trying to add a layout constraint.

A: You can embed your TableViewController in a Navigation Controller and segue to the Navigation controller.


text:
Q: Regular expression for match sentences not starts with specified prefix I would like to find strings in double quotes but only if they used outside of call of specified function foo. For example:
foo("some str1"); // ignore
foo2("another string"); // need this
"simple string"; // need this
foo(L"wide str"); // ignore
#define NAME "name" // need this
int i = foo("must be ignored"); // ignore

I have tried \b(?!foo\()L?"[^"]*"\b from this answer, but it doesn't work correct. Used end double quote on one line as begin on another. Like this "); // ignore<CR> foo2("
If I suppose I should include possessive quantification. To substring not satisfying excluded completely from further search. But don't know how to do it correctly.
It is required to search for files in the Embarcadero RAD Studio XE, but satisfied with any decision in the Perl regexp syntax.
Important: wants to find all occurences of double quoted strings outside of foo function. And not to be distracted by a string inside the foo.

A: You can try it here: https://regex101.com/r/mG7gP7/1
I match two scenario

*

*Search for function not name foo, and match the string inside quotes.

*Any text inside quotes where there is no function call

A: What do you think about this one?
/(^(?!foo\()|\)).*"(.*)"/gm


text:
Q: PHP WHY Warning: filemtime(): stat failed for Warning: filemtime(): stat failed for includes\img\defaultimg.jpg in

I read and researched but found nothing useful
in the php manual only says this:
If PHP's integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning "stat failed". All stat()-related commands will exhibit the same behavior.

but is just a jpg  900k
this is my code works fine in xammp, but not in production
  $dirimg="includes/img/";  //this one also throws warning
        $filename = "".$dirimg."".$resultsb['Img'].".jpg";  //the path
        if(file_exists ($filename)){  // exists?
        $timeimg=filemtime($filename);
       $srci="".$dirimg."".$resultsb['Img'].".jpg?=".$timeimg."";
        }else{$timeimg=filemtime("includes\img\defaultimg.jpg");  //another path, the file does exists
       $srci="includes\img\defaultimg.jpg?=".$timeimg.""; } //

both throw the same warning in the respective path,  the file exits btw
the image can be seen,
but i need to know
when it is modified so the browser refreshes it

A: It was the slashes  hahaha , the server is in Linux
So, they have to be like this  "includes/img/defaultimg.jpg?="
instead of "includes\img\defaultimg.jpg?="
LOL


text:
Q: Access scheduled run time inside Kubertes CronJob I'm trying run a cron job with Kubernetes. The job executes a program that performs some computation based on the job's scheduled start time. How can my program get access to this value during its execution?

A: Option 1 (easiest): Put the same value to job container environment variable. I assume you install with helm or similar mechanism, so it should be easy to reuse schedule variable in 2 places.
Option 2: Use a combination of a Role, RoleBinding and ServiceAccount, then use kubectl / language k8s client to retrieve cronjob (you will need to know its name if there's multiple in a namespace) and get schedule from its parameters.
Option 3: https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/ This is a variation of 1 but using the resourceFieldRef. Not sure you can refer a cronjob resource tho :(


text:
Q: Scrapy start Crawling after login Disclaimer:  The site I am crawling is a corporate intranet and I modified the url a bit for corporate privacy.
I managed to log into the site but I have failed to crawl the site.
Start from start_url https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf( this site would direct you to a similar site with more complex url :
i.e.

https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf/h_RoomHome/ade682e34fc59d274825770b0037d278/?OpenDocument
  {unid=ADE682E34FC59D274825770B0037D278})

for every page including the start_url, I want to crawl all href found under //li/<a>( For every page it crawled, there would be abundant number of hyperlinks available, and some of them will duplicate because you can access  both the parent and children sites on the same page.

As you may see, the href does not composite the actual link ( the link quoted above) we see when we crawl into that page. There is also a # in front of its useful content. Would it be the source of problem?
For restricted_xpaths,I have restricted the path to 'logout' the page.
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.http import Request, FormRequest
from scrapy.linkextractors import LinkExtractor
import scrapy

class kmssSpider(CrawlSpider):
    name='kmss'
    start_url = ('https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf',)
    login_page = 'https://kmssqkr.ccgo.sarg/LotusQuickr/dept/Main.nsf?OpenDatabase&Login'
    allowed_domain = ["kmssqkr.sarg"]

    rules= (Rule(LinkExtractor(allow=(r'https://kmssqkr.sarg/LotusQuickr/dept/\w*'),restrict_xpaths=('//*[@id="quickr_widgets_misc_loginlogout_0"]/a'),unique= True),
                  callback='parse_item', follow = True),
                                )
#    r"LotusQuickr/dept/^[ A-Za-z0-9_@./#&+-]*$"
#    restrict_xpaths=('//*[@id="quickr_widgets_misc_loginlogout_0"]/a'),unique = True)

    def start_requests(self):
        yield Request(url=self.login_page, callback=self.login ,dont_filter = True
                )
    def login(self,response):
        return FormRequest.from_response(response,formdata={'user':'user','password':'pw'},
                                        callback = self.check_login_response)

    def check_login_response(self,response):
        if 'Welcome' in response.body:
            self.log("\n\n\n\n Successfuly Logged in \n\n\n ")
            yield Request(url=self.start_url[0])
        else:
            self.log("\n\n You are not logged in \n\n " )

    def parse_item(self, response):
        self.log('Hi, this is an item page! %s' % response.url)
        pass

Log:
2015-07-27 16:46:18 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2015-07-27 16:46:18 [boto] DEBUG: Retrieving credentials from metadata server.
2015-07-27 16:46:19 [boto] ERROR: Caught exception reading instance data
Traceback (most recent call last):
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\site-packages\boto\utils.py", line 210, in retry_url
    r = opener.open(req, timeout=timeout)
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\urllib2.py", line 431, in open
    response = self._open(req, data)
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\urllib2.py", line 449, in _open
    '_open', req)
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\urllib2.py", line 1227, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Users\hi\AppData\Local\Continuum\Anaconda\lib\urllib2.py", line 1197, in do_open
    raise URLError(err)
URLError: <urlopen error timed out>
2015-07-27 16:46:19 [boto] ERROR: Unable to read instance data, giving up
2015-07-27 16:46:19 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, HttpProxyMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-07-27 16:46:19 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-07-27 16:46:19 [scrapy] INFO: Enabled item pipelines:
2015-07-27 16:46:19 [scrapy] INFO: Spider opened
2015-07-27 16:46:19 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-07-27 16:46:19 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-07-27 16:46:24 [scrapy] DEBUG: Crawled (200) <GET https://kmssqkr.ccgo.sarg/LotusQuickr/dept/Main.nsf?OpenDatabase&Login> (referer: None)
2015-07-27 16:46:28 [scrapy] DEBUG: Crawled (200) <POST https://kmssqkr.ccgo.sarg/names.nsf?Login> (referer: https://kmssqkr.ccgo.sarg/LotusQuickr/dept/Main.nsf?OpenDatabase&Login)
2015-07-27 16:46:29 [kmss] DEBUG:

 Successfuly Logged in

2015-07-27 16:46:29 [scrapy] DEBUG: Redirecting (302) to <GET https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf/h_Toc/d0a58cff88e9100b852572c300517498/?OpenDocument> from <GET https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf>
2015-07-27 16:46:29 [scrapy] DEBUG: Redirecting (302) to <GET https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf/h_RoomHome/ade682e34fc59d274825770b0037d278/?OpenDocument> from <GET https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf/h_Toc/d0a58cff88e9100b852572c300517498/?OpenDocument>
2015-07-27 16:46:29 [scrapy] DEBUG: Crawled (200) <GET https://kmssqkr.sarg/LotusQuickr/dept/Main.nsf/h_RoomHome/ade682e34fc59d274825770b0037d278/?OpenDocument> (referer: https://kmssqkr.sarg/names.nsf?Login)
2015-07-27 16:46:29 [scrapy] INFO: Closing spider (finished)
2015-07-27 16:46:29 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1954,
 'downloader/request_count': 5,
 'downloader/request_method_count/GET': 4,
 'downloader/request_method_count/POST': 1,
 'downloader/response_bytes': 31259,
 'downloader/response_count': 5,
 'downloader/response_status_count/200': 3,
 'downloader/response_status_count/302': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2015, 7, 27, 8, 46, 29, 286000),
 'log_count/DEBUG': 8,
 'log_count/ERROR': 2,
 'log_count/INFO': 7,
 'log_count/WARNING': 1,
 'request_depth_max': 2,
 'response_received_count': 3,
 'scheduler/dequeued': 5,
 'scheduler/dequeued/memory': 5,
 'scheduler/enqueued': 5,
 'scheduler/enqueued/memory': 5,
 'start_time': datetime.datetime(2015, 7, 27, 8, 46, 19, 528000)}
2015-07-27 16:46:29 [scrapy] INFO: Spider closed (finished)

  [1]: http://i.stack.imgur.com/REQXJ.png

----------------------------------UPDATED---------------------------------------
I saw the cookies format in http://doc.scrapy.org/en/latest/topics/request-response.html.
These are my cookies on the site, but I am not sure what and How I should add them along with Request.

A: First of all do not be demanding, sometimes I get angry and won't answer your question.
To see which cookies are sent with your Request enable debugging with COOKIES_DEBUG = True.
Then you will notice that cookies are not sent even if Scrapy's middleware should send those cookies. I think this is because you yield a custom request and Scrapy won't be more clever than you and accepts your solution to send this request without cookies.
This means you need to access the cookies from the response and add the required ones (or all) to your Request.


text:
Q: Angular overload component's property with getter and setter with decorator How override a getter and a setter on object and add some logic but continue to call original methods?
import { Component, OnInit } from '@angular/core';

function defineDecorator() {
  return function (target: object, propertyKey: string) {
    console.log('decorate', target, propertyKey);
    const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
    const originalSet = descriptor && descriptor.set ? descriptor.set : null;
    const originalGet = descriptor && descriptor.get ? descriptor.get : null;

    Object.defineProperty(target, propertyKey, {
      get: function (): any {
        console.log('overload getter called');
        if (originalGet) {
          originalGet.call(this);
        }
        return 'test';
      },
      set: function (value: any) {
        console.log('overload setter called');
        if (originalSet) {
          originalSet.call(this, value);
        }
      },
      enumerable: true,
      configurable: true,
    });
  };
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  _foo: string;

  @defineDecorator()
  set foo(value: string) {
    console.log('original setter called');
    this._foo = value;
  }
  get foo() {
    console.log('original getter called');
    return this._foo;
  }

  ngOnInit(): void {
    this.foo = 'bar';
  }
}

demo online https://stackblitz.com/edit/angular-ivy-qj1p7a?file=src%2Fapp%2Fapp.component.ts


text:
Q: ISZ (compressed ISO format) viewer for Mac OS X Is there any utility available that mount or view ISZ files (the compressed ISO format used by Ultra ISO) in Mac OS X?

A: I have no experience with it, but AnyToISO claims to be able to convert an ISZ to ISO. From there you can mount or burn it normally.

A: If you're running Linux or OSX, this python script works great for me:
https://github.com/oserres/isz-tool/zipball/master
usuage
./oserres-isz-tool-1c8541e/isz-tool.py isz2iso try.isz
Extracting try.isz to try.iso -
Done

i was really surprised by the effectiveness of this compression:
-rw-r--r--   1 domdorn  staff   3,1G 10 Jan 18:06 try.iso
-rw-r--r--@  1 domdorn  staff   991M 10 Jan 18:04 try.isz


text:
Q: How to verify if a string.split() returns null I am reading data from a file:
Some Name;1|IN03PLF;IN02SDI;IN03MAP;IN02SDA;IN01ARC
Some Other Name;2|IN01ALG;IN01ANZ
Another Name;3|
Test Testson;4|IN03MAP;IN01ARC;IN01ALG

I use string.split() for every line I read from that file, like this:
String args[]         = line.split("\\|");
String candidatArgs[] = args[0].split(";");

if (args[1] != "" || args[1] != null) {

    String inscrieriString[] = args[1].split(";");

Thing is: when I reach Another Name;3| after .split("\\|") the second part (args[1]) should be empty, either null or ""  (I don't really know).
However I get an Array index out of bounds error on if (args[1] != "" || args[1] != null) (again, at: Another Name;3|)

A: You need to check the length of your args array.
String.split() returns an array of length 1 for your third line, so that args[1] is out of bounds.
You should also use String.isEmpty() instead of != "".
Most likely, you can even skip your additional checks - checking the array length should be sufficient:
if (args.length > 1) {
    String inscrieriString[] = args[1].split(";");
    ...
}

A: The args will only have one element in it.

if (args.length > 1) {
    String inscrieriString[] = args[1].split(";");
}

A: Check the length of args when splitting and only access the other index if the length allows it (if the args.length > 1).
In this case:
String line = "Another Name;3|"; //simplified for the example
line.split("\\|");

It will return this array:
{ "Another Name;3" }

A: try
String args[]         = line.split("\\|",2);
String candidatArgs[] = args[0].split(";");

if (args.length==2)
    String inscrieriString[] = args[1].split(";");

A: args[1] isn't empty or null. It is out of bounds in the array.
System.out.println("Another Name;3|".split("\\|").length);

You would need to check the length of the array before using it.

A: I think you can test the length of args and it should return 1 or 2. If it's 1 you know that there's no args[1].


text:
Q: Is it possible to display multi-page, multi-layer TIFF images using javascript in a webpage? We are thinking about a library which can get a TIFF image and display each page (frame) of TIFF file in a separate canvas element. Also some pages might have layers. We want to be able to show/hide layers at user's will.
It is not necessary to tell me the complete solution or library. Just tell me if it is possible to accomplish all these requirements by javascript or we need to get help of server-side programming?

A: Should be possible. I don't think browsers support the TIFF format natively, but a quick Google search turns up at least two TIFF parsers for JavaScript. From there on, you can display it in any way you like; tiff.js even has a multipage demo.


text:
Q: Processing large data in Mathematica I'm dealing with large input arrays with Mathematica and it looks like I can't process anything bigger than (or equal to) 1024*1024 and 81*81*81. Is that normal? Should I be able to do computations on such input data? If so, how?

A: I think that depends on what calculations you are performing.
For example, in a very modest laptop:
Clear["Global`*"];
k = 2000;
Timing[a = Table[i j + i - j, {i, k}, {j, k}];
 MatrixPlot@a]

Takes 20 seconds.
Matrix multiplying up to 1000x1000:
f[n_] := Table[RandomInteger[{1, n}], {n}, {n}];
ListLinePlot[
 Table[{n, First@AbsoluteTiming@(#.#) &@f[n]}, {n, 100, 1000, 100}]]

So, it depends heavily on what you are trying to calculate.


text:
Q: Swift: Programmatic Autolayout broken by UNavigationController I have inherited a UIKit app where my predecessor has written all the interface code by hand. I have a view controller, a simple login screen that works just fine, but when I add it to a UINavigationController it is oddly stretched. This doesn't make a lot of sense to me.
I feel like I must be missing some simple flag, or what do I need to do to make the Navcontroller play nice with this programmatic autolayout (which is hopefully my last ever)
// this a view controller extension
func apply(constraints: [NSLayoutConstraint]) {
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(constraints)
    }

There's my handy dandy, seemingly sane utility for applying constraints. As an example, the nice little oval thing making my password textfield looks nice has these constraints set up.
// these constraints are being setup in the view controller
        emailCapsuleView.apply(constraints: [
            emailCapsuleView.topAnchor.constraint(equalTo: subBigTitle.bottomAnchor, constant: 24.0),
            emailCapsuleView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            emailCapsuleView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
            emailCapsuleView.heightAnchor.constraint(equalToConstant: Dimensions.inputFieldHeight)
        ])

Outside of a UINavigationController everything is fine,

but in a UINavigationController everythhing is super wide and broken (simulator shot)

The width is not the problem here - if I use a constant for the width, my subview is still off center despite having it's centerX sets to the view controller's view's center X.

A: Configure your navigation controller and after that try like this:
set your objects:
let emailTextfield: UITextField = {
    let tf = UITextField()
    tf.backgroundColor = .white
    tf.layer.borderWidth = 1
    tf.layer.borderColor = UIColor.lightGray.cgColor
    tf.setPadding(left: 10, right: 10)// use my extension below
    tf.attributedPlaceholder = NSAttributedString(string: "Email address", attributes: [.foregroundColor: UIColor.lightGray])
    tf.layer.cornerRadius = 14
    tf.clipsToBounds = true
    tf.translatesAutoresizingMaskIntoConstraints = false

    return tf
}()

let passTextfield: UITextField = {
    let tf = UITextField()
    tf.backgroundColor = .white
    tf.layer.borderWidth = 1
    tf.layer.borderColor = UIColor.lightGray.cgColor
    tf.setPadding(left: 10, right: 10)// use my extension below
    tf.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [.foregroundColor: UIColor.lightGray])
    tf.layer.cornerRadius = 14
    tf.clipsToBounds = true
    tf.translatesAutoresizingMaskIntoConstraints = false

    return tf
}()

let loginButton: UIButton = {
    let b = UIButton(type: .system)
    b.backgroundColor = .black
    b.setTitle("Save Image", for: .normal)
    b.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
    b.setTitleColor(.white, for: .normal)
    b.layer.cornerRadius = 14
    b.clipsToBounds = true
    b.translatesAutoresizingMaskIntoConstraints = false

    return b
}()

let subBigTitle: UILabel = {
    let l = UILabel()
    l.text = "Your Big Title"
    l.font = .systemFont(ofSize: 30, weight: .regular)
    l.textColor = .black
    l.textAlignment = .center
    l.translatesAutoresizingMaskIntoConstraints = false
    return l
}()

Now in viewDidLoad set stackView, bigTitle label and constraints:
view.addSubview(subBigTitle)
    subBigTitle.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    subBigTitle.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    subBigTitle.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
    subBigTitle.heightAnchor.constraint(equalToConstant: 60).isActive = true

    let stackView = UIStackView(arrangedSubviews: [emailTextfield, passTextfield, loginButton])
    stackView.axis = .vertical
    stackView.distribution = .fillEqually
    stackView.spacing = 10
    stackView.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(stackView)
    stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8).isActive = true
    stackView.heightAnchor.constraint(equalToConstant: 170).isActive = true
    stackView.topAnchor.constraint(equalTo: subBigTitle.bottomAnchor, constant: 24).isActive = true
    stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

to add text padding to your textfield use my extension:
extension UITextField {

func setPadding(left: CGFloat, right: CGFloat){

 let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: left, height: self.frame.size.height))
 self.leftView = paddingView
 self.leftViewMode = .always

 let paddingViewRight = UIView(frame: CGRect(x: 0, y: 0, width: right, height: self.frame.size.height))
 self.rightView = paddingViewRight
 self.rightViewMode = .always
 }
}

and this is the result:


text:
Q: how do I get my logger messages to go to a file when testing a controller with rspec? I'm using Rspec2 with Watchr to test a post to a controller, like so:
...
 post :add_item, :add_item=> { "price" => price.to_s, "product_line" => line }
 # puts " response: "  + response.body
 response.should be_success
...

I am getting a response and it looks fine, but for some reason this one isn't giving me a "success" response. I'm trying to figure out why. To that end, it would be very helpful if I could see my logs. I can see that the logs are getting initialized and are pointing to the right place, because when my env starts up I have this:
Loading environment: test
Logger: #<ActiveSupport::BufferedLogger:0xa201b24 @level=0, @buffer={},
  @auto_flushing=1, @guard=#<Mutex:0xa201728>,
  @log=#<File:/mnt/hgfs/the_app/log/test.log>, @namespace="">
Database: the_app_test

So that looks normal -- All my mongodb calls are getting logged, but RSpec seems to be redirecting the logger calls. Here's a sample that's not showing in the logs:
logger.debug "Params #{params.inspect}" (this line is right after the def in the controller)
I've checked my environments rb files and don't see anything that would explain this. Is there a way to get messages that are generated by controllers by rspec to go to their own log file? Is Rspec redirecting my logging output?
I read this blog post, but it's pretty outdated so I'm not sure it will help. Ever an issue with Rails.

A: The quick but ugly way: put logger = Rails::logger at the top of your controller method. Not sure if this will break normal logging yet.
and to put
config.before(:suite) do
Rails::logger  =
    ActiveSupport::BufferedLogger.new(File.join(Rails.root,
    "log", "rspec_env_#{Rails.env}.log"),
    ActiveSupport::BufferedLogger::Severity::DEBUG)

in my spec_helper.rb. Those two will result in the rspec logger calls going to "rspec_env_test.log" etc.
Anyone got a better way?


text:
Q: Subset data frame by DateTime column? I am working with a data set with a measuring interval of 15 mins. The data is stored with a DateTime column with the format yyyy/mm/dd hh/mm/ (POSIXct). I would like to subset my data using the DateTime column. So for example I would like to make a subset that ranges from 2019-07-25 00:00 to 2019-07-25 23:45.
Here is an example of my data
 DateTime                     S4_SM1_30 S4_SM2_30 S4_SM3_30 S4_SM4_30 S4_SM1_60 S4_SM2_60 S4_SM3_60 S4_SM1_90 S4_SM2_90
1   2019-05-01 00:00:00       8.5       7.8      10.3       6.6      24.1      28.5      26.5      11.4        17
2   2019-05-01 00:15:00       8.6       7.8      10.4       6.6      24.3      28.6      26.5      11.4        17
3   2019-05-01 00:30:00       8.6       7.8      10.3       6.6      24.3      28.5      26.5      11.3        17
4   2019-05-01 00:45:00       8.7       7.8      10.3       6.6      24.3      28.5      26.5      11.3        17
5   2019-05-01 01:00:00       8.6       7.8      10.4       6.6      24.2      28.5      26.5      11.3        17
6   2019-05-01 01:15:00       8.6       7.8      10.3       6.6      24.2      28.5      26.6      11.4        17
7   2019-05-01 01:30:00       8.5       7.8      10.4       6.6      24.3      28.5      26.5      11.3        17
8   2019-05-01 01:45:00       8.6       7.8      10.4       6.6      24.3      28.5      26.5      11.4        17

I`ve tried to use the following code to make the subset.
df <- df %>%
  filter(DateTime >= as.POSIXct('2019-07-25 01:45') & DateTime <= as.POSIXct('2019-07-25 23:45'))

The code seems to kind of work, but the result I get is flawed. The subset starts on the 2019-07-24 22:00 and ends on the 2019-07-25 21:45. So it basically starts and ends 2 hours to early. Here is an example.
DateTime S4_SM1_30 S4_SM2_30 S4_SM3_30 S4_SM4_30 S4_SM1_60 S4_SM2_60 S4_SM3_60 S4_SM1_90 S4_SM2_90
1  2019-07-24 22:00:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
2  2019-07-24 22:15:00         7       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
3  2019-07-24 22:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
4  2019-07-24 22:45:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
5  2019-07-24 23:00:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.7
6  2019-07-24 23:15:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
7  2019-07-24 23:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
8  2019-07-24 23:45:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.1       9.7
9  2019-07-25 00:00:00         7       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
10 2019-07-25 00:15:00       6.9       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
11 2019-07-25 00:30:00         7       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
12 2019-07-25 00:45:00         7       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
13 2019-07-25 01:00:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
14 2019-07-25 01:15:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.3       9.6
15 2019-07-25 01:30:00       6.9       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
16 2019-07-25 01:45:00         7       5.9       5.9       5.3      17.1      18.8      16.9       7.2       9.6
17 2019-07-25 02:00:00         7       5.9         6       5.4        17      18.8      16.9       7.2       9.6
18 2019-07-25 02:15:00       6.9       5.9         6       5.3        17      18.8      16.9       7.2       9.6
19 2019-07-25 02:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
20 2019-07-25 02:45:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
21 2019-07-25 03:00:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
22 2019-07-25 03:15:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
23 2019-07-25 03:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
24 2019-07-25 03:45:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
25 2019-07-25 04:00:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
26 2019-07-25 04:15:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
27 2019-07-25 04:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
28 2019-07-25 04:45:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
29 2019-07-25 05:00:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
30 2019-07-25 05:15:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
31 2019-07-25 05:30:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
32 2019-07-25 05:45:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
33 2019-07-25 06:00:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
34 2019-07-25 06:15:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
35 2019-07-25 06:30:00       6.9       5.9         6       5.3        17      18.8        17       7.2       9.6
36 2019-07-25 06:45:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
37 2019-07-25 07:00:00         7       5.9         6       5.3        17      18.8        17       7.2       9.6
38 2019-07-25 07:15:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
39 2019-07-25 07:30:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
40 2019-07-25 07:45:00         7       5.9       5.9       5.3        17      18.8        17       7.2       9.6
41 2019-07-25 08:00:00         7       5.9         6       5.3        17      18.8      16.9       7.2       9.6
42 2019-07-25 08:15:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
43 2019-07-25 08:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
44 2019-07-25 08:45:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
45 2019-07-25 09:00:00       6.9       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
46 2019-07-25 09:15:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
47 2019-07-25 09:30:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
48 2019-07-25 09:45:00         7       5.9       5.9       5.3        17      18.8      16.9       7.2       9.6
49 2019-07-25 10:00:00         7       5.9       5.9       5.3        17      18.8      16.8       7.2       9.6
50 2019-07-25 10:15:00         7       5.9       5.9       5.3        17      18.8      16.8       7.2       9.6
51 2019-07-25 10:30:00       6.9       5.9       5.9       5.3      16.9      18.8      16.8       7.2       9.6
52 2019-07-25 10:45:00       6.9       5.9       5.9       5.3      16.9      18.8      16.8       7.3       9.6
53 2019-07-25 11:00:00       6.9       5.9       5.9       5.3      16.9      18.8      16.8       7.2       9.6
54 2019-07-25 11:15:00       6.9       5.9       5.9       5.3      16.9      18.8      16.8       7.2       9.6
55 2019-07-25 11:30:00       6.9       5.9       5.9       5.3        17      18.7      16.8       7.2       9.6
56 2019-07-25 11:45:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.2       9.6
57 2019-07-25 12:00:00       6.9       5.9       5.9       5.3        17      18.8      16.8       7.2       9.6
58 2019-07-25 12:15:00       6.9       5.9       5.9       5.3        17      18.7      16.8       7.2       9.6
59 2019-07-25 12:30:00       6.9       5.9       5.9       5.3        17      18.7      16.8       7.2       9.6
60 2019-07-25 12:45:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.3       9.6
61 2019-07-25 13:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.3       9.6
62 2019-07-25 13:15:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
63 2019-07-25 13:30:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.2       9.6
64 2019-07-25 13:45:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.2       9.6
65 2019-07-25 14:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.8       7.2       9.6
66 2019-07-25 14:15:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
67 2019-07-25 14:30:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
68 2019-07-25 14:45:00       6.9       5.8       5.9       5.3      16.9      18.7      16.7       7.2       9.6
69 2019-07-25 15:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
70 2019-07-25 15:15:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
71 2019-07-25 15:30:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.1       9.6
72 2019-07-25 15:45:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
73 2019-07-25 16:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
74 2019-07-25 16:15:00       6.9       5.8       5.9       5.3      16.8      18.7      16.7       7.2       9.6
75 2019-07-25 16:30:00       6.9       5.9       5.8       5.3      16.9      18.7      16.7       7.2       9.6
76 2019-07-25 16:45:00       6.9       5.9       5.9       5.3      16.8      18.7      16.7       7.2       9.6
77 2019-07-25 17:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
78 2019-07-25 17:15:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
79 2019-07-25 17:30:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
80 2019-07-25 17:45:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
81 2019-07-25 18:00:00       6.9       5.9       5.9       5.3      16.9      18.7      16.7       7.2       9.6
82 2019-07-25 18:15:00       6.9       5.9       5.8       5.3      16.9      18.6      16.7       7.2       9.6
83 2019-07-25 18:30:00       6.9       5.8       5.9       5.3      16.9      18.6      16.7       7.2       9.6
84 2019-07-25 18:45:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
85 2019-07-25 19:00:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
86 2019-07-25 19:15:00         7       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
87 2019-07-25 19:30:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
88 2019-07-25 19:45:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
89 2019-07-25 20:00:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
90 2019-07-25 20:15:00         7       5.9       5.9       5.3      16.8      18.6      16.8       7.2       9.6
91 2019-07-25 20:30:00       6.9       5.9       5.9       5.3      16.9      18.6      16.8       7.2       9.6
92 2019-07-25 20:45:00       6.9       5.9       5.9       5.3      16.9      18.6      16.7       7.2       9.6
93 2019-07-25 21:00:00       6.9       5.8       5.9       5.3      16.9      18.6      16.8       7.1       9.5
94 2019-07-25 21:15:00       6.9       5.9       5.8       5.3      16.8      18.6      16.8       7.2       9.6
95 2019-07-25 21:30:00       6.9       5.9       5.9       5.3      16.9      18.6      16.8       7.2       9.5
96 2019-07-25 21:45:00       6.9       5.9       5.9       5.3      16.9      18.6      16.8       7.2       9.6

I would be thankful for any help!

A: By default as.POSIXct takes the local timezone, you might want to add specific timezone to it.
library(dplyr)

df %>% filter(DateTime >= as.POSIXct('2019-07-25 01:45', tz = 'GMT') &
              DateTime <= as.POSIXct('2019-07-25 23:45', tz = 'GMT'))

Moreover, if you need GMT/UTC timezone you can use lubridate::ymd_hms which has UTC as default timezone.


text:
Q: Bootstrap TokenInput Cancel all previous requests Could someone please let me know how to cancel previous ajax request when typing in the token? I am facing problem with multiple ajax requests and my server is hanging due to that.
            $('#Searchinput').tokenInput(getMyRestServer, {
            theme: "facebook",
            queryParam : "param",
            preventDuplicates: true,
            tokenDelimiter: "|",
            minChars: 5,
            hintText: "Type your search criteria here",
            noResultsText: "No Results found. Please refine your search...",
            searchingText: "Fetching results ...please wait...",
            allowCustomEntry: true});


text:
Q: Why are my spaces not trimmed This seems obvious and straightforward, but it's not working. I'm working from in Excel VBA. I get the open Word application and extract text from a bookmarked spot within a table in Word. Then the trouble starts. The resulting string is 5 chr(32) spaces. But whatever I try, I can't get rid of the spaces. Why are the spaces not being trimmed or replaced?
Dim Wd As Word.Application
Set Wd = GetObject(, "Word.Application")
Dim doc As Word.Document
'Dim r As Word.Range
'Dim p As Word.Paragraph
Dim tb As Word.Table

Set doc = Wd.ActiveDocument
Set tb = doc.Tables(1)
'tb.Select

Dim Place As String
Place = Trim(doc.Bookmarks("County").Range.Text)

'outputs length 5
Debug.Print Len(Place)

'this outputs 32 5 times so I know we have chr(32) and not something else
Dim i As Integer
For i = 1 To Len(Place)
    Debug.Print Asc(Mid(Place, i, 1))
Next

'try trim
Place = Trim(Place)
Debug.Print Len(Place)
'still 5 spaces

'try replace
Dim s As String
s = VBA.Replace(Place, Chr(32), "")
Debug.Print Len(Place)
'still 5 spaces

What is happening with my code?

A: Probably a unicode space, consider U2000 EN QUAD Whitespace:
x="W" & chrw(&h2000) & "W"
?x
W W
?asc(mid(x,2,1))
 32    <= normalized
?ascw(mid(x,2,1))
 8192  <= true character

So examine the char with ascw and replace with chrw


text:
Q: android geofencing java.lang.IllegalStateException: GoogleApiClient is not connected yet I am using geofencing in my app. Whenever I try to add geofences, I get the following error.
IllegalStateException: GoogleApiClient is not connected yet

In AppCompatActivity onCreate method I define the client
/* Create a new google api client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();

and in my onStart method I connect to it ensuring that it is not null
/* Connect to the API client */
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}

but still it gives that error.
My AppCompatActivity implements OnMapReadyCallback and ResultCallback interfaces among others
for which I have an overridden method
@Override
public void onMapReady(GoogleMap googleMap) {}

The onMapReady method contains this lines of code
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
        getGeofencingRequest(),
        getGeofencePendingIntent()
).setResultCallback(MapsActivity.this);

I have defined getGeofencingRequest and getGeofencingPendingIntent private methods and overridden the onResult method in ResultCallback.
I have spent hours and hours on this error and can't seem to get headway. The app executes normally until the AppCompatActivity is started. onCreate happens normally, onStart happens normally as well.
I think there are two possibilities for this error:

*

*The onMapReady method is being called before onStart (unlikely)

*The onStop method disconnects the client before it is available to the onMapReady method
Regardless some resolution to the error will be appreciated.
Link to full gist is below:
https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac

A: I found the answer to my own question.
Apparently, the google API client connection is separate to the Google Map connection. API client is specifically for location services.
As such I needed to set up geofencing after the API connection has been established.
So I moved all of my geofencing code inside of onConnected as well.
@Override
public void onConnected(Bundle savedInstanceState) { }

That solved the issue.
Take a look at the updated gist:
https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac


text:
Q: np.mean(phDF.ram) raise eror phoneinfo=np.array([['galaxy s8','android',64,4,140,'samsung',6],['lumia','windows',32,3,150,'microsoft',6],
                    ['xperia l1','android',16,2,180,'sony',5],['iphone7','ios',128,2,138,'apple',4],
                    ['u ultra','android',64,4,170,'htc',5],['galaxy s5','android',16,2,145,'samsung',5],
                    ['iphone 5s','ios',32,1,112,'apple',4],['moto g5','android',16,3,144.7,'motorola',5],
                    ['pixel','android',128,4,143,'google',5]])

phDF=pd.DataFrame(phoneinfo,index=[1,2,3,4,5,6,7,8,9],columns=['name','os','capacity','ram','weight','company','inch'])

np.median(phDF.ram)

Error message:
TypeError: ufunc 'true_divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

A: As the dtype of your ram column is in object type, np.median can't work on it.
phDF.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 9 entries, 1 to 9
Data columns (total 7 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   name      9 non-null      object
 1   os        9 non-null      object
 2   capacity  9 non-null      object
 3   ram       9 non-null      object
 4   weight    9 non-null      object
 5   company   9 non-null      object
 6   inch      9 non-null      object
dtypes: object(7)
memory usage: 576.0+ bytes

You can do it by either of the following ways:
Try Series.median() instead:
phDF.ram.median()

Or convert the dtype to int before using np.median:
np.median(phDF.ram.astype(int))

Or use pd.to_numeric() to convert the column to numeric first:
np.median(pd.to_numeric(phDF.ram))

Result:
3.0


text:
Q: how-to create an insecure jupyter server Jupyter only allows access from localhost unless I do a bunch of extra security stuff.  I am running my server so that it is only accessible on a local network where anyone with access is equal in trustworthiness to localhost.  How do I set up a jupyter notebook server with no extra security features?

A: Based on your question, I expect you want this configuration (in ~/.jupyter/jupyter_notebook_config.py):
c.NotebookApp.ip = '0.0.0.0' # listen on all IPs
c.NotebookApp.token = ''     # disable authentication

There are a few security features in Jupyter (as of 4.3.1). I'll go over how to disable each one, and whether/when it makes sense to disable it:

*

*It listens only on localhost. This can be changed to all public IP addresses:
c.NotebookApp.ip = '0.0.0.0'

Listening on public IPs should generally come with enabling HTTPS and/or password or token authentication (docs). If it's all internal on a trusted network where nothing bad ever happens, you can proceed to disable other security features:

*Token authentication is enabled by default. To disable it:
c.NotebookApp.token = ''

Disabling authentication means that anyone with access to the host can run code. It seems like this is what you want. You can also enable a password:
In [1]: from notebook.auth import passwd
In [2]: passwd()
Enter password:
Verify password:
Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'

You can store this in c.NotebookApp.password.
You can also store this password in (~/.jupyter/jupyter_notebook_config.json):
{
    "NotebookApp": {
        "password": "sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed"
    }
}

*Jupyter also has CORS protections, to avoid other websites from being able to access this server. This means that when a user on your network visits example.com, javascript on that page cannot execute code on your notebook server. It sounds like you don't want to touch this, but if you are running a service that should be able to access the notebook server, you can add it to:
c.NotebookApp.allow_origin = 'https://your.other.host'

*Finally, Jupyter 4.3.1 introduces an xsrf token, which is part of dealing with the same category of cross-site execution above. You don't need to touch this if users are only accessing the server directly, rather than through javascript on additional websites.
c.NotebookApp.disable_check_xsrf = True

A completely insecure notebook server, which is to say one where any website can run code on it, as long as a browser can connect to its host (this would include localhost or LAN if the browser is running from inside the LAN):
c.NotebookApp.ip = '0.0.0.0' # listen on all IPs
c.NotebookApp.token = ''     # disable authentication
c.NotebookApp.allow_origin = '*' # allow access from anywhere
c.NotebookApp.disable_check_xsrf = True # allow cross-site requests

This might be desirable if you are aiming to make compute resources free for the world to use however they want via the notebook API.


text:
Q: Is Interrupted Time Series analysis an appropriate approach for my problem? A project I'm working on could potentially use an interrupted time series analysis, which is something I've never done before. Could anyone recommend a good free resource on how to do them, potential pitfalls and how to avoid them etc? I'm trying to figure out if what I have is even appropriate for this kind of analysis, and if not, what else I might use.
I'm looking at a natural experiment, where a particular well-covered event happened smack dab in the middle of the data collection period of a survey on a related topic. I'm trying to see if the event had an impact on people's expressed opinions. The survey collected some 3000 responses prior to the event, and another 1000 afterwards, and the order they were collected was random. When I just do some simple analysis, I see what looks like a fairly small difference in averages in the before an after group, but I'm not sure how to statistically test it for significance.
If you can also recommend specific tools for R, that would also be great, but for now I'm just trying to figure out if this is the right statistical analysis for my question.
Thanks!


text:
Q: How to handle authentication on Prometheus metrics endpoint for an application on GKE? I have a set of microservices running in a GKE cluster. They all have a /prometheus endpoint which exposes metrics for Managed Prometheus collectors to collect.
Everything works fine when the endpoint is exposed and I follow the instructions here: https://cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed - the metrics get collected and are visible under Cloud Monitoring.
However, I would like to protect this endpoint with some sort of authorization on the app level so that not anyone can access this endpoint for obvious reasons.
How can I do this? I don't see any option to give the PodMonitoring scraper some token or key to use when making http requests. What is the recommended approach?

A: Accessing and analyzing ingested data can be done through the Prometheus UI. Based on the metrics scope associated with your project, this UI executes PromQL queries against all of the data in your Google Cloud project.
In addition, the user interface serves as an authentication proxy for accessing ingested data. This feature can be used for client tools that don't support OAuth2, including Grafana. You must also deploy the Prometheus UI if you intend to use Grafana to visualize data from Managed Service for Prometheus.
To deploy prometheus UI you can follow this documentation.
To Authenticate the UI you can follow this documentation.


text:
Q: Is there any difference between "already" and "now" when used with the present perfect? Could you tell me if there is any difference between already and now when used with the present perfect? For example:

I have already had five tablets, so I know a thing or two about them.
I have had five tablets now, so I know a thing or two about them.

A: There is a subtle difference in connotations.
The first sentence suggests continuing, and the second sentence suggests competition.
"Already" is a tricky one to parse. To borrow Kate's sentence "I've been to Spain five times already", it means very different things when you just told me you're going to Spain or Italy.

A: I think already carries the implication that you expect to have the experience again, or that having had it is a reason for not needing to have it again.

The pharmacy supplied me with twenty tablets, and I've already taken five.

I had a lovely holiday in Spain. I've been there five times now.
I think I shall go to Italy next year. I've been to Spain five times already.


text:
Q: How to make element clicked before it hiden from parent on unfocus I trying to make an simple search field element, i created a plain javascript code down below.
The filter and the focus are as expected with the code, but when i clicked the grandchild element, it doesn't nothing, like it even not even being clicked. The element is still right there, it's seem the unfocus on the <input> element happend first than the listener on the grandchild. Is there a way, how to make the click happend first, or to delay when unfocus?

String.prototype.isContain = function(trg) {
  return (getLength(this.toLowerCase().split(trg.toLowerCase())) > 1);
}

let fieldinput = document.querySelectorAll(".child-1")[0];
fieldinput.addEventListener("keyup", function() {
  let grandchild = document.querySelectorAll(".grandchild");
  for (let x in grandchild) {
    if (grandchild.hasOwnProperty(x)) {
      if (grandchild.innerHTML.isContain(fieldinput.value)) {
        grandchild[x].style.display = "block";
      } else {
        grandchild[x].style.display = "none";
      }
      grandchild[x].addEventListener("click", function() {
        console.log(grandchild[x].innerHTML); // this never executed
      });
    }
  }
});
.parent {
  position: relative;
}

.parent .child-1 {
  padding: 10px;
}

.parent .child-2 {
  position: absolute;
  max-height: 0px;
  top: 100%;
}

.parent .child-1:focus+.child-2 {
  max-height: 500px;
}

  <input class="child-1" type="text" placeholder="Focus Here">

Option 1

Option 2

Option 3

A: Several issues

*

*missing code

*unnecessary use of querySelectorAll when you only want one element

*nested event listener creation - You currently add an event listener to all grandchildren for every key you press

*Non-Dry

String.prototype.isContain = function(trg) {
  return this.toLowerCase().split(trg.toLowerCase()).length > 1;
}

document.querySelector(".child-1").addEventListener("input", function() {
  document.querySelectorAll(".grandchild")
    .forEach(grandChild =>  grandChild.hidden = !grandChild.innerHTML.isContain(this.value))
});
document.querySelector(".child-2").addEventListener("click", function(e) {
  const tgt = e.target.closest(".grandchild");
  if (tgt) console.log(tgt.textContent)
});
.parent {
  position: relative;
}

.parent .child-1 {
  padding: 10px;
}

.parent .child-2 {
  position: absolute;
  max-height: 0px;
  top: 100%;
}

.parent .child-1:focus+.child-2 {
  max-height: 500px;
}

.hide { display: none }

  <input class="child-1" type="text" placeholder="Focus Here">

Option 1

Option 2

Option 3


text:
Q: Symfony2/Twig - Outputting an array of data I was wondering the best way to do something.  My controller makes a call to a service's function.  This function obtains some DOMDocument stuff and I didnt want to pass this whole response to twig.  So what I do is this
public function terminalService($terminal_command)
{
    $dom = new \DOMDocument('1.0', 'UTF-8');
    $responseData = $this->commandsService->executeSingleCommand($terminal_command);
    $dom->loadXML($responseData);

    $elements = $dom->getElementsByTagNameNS('http://www.test.com/ter_0', 'Text');

    $elNum = 0;
    $flightInfo = array();

    while ( $elNum < $elements->length ) {
        $flightInfo[] = $elements->item($elNum)->nodeValue;
        ++$elNum;
    }

    return $flightInfo;
}

So that takes the DOMDocument, finds all the elements which have the Text namespace and places them into an array element.  My controller then receives this array and then passes it to the view
$commandData = $apiService->terminalService($terminal_command);

return $this->render('NickAlertBundle:Page:terminal.html.twig', array(
     'data' => $commandData,
));

How can I get each element of the array displayed on a new line?  In my view I am currently doing

    {% if data is defined %}
        {% for d in data %}
            {{ d|nl2br }}
        {% endfor %}
    {% endif %}

All that does however is display everything in one long string.  funny enough, if I dump data it displays it how I want (but I obviously cant do this in production).  So how can I display each array element on its own line?
Update
A dump displays the data how I want it displays e.g.
6 => "3*A$NZ9835 C4 D4 J4 Z4 B7 H7 M7 Y7 LHRLAX 1035 1350   *  777 0E"
7 => "           Q7 T7 V7 W7 G7 K7 L7 S7 "

So as you can see line 7 is displayed with a lot of spaces in order to format the output correctly.  If I simply place a break at the end of my output, it displays like so
7 #AY4014 F9 A9 P9 J9 C9 D9 I9 Y9 LHRLAX 1215 1530 * 77W 0E
B9 H9 K9 M9 L9 V9 S9 N9 Q9 O9 G9

Is there any way to retain the spaces or duplicate what a dump does?
Thanks

A: Since you have most of the logic set, I would change the for loop to this:

    {% if data is defined %}
        {% for d in data %}

{{ d }}

        {% endfor %}
    {% endif %}


text:
Q: Why does the ping from inside docker is faster than the main OS? I tried to ping google from both inside the container running Ubuntu and my main OS. The result is as follow:

Why is the ping from my docker faster than my main OS?

A: This is a known bug - ping inside container does not ping actual host ip but seems to ping localhost.
As of September 2016, it's unfixed.


text:
Q: SQL: How do you count the number of unique records? I'm new to SQL and sorry if this q has been asked before - I couldn't phrase it properly.
Say I have a table that looks like this:
Name    Call ID
Sally   1
Sally   2
Sally   3
Mike    4
Mike    5
Bob     6
Bob     7

I want to create a new table that looks like this:
Name    No. of calls
Sally   3
Mike    2
Bob     2

Attempt
I assume I would do something like:
SELECT
Name,
COUNT(distinct Name) AS No. of Calls
FROM Table

Thanks.

A: You just need to group them and that's all.
SELECT
     Name
     COUNT(*) AS [No. of Calls]
FROM
     Table
GROUP BY
     Name

A: You're looking for GROUP BY:
SELECT Name, COUNT(*) AS 'No. of Calls'
FROM Table
GROUP BY NAME
ORDER BY COUNT(*) DESC