text:
Q: Flutter resize TextField by dragging Is there any way to create something like these dots, which can help in expanding TextField.

A: Screenshot:

Create a widget.
class ExpandableTextField extends StatefulWidget {
  final double height;
  final double maxHeight;
  final double dividerHeight;
  final double dividerSpace;
  final Widget child;

  const ExpandableTextField({
    Key key,
    @required this.child,
    this.height = 44,
    this.maxHeight = 300,
    this.dividerHeight = 40,
    this.dividerSpace = 2,
  }) : super(key: key);

  @override
  _ExpandableTextFieldState createState() => _ExpandableTextFieldState();
}

class _ExpandableTextFieldState extends State<ExpandableTextField> {
  double _height, _maxHeight, _dividerHeight, _dividerSpace;

  @override
  void initState() {
    super.initState();
    _height = widget.height;
    _maxHeight = widget.maxHeight;
    _dividerHeight = widget.dividerHeight;
    _dividerSpace = widget.dividerSpace;
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: _maxHeight,
      child: Column(
        children: <Widget>[
          SizedBox(
            height: _height,
            child: widget.child,
          ),
          SizedBox(height: _dividerSpace),
          Container(
            height: _dividerHeight,
            width: 60,
            child: GestureDetector(
              child: FittedBox(child: Text("----")),
              onPanUpdate: (details) {
                setState(() {
                  _height += details.delta.dy;

                  // prevent overflow if height is more/less than available space
                  var maxLimit = _maxHeight - _dividerHeight - _dividerSpace;
                  var minLimit = 44.0;

                  if (_height > maxLimit)
                    _height = maxLimit;
                  else if (_height < minLimit)
                    _height = minLimit;
                });
              },
            ),
          )
        ],
      ),
    );
  }
}

Use it like:
ExpandableTextField(
  child: TextField(
    decoration: InputDecoration(hintText: "Enter a message"),
    maxLines: 100, // give any number, but make sure it is not small
  ),
)


text:
Q: Integers mod $p$ "together" algebraically closed Let $f(x)$ be a nonconstant polynomial over $\mathbb Z$.
Must $f$ have a zero in $\mathbb F_p$ for some prime number $p$?
More generally, let $f_1,\dots,f_k$ be such polynomials, must there exist a $p$ such that each $f_i$ has a zero in $\mathbb F_p$?

A: Let $d$ be the degree of $f$. There are at most $2d$ integers $m$ such that $|f(m)|=1$. Pick any other integer $n$ and then an arbitrary prime factor $p$ of $f(n)$.

A: Easy answer to the first question: for $n \gg 0$, we have $f(n) > 1$ or $f(n) < -1$. Hence $f(n)$ is divisible by some prime number $p$, so $n$ is a root mod $p$.

A: The answer to the first question is positive. We may assume WLOG that $f$ is irreducible.
The Frobenius Density Theorem states that density of primes $p$ such that $f \mod p$ has a given decomposition (i.e. factors into irred. polynomials of prescribed degrees $n_1,\cdots,n_r$) is
$$\frac{\# \{ \sigma \in \text{Gal}(f) \mid \sigma \text{ has cycle structure }n_1,\cdots, n_r \} }{|\text{Gal}(f)|},$$
where $\text{Gal}(f)$ is the Galois group of $f$. See the discussion in this introductory paper by Sury.
By choosing the decomposition type of linear factors ($n_i = 1$), we see that for infinitely many primes $p$ (their density is $1$ over the size of the Galois group) we have that $f \mod p$ splits into linear factors (and in particular has zeroes). This is because the identity element of the Galois group of $f$ have cycle structure with $n_i=1$.
Remark: If you solely want the existence of infinitely many such primes (and not their density), The Frobenius density theorem may be avoided, see this discussion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting a .txt with data on multiple lines to a .csv I'm trying to turn data from a .txt file into a .csv file using Python. My .txt file is currently formatted kind of like this:
www.thing.com
Thing
2010
linkedin.com/company/thing
www.hello.com
Hello
1999
linkedin.com/company/hello
...

I want a program that will read through the 4 lines about 'Thing', and make that into a row. Then, it will read the 4 lines about 'Hello', and make that into a row, with each item being in the same column as the row about 'Thing'.
"www.thing.com,Thing,2010,linkedin.com/company/thing"
"www.hello.com,Hello,1999,linkedin.com/company/hello"
...

Here's what I have so far (which is not a lot):
import csv

text_file = open("document.txt", "r")

with open('output.csv', 'wb') as mycsv:
    filewriter = csv.writer(mycsv)

    mycsv.writerow(["company", "name", "date", "linkedin"])

    for line in text_file:
        URL = line
        line = next(text_file)
        name = line
        line = next(text_file)
        date = line
        line = next(text_file)
        LinkedIn = line
        line = next(text_file)
        mycsv.writerow(URL, name, date, LinkedIn)

Most I've looked up so far already has the .txt document formatted with each row in only one line, but my .txt has one row of data in multiple lines.
How would I go about solving this?

A: Here is another way to solve your issue:
def group_data(table, n=4):
    # Group your table's data by n elements
    yield from [table[k: k + n] for k in range(0, len(table), n)]

def write_csv(file_name, data):
    with open(file_name, 'a') as f:
        # Loop over your grouped data
        for elm in data:
            # Write the grouped elemenets into a file
            f.write(','.join(k for k in elm) + '\n')

a = '''www.thing.com
Thing
2010
linkedin.com/company/thing
www.hello.com
Hello
1999
linkedin.com/company/hello'''

data = [elm for elm in a.split('\n')]
grouped = group_data(data)
write_csv('csv_file.csv', grouped)

Output:
www.thing.com,Thing,2010,linkedin.com/company/thing
www.hello.com,Hello,1999,linkedin.com/company/hello

NB: If your data cannot be grouped by a fixed number, then you should think about a new algorithm to have your desired output. Or, you can see if there is a repeated pattern you can use to make the grouping happen. Otherwise, this current code will work with your current text snippet.

A: You can group the input file by 4 lines by zipping the input file iterator for 4 times:
from itertools import repeat
csv.writer(mycsv).writerows([[i.rstrip() for i in r] for r in zip(*repeat(text_file, 4))])


text:
Q: Перемешивание массива в PHP Как перемешать массив случайным образом. Чтобы с каждым разом вызова скрипта массив был разным?
A: В этом Вам поможет прекрасная функция shuffle(), мы все знаем насколько она хороша, её использование вызывает фантастическое удовольствие.
A: Сортировать большой массив долго, если ключи последовательно - нужно сгенерировать случайные цифры в диапазоне ключей и выдать эти элементы.


text:
Q: Can't initialise a class in ASP.NET Core? So I'm working on an ASP.net project and ive created a few methods for saving, editing and reading text files from within in my project. As part of this I wanted to use the WebRootPath method from IHostingEnvironment to save the root path of the website as a variable and not have to hardcode that into my application. Ive had a look around and the general consensus for how to do this seems to be to create a constructor as below
private readonly IHostingEnvironment HostingEnvironment;

        public Files (IHostingEnvironment _hostingEnvironment)
        {
            HostingEnvironment = _hostingEnvironment;
        }

This works as far as it allows me to access the root path within the class through the HostingEnvironment property. The issue is as soon as I want to access the methods from another class and have to initialise this "Files" class, I get an error as its asking me to pass in a value of type IHostingEnvironment; see the error below
Initialisation error.
I don't really know how to do that or how to get around it. If anyone could help me work out what to do or find a workaround please that would be much appreciated

A: You made a constructor for your class which accepts an argument. So you can no longer initialize the class without argument.
So first of all your problem is not related to finding web root path, you may want to edit it. Second the solution is to make another constructor which accepts no arguments and call the other constructor in it with the required parameter.
private readonly IHostingEnvironment HostingEnvironment;

        public Files ()
        {
                Files([The HostingEnviroment variable goes here]);
        }
        public Files (IHostingEnvironment _hostingEnvironment)
        {
            HostingEnvironment = _hostingEnvironment;
        }

A: I don't think that you really need the whole HostingEnvironment just to get string from appsettings, you can created just a special service , or catch it in startup. But if you still want to use HostingEnvironment in your EventClass you can inject it using Event constructor
public class Event
{
  private read only Files _fileMethods;

  public Event (IHostingEnvironment hostingEnvironment)
        {
            _fileMethods = new Files(hostingEnvironment);

        }
}

the same way you can inject the any special service that you can create instead of hostingEnvironment


text:
Q: Is there ways to create optional arguments to functions in vb script? Is there ways to create optional arguments to functions in vb script allowing you to write functions something like...
myFunc("happy")
myFunc("happy", 1, 2, 3)
myFunc("happy", 1)
etc.

A: How about overloading?

A: You can always make it a class and use Public Property Let to populate your Sub/Function before calling it:
  Set oSubName = New cSubName

    'fill your parameters, you can always add more later
    oClass.OptionalParameter1 = true
    oClass.OptionalParameter2 = false

    'execute sub
    oSubName.Execute

  Set oSubName = Nothing

This would require some knowledge on how to make classes, but is probably the next best solution to using arrays.
Good luck.

A: The optional keyword (like in VB6) is not allowed in vbscript
maybe this helps:
https://web.archive.org/web/20210304114036/http://www.4guysfromrolla.com/webtech/071801-1.shtml

A: Obviosly this depends on your environment and whether it supports using both JScript and VBScript in the same file, but I've had some success using Windows Script Host (*.wsf files), ie
<?xml version="1.0" standalone="yes" ?>
<package xmlns="Windows Scripting Host">
    <job id="param">
    <?job debug="true"?>

        <script language="JavaScript">
            <![CDATA[
                function MakeString(args) {
                    var s = [];
                    for(var i = 0, length = arguments.length; i < length; i++)
                        s.push(arguments[i]);
                    return s.join('');
                }
            ]]>
        </script>
        <script language="vbscript">
            <![CDATA[
                WScript.Echo MakeString("hello", " ", "world")
                WScript.Echo MakeString()
                WScript.Echo MakeString(1,2,3,4)
            ]]>
        </script>
    </job>
</package>

where you can define your function in JScript and reference it in VBScript. A better way may well be to include your JScript functions as an external file ie
    <script language="JavaScript" src="makestring.js"/>
    <script language="vbscript">
        <![CDATA[
            WScript.Echo MakeString("hello", " ", "world")
            WScript.Echo MakeString()
            WScript.Echo MakeString(1,2,3,4)
        ]]>
    </script>

A: Just pass a different type and look it.
wscript.echo "1: " & math(7,8,false)
wscript.echo "2: " & math(7,8,5)
wscript.echo "3: " & math(15,false,5)

function math( Addend1 , Addend2, Divisor )
dim tmpTotal

if Addend2 then
   TmpTotal = Addend1 + Addend2
else
   tmpTotal = Addend1
end if

if Divisor then     'if argument Divisor is other than False then do it.
   if Divisor > 0 then  'Hated Divide by Zero since VIC-20.
      tmpTotal = tmpTotal / Divisor)
   end if
end if

end function


text:
Q: Update QA environment - workflow manager databases We have a QA SharePoint 2013 environment we want to refresh from PROD. Workflow manager is already configured and working. I completed the refresh of the content databases but realized the 2013 workflow instances were orphaned. Does anyone know which of the Workflow manager databases also need to be copied to our QA? The WFInstanceManagementDB seems to be one (possibly containing the instances) but there are also the WFManagementDB, WFResourceManagementDB, SbManagementDB, SBMessageContainer01, SbGatewayDatabase that appear to be associated with WFM.
Thanks.

A: You should be able to make it work by making scope restore. Follow the procedures from SM for Disaster Recovery. This article also is good with step by step what needs to be done
Workflow Manager Disaster Recovery


text:
Q: How to resolve with a default class if a matching register is not found in Autofac I am using the following code for register:
builder.RegisterType<QCatVCardParser>().Named<IQCatParser>(".VCF");
builder.RegisterType<QCatVCardParser>().Named<IQCatParser>(".VCARD");
builder.RegisterType<QCatOutlookMessageParser>().Named<IQCatParser>(".MSG");
builder.RegisterType<QCatMimeMessageParser>().Named<IQCatParser>(".EML");
builder.RegisterType<QCatCalendarParser>().Named<IQCatParser>(".ICS");
container = builder.Build();

To retrieve a class reference I am using the below code:
var r = container
    .ResolveNamed<IQCatParser>(Path.GetExtension(fileName).ToUpperInvariant());

Now my question is if a unsuppoted file extension comes let's say .DOC I want to resolve it with a component among one of the registered classes or else with the first registered class.
Is it possible to do this with AutoFac?

A: You can do this with Autofac. You need to create an IRegistrationSource that can provide the default registration if needed. For example, here is the RegistrationsFor code of a source that provides settings classes:
var typedService = service as IServiceWithType;
if (typedService != null && typedService.ServiceType.IsClass && typeof(ISettings).IsAssignableFrom(typedService.ServiceType))
{
    yield return RegistrationBuilder.ForDelegate((c, p) => c.Resolve<ISettingsReader>().Load(typedService.ServiceType))
                .As(typedService.ServiceType)
                .CreateRegistration();
}

Then, inside of a module or directly using your Autofac builder, call RegisterSource to hook up the new registration source.


text:
Q: How can I access the event on underlay element? I have a div, which contains an iframe with map and another div overlapping the map.
HTML

Want to learn more?

CSS
.locationFinder {
    position: relative;
    width: 100%;
    height: 425px;
    background-repeat: no-repeat;
}
.mapover {
    position: absolute;
    top: 0;
    width: 100%;
    height: 428px;
    background-repeat: no-repeat;
    background: black;
    opacity: .5;
}

The second div is over map. so I can't perform any operation on it.
so my requirement is , user still be able to use the map . Is there any way i can achieve this?

A: Did you try pointer-events: none; in your mapover css class ?  This may require additional CSS for certain versions of ie.


text:
Q: Function return type hinting for an array of objects in PHP7 I am very happy with the new features in PHP 7. But I am confused on how to return an array of objects in PHP 7.
For example, we have a class Item, and we want to return an array of objects of this class from our function:
function getItems() : Item[] {
}

But it does not work this way.

A: You can type hint this way using docblocks.
PHP editor (IDE) like PhpStorm supports this very well and will properly resolve the class when iterating over such array.
/**
 * @return YourClass[]
 */
public function getObjects(): array

PHPStorm also supports nested arrays:
/**
 * @return YourClass[][]
 */
public function getObjects(): array

Newer versions of PHPStorm support phpstan/psalm format:
/**
 * @return array<int, YourObject>
 */
public function getObjects(): array

A: I actually understand what you mean, but the answer unfortunately is that you can't do that. PHP7 lacks that kind of expressivity, so you can either declare your function to return "array" (a generic array) or you have to create a new class ItemArray which is an array of Item (but that meaning you will have to code it yourself).
There is currently no way to express "I want an array of Item" instances.
EDIT: As an added reference, here the "array of" RFC of what you wanted to do, it has been declined due to various reasons.

A: The current version of PHP doesn't support a built-in type hinting for an array of objects, as there is no such data type as "an array of objects". A class name can be interpreted as a type in certain contexts, as well as array, but not both at a time.
Actually you can implement such kind of strict type hinting by creating a class based on the ArrayAccess interface, e.g.:
class Item
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }
}

class ItemsArray implements ArrayAccess
{
    private $container = [];

    public function offsetSet($offset, $value)
    {
        if (!$value instanceof Item) {
            throw new Exception('value must be an instance of Item');
        }

        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

function getItems() : ItemsArray
{
    $items = new ItemsArray();
    $items[0] = new Item(0);
    $items[1] = new Item(2);
    return $items;
}

var_dump((array)getItems());

Output
array(2) {
  ["ItemsArrayitems"]=>
  array(0) {
  }
  ["container"]=>
  array(2) {
    [0]=>
    object(Item)#2 (1) {
      ["value":protected]=>
      int(0)
    }
    [1]=>
    object(Item)#3 (1) {
      ["value":protected]=>
      int(2)
    }
  }
}

A: It is not possible at the moment. But you can achieve your intended behavior with a custom array class

function getItems() : ItemArray {
  $items = new ItemArray();
  $items[] = new Item();
  return $items;
}

class ItemArray extends \ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Item) {
            return parent::offsetSet($key, $val);
        }
        throw new \InvalidArgumentException('Value must be an Item');
    }
}

Thanks to bishop's answer here


text:
Q: Is there any documentation for developing applications on jailbreak iPhone I wanted to develop an application for jailbroken iphone so that I can access SMS database.

*

*Can anyone tell me where to get good
stuff to start development for
jailbroken iPhone?

*Can I use XCODE
for development? If yes, how can I
use XCODE?

*Do I need any provisioning
profiles while installing
application on iPhone?

Thanks in advance.

A: YES, XCode is used to write code, even for jailbroken Apps
If you're developing for a jailbroken app first you need to to set Code Signing Identity to Don't Code Sign, then Build the app but dont Build and Go.
When its done building, SSH into your iPhone and copy your app into /Applications.
Then you need to install Link Identity Editor and Mobile Terminal from Cydia. After it's done installing them, open Mobile Terminal and enter:
Code:
ldid -S /Applications/YourApp.app/YourApp
Then just respring your device with BossPrefs or SBSettings (killall SpringBoard wont work if you are on 2.1+) and your app should appear and your Home Screen
For More Info, have a look at this Developing for jailbroken iPhone


text:
Q: How to set the coordinates for a polygon in openlayers? I am very new to OpenLayers and JavaScript, and I have the following problem.
I have an .csv table representing the coordinates of points I want to visualize them on a map using OpenLayers.
I have found the following example on the OpenLayers page,
https://openlayers.org/en/latest/examples/polygon-styles.html
However, I couldn't understand the representation of the coordinates there. More specifically, I didn't know what does the e mean in the coordinate [-5e6, 6e6] for example.
However, I tried to plot a simple square on my map using my coordinates, but it just giving me a point, in the center of the map, as following:
https://jsfiddle.net/api/post/library/pure/#&togetherjs=bD5bfPm7vz
So I don't know what's exactly is wrong, and what should I change? I think it's all in the way the coordinates are written, but not sure though.
And this is my code:
var styles = [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'blue',
      width: 3
    }),
    fill: new ol.style.Fill({
      color: 'rgba(0, 0, 255, 0.1)'
    })
  }),
  new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
        color: 'orange'
      })
    }),
    geometry: function(feature) {
      // return the coordinates of the first ring of the polygon
      var coordinates = feature.getGeometry().getCoordinates()[0];
      return new ol.geom.MultiPoint(coordinates);
    }
  })
];

var geojsonObject = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:3857'
    }
  },
  'features': [{
    'type': 'Feature',
    'geometry': {
      'type': 'Polygon',
      'coordinates': [[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6],
          [-3e6, 6e6], [-5e6, 6e6]]]
    }
  }]
};

var source = new ol.source.Vector({
  features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

var layer = new ol.layer.Vector({
  source: source,
  style: styles
});

    var basic = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

var map = new ol.Map({
  layers: [basic, layer],
  target: 'map',
  view: new ol.View({
    center: [0, 3000000],
    zoom: 2
  })
});

A: OK, I found the answer.
The following coordinates [-5e6, 6e6] is in X,Y format, and is based on the EPSG:3857 projection. XeY is equal to X * 10 ^ Y. Normally the openlayers use the EPSG:3857 projection, but in order to use the longitude/latitude coordinates format, we have to use the projection: EPSG:4326 projection, and we specify it clearly like: projection: 'EPSG:4326


text:
Q: Why does my code uncomment this part of the code out So I've been making a simple HTTP flooder with a Wget and a user agent but when flooding i realize this happens
125.27.78.172 - - [26/Apr/2016:12:38:45 -0500] "GET / HTTP/1.1" 403 4961 "-" "Wget"

And if you are confused about this error i asked my friend to flood my VPS and this happend
208.67.1.176 - - [26/Apr/2016:12:48:32 -0500] "GET / HTTP/1.0" 403 4961 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36"

Why is is it not working with me code:
sprintf(command, "wget -O /tmp/fff --header="Accept: text/html" --user-agent="Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36" http://208.67.1.176/ ");

if you're wondering how this is a flooder the main code loops it

A: Escape the string?
sprintf(command, "wget -O /tmp/fff --header=\"Accept: text/html\" --user-agent=\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36\" http://208.67.1.176/ ");


text:
Q: order of cookbooks in run-list using a custom ohai plugin I have a wapper cookbook that contains a custom ohai plugin. This plugin is used in my second cookbook. Is my config.rb file correct?
cookbook_path [
    '/home/user/.chef/cookbooks',   #<< ohai cookbook
    '/home/user/cookbooks'          #<< wrapper cookbook (ohai plugin) and second cookbook
]

ohai.plugin_path += [
   '/home/user/cookbooks/ohai/plugins'
]

ohai.directory '/home/user/cookbooks/ohai/plugins'

Is it necessary that the wrapper cookbook with the ohai plugin is in the run-list before the second cookbook?
UPDATE:
When I update my custom ohai plugin attribute and run the chef-client, the updated ohai plugin is copied to the specified location /etc/chef/ohai/plugins but the log information shows still the previous value.
include_recipe 'ohai'

ohai 'reload' do
  plugin 'example'
  action :nothing
end

cookbook_file "#{node['ohai']['plugin_path']}/example.rb" do
  source 'example.rb'
  notifies :reload, 'ohai[reload]', :immediately
end

test = "#{node['ohai']['example']}"
log test

A: use ohai resource to load the custom plugin.


text:
Q: How to add data labels in ternary plotly diagram? I am following the example from the plotly documentation. I obtained nice contour plot with datapoints:

Now I would like to make it more readable by either adding labels to the datapoints or to isolines.  Currently, I can know datapoint's coordinates and values by hovering my mouse over it, but I would prefer those numbers to be permanently annotated, so I can for example print it in a scientific article.

A: I would highlight points of interest with fig.add_trace(go.Scatterternary() and tweak the text and marker attributes to make it look good. Here's an example where I've highlighted a point in the lower left corner:
Plot 2

Why not fig.add_annotatoins() or something else?
The perfect would arguably be to be able just set the hoverinfo for any given marker to show all the time. But to my knowledge that's just not possible at the moment. You could also use fig.add_annotations(), but as far as I know you would have to rely on x, y coordinates only both xref and yref set to paper.
An upside of the fig.add_trace(go.Scatterternary() though is that you can include those data in the legend as well with:
fig.update_layout(showlegend = True)
fig.for_each_trace(lambda t: t.update(showlegend = False))
fig.data[-1].showlegend = True

Plot 2

Complete code:
import plotly.figure_factory as ff
import numpy as np
import plotly.graph_objects as go

Al, Cu = np.mgrid[0:1:7j, 0:1:7j]
Al, Cu = Al.ravel(), Cu.ravel()
mask = Al + Cu <= 1
Al, Cu = Al[mask], Cu[mask]
Y = 1 - Al - Cu

enthalpy = (Al - 0.5) * (Cu - 0.5) * (Y - 1)**2
fig = ff.create_ternary_contour(np.array([Al, Y, Cu]), enthalpy,
                                pole_labels=['Al', 'Y', 'Cu'],
                                ncontours=20,
                                coloring='lines',
                                showmarkers=True)

fig.add_trace(go.Scatterternary(
    a = [2],
    b = [8],
    c = [2],
    mode = "markers+text",
    text = ["A"],
    texttemplate = "%{text}<br>(%{a:.2f}, %{b:.2f}, %{c:.2f})",
    textposition = "bottom center",
    marker_symbol = 'circle-open',
    marker_color = 'green',
    marker_line_width = 3,
    marker_size = 12,
    textfont = {'family': "Times", 'size': [14, 14, 14],
#                 'color': ["IndianRed", "MediumPurple", "DarkOrange"]
               }
))

fig.update_layout(showlegend = True)
fig.for_each_trace(lambda t: t.update(showlegend = False))
fig.data[-1].showlegend = True

fig.show()


text:
Q: Incremental Instrumented Android Test Results I am using TeamCity and I am looking at how to get incremental instrumented android test results.
To run the tests I run ./gradlew :TestApp:connectedAndroidDebugTest --info
This gives me output of what tests are running and their state but the full report is only generated at the end.
How can I get incremental android test results in TeamCity?  I can add custom logs that TeamCity will pick up, but I am unsure where to add them in the gradle build file.

A: Looks like, you are using Command Line runner step.
Try using Gradle runner step instead. You will get on-the-fly test reporting with it. TeamCity will display each test as soon as it is executed.


text:
Q: How do I insert time into my Maya animation timeline I frequently get myself into trouble when I've put together a complex animation in Maya with lots of rigs and connections and animated attributes and then find that I need to insert 100 frames somewhere in my 5000 frame animation to make space for additional animation. In the past, I've struggled with selecting all objects and all of their keyframes to move them down the timeline as it seems that I always miss some attributes that don't get moved and then things get ugly and I waste a lot of time fixing things.
I feel like there must be a more elegant way to insert a certain number of frames into the timeline easily without worrying that some keyframes will be left behind. I've tried my luck with the dope sheet, but I don't really find it any easier to use than the graph editor.

A: "Elegant" in this case is in the eye of the beholder.
Effectively what you need to do is move all the keys after a given point by a given amount. The hard part is that moving the keys will change the meaning of the curves: the interpolation is going to change no matter what you do unless you've got locked tangents on both sides of the change.
if you just want to insert keys at a particular point in time, it'll look like this:
def move_keys_after(start, time_shift):
    key_string = '%s:' % start
    for curve in cmds.ls(type='animCurve'):
        before =  cmds.keyframe(curve, q=True)
        cmds.keyframe(curve, r = True,  tc = time_shift, t = (key_string,), iub=True)
        after = cmds.keyframe(curve, q=True)
        print curve, before, "->", after

move_keys_after( 10, 20)

That example moves all of the keys in the scene after time start by time_shift frames.  If you want to limit this to an object you could get the anim curves from the object directly or use the animation flag of the keyframe command


text:
Q: How to understand the defer statement I have two examples about defer statement in golang, the first one is incorrect, and the second one is correct. But I think they have the same problem, in my opinion I think the second still has risk that run out of file descriptors, could any one can help me to clarify why the second is correct? Thanks!
Example1:
for _, filename := range filenames {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close() // NOTE: risky; could run out of file descriptors
    // ...process f...
 }

Example2:
for _, filename := range filenames {
    if err := doFile(filename); err != nil {
        return err
    }
}
func doFile(filename string) error {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close()
    // ...process f...
}

A: Deferred functions run when the enclosing function returns. Spec: Defer statements:

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

In your first example you use a single for loop in which you use defer statements, but the deferred functions will not get executed at the end of the iterations, only after the for loop (when the enclosing function ends). This means all the files you open inside the for loop will remain open 'till the "end". If filenames contains a thousand valid file names, the loop will (try to) open a thousand files before starting to close any of them.
In your second example you "outsourced" dealing with the files to a separate function. Using defer in this function is fundamentally different, as when this function returns, the deferred function (File.Close()) will be called first. So in your second example at most 1 file is open at all times by the posted code, no matter how many elements filenames contains.


text:
Q: Swiffy HTML5 creative clickTAG vs link1 When we are converting creative from swf to html5 with Swiffy and as result we got clickTAG or link1 GET options to redirect url.
Because of this, we have to transmit the same data in the two settings.
Question
Can swiffy runtime replace all link1 to clickTAG so that we can pass a reference to the clickTAG!

A: I was found the solution
var stage = new swiffy.Stage(document.getElementById('swiffycontainer'),
swiffyobject, {});

var tmpVars = {}, flashVars = [];
var keyValues = window.location.search.substring(1).split('&');
for (var i in keyValues) {
    var key = keyValues[i].split('=');
    if (key.length > 1) {
        tmpVars[key[0]] = key[1];
    }
}
if (tmpVars.hasOwnProperty('clickTAG')) {
    tmpVars.link1 = tmpVars.clickTAG;
}
for (var i in tmpVars) {
    flashVars.push([i, tmpVars[i]].join('='));
}

stage.setFlashVars(flashVars.join('&'));
stage.start();


text:
Q: Haskell which function to group list every n such that :: [a] -> Int -> [[a]] I'm sure there's a simple function to do this, it should:
> groupEvery [1,2,3,4,5,6] 2
[[1,2],[3,4],[5,6]]

I just don't know off hand and hoogle was no help..

A: There is also the chunksOf function in the Data.List.Split package, which is part of the Haskell Platform and does exactly what you described.

A: I don't know of any built-in function for that, but it can be implemented easily:
slice :: Int -> [a] -> [[a]]
slice _ [] = []
slice n xs = hs : slice n ts
  where (hs, ts) = splitAt n xs

It repeatedly splits its input to first n elements and the rest. Or, using unfoldr from Data.List:
slice n = unfoldr (\xs -> if null xs then Nothing
                                     else Just (splitAt n xs))

Update: Just for fun I tried to make as short version as possible using standard functions. So far I've got
import Data.Functor ((<$))
import Data.List (unfoldr)
import Data.Maybe (listToMaybe)

slice :: Int -> [a] -> [[a]]
slice n = unfoldr (\xs -> splitAt n xs <$ listToMaybe xs)

using <$ from Maybe's instance of Functor. Or slightly shorter but even less comprehensible using Applicative for (->) [a]:
slice n = unfoldr (liftA2 (<$) (splitAt n) listToMaybe)
slice n = unfoldr ((<$) <$> splitAt n <*> listToMaybe)

The most incomprehensible version of my attempts was
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
slice n = unfoldr (runMaybeT ((MaybeT listToMaybe) >> (lift $ splitAt n)))

A: Or, if you like one-liners:
slice :: Int -> [a] -> [[a]]
slice n = takeWhile (not . null) . map fst . drop 1 . iterate (splitAt n . snd) . (\a -> ([],a))

Or even:
{-# LANGUAGE TupleSections #-}
slice :: Int -> [a] -> [[a]]
slice n = takeWhile (not . null) . map fst . drop 1 . iterate (splitAt n . snd) . ([],)


text:
Q: ContentControl not showing Content I have a custom ContentControl which has a fixed XAML layout like a UserControl (Rather than the usual applied generic template).
Previously this layout had no extra markup, so it was literally:
<ContentControl x:Class="MyControls.CustomViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
</ContentControl>

This worked fine.
I now want to put a border around the content, so I have changed the XAML to:
<ContentControl x:Class="MyControls.CustomViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <ContentControl.Template>
        <ControlTemplate>
            <Border BorderThickness="5" BorderBrush="LightGreen">
                <ContentPresenter />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

This shows the border, but no content.
I tried supplying an explicit binding for ContentPresenter:
<ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>

But this made no difference.
Setting an explicit Content does work:
<ContentPresenter Content="TEST" />

Anyone know why the Content binding doesn't work? I guess I could fall back to the usual generic template but it would be easier if I could just do it directly like a UserControl.

A: Use TemplateBinding instead of Binding inside a ControlTemplate :
<ContentControl.Template>
    <ControlTemplate TargetType="ContentControl">
        <Border BorderThickness="5" BorderBrush="LightGreen">
            <ContentPresenter Content="{TemplateBinding Content}"/>
        </Border>
    </ControlTemplate>
</ContentControl.Template>

EDIT:
The important part of the shown code snippet is the TargetType in the definition of the ControlTemplate. With the target type
<ContentControl.Template>
    <ControlTemplate TargetType="ContentControl">
        <Border BorderThickness="5" BorderBrush="LightGreen">
            <ContentPresenter/>
        </Border>
    </ControlTemplate>
</ContentControl.Template>

already works without any TemplateBinding

A: Add TargetType for Control Template
<ContentControl.Template>
    <ControlTemplate  TargetType="Button">
        <Border BorderThickness="5" BorderBrush="LightGreen">
            <ContentPresenter />
        </Border>
    </ControlTemplate>
</ContentControl.Template>


text:
Q: Structure of build.gradle In the following simple build.gradle file, i have some basic questions.
1.In repositories, when i specify mavenCentral(), is it the repository where all the libraries that i specify like  compile 'com.android.support:support-v4:21.0.2'will be searched? Is there anything else for this apart from mavenCentral()? And what is the url required for after that(oss.sonatype..)?
2.What are the items that should be specified in classpath? Why cant the classpath items be specified like we specify the support libraries?
3.And for using a third party library, i had to specify an Amazon AWS URL at the bottom in allProjects() section. Why is this URL required?
 buildscript {
        repositories {
            mavenCentral()

        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
        classpath 'com.jimdo.gradle:gradle-apt-plugin:0.2-SNAPSHOT'

    }
}

allprojects {
    repositories {
        mavenCentral()
        maven {
            url "https://s3-ap-southeast-1.amazonaws.com/abc-release/abc/"
        }
    }
}

A:
1.In repositories, when i specify mavenCentral(), is it the repository where all the libraries

No, you also have an implicit local Maven repository (usually at ~/.m2) which can also be searched for locally installed packages.  The newer Android Studio builds use jcentral rather than Maven central, but the concept is the same: a central repository for packages.

2.What are the items that should be specified in classpath? Why cant the classpath items be specified like we specify the support libraries?

These are build tool (i.e. gradle) dependencies.  Your app's dependencies are outlined in the app module's specific build.gradle file.

3.And for using a third party library, i had to specify an Amazon AWS URL at the bottom in allProjects() section. Why is this URL required?

Because their libraries are not in Maven central.  So you're effectively pointing Maven to an outside repository you wish to use for your app and any of its libraries.

A:
1.In repositories, when i specify mavenCentral(), is it the repository where all the libraries that i specify like  compile 'com.android.support:support-v4:21.0.2'will be searched?

Yes, but only if it isn't in buildscript block.
Everything inside buildscript is used by build system – gradle and possibly some libraries for it.
allprojects.repositories is place where you declare repositories where libraries used by your application will be searched.


text:
Q: Inverter VOH VOL Does inverter VOL and VOH depend on output load?
I wast trying to solve the below interesting problem.

I think the output will be simply 3v if I consider VOH won't change even under loading. Because here extra 100 ohm resistance is added with same voltage 3volts.So the current through the extra 100ohm will be zero and output will stay at 3volts.
I want to to know whether inverter VOH and VOL depend on output load.

A: Of course they do. The output impedance of the inverter and the load impedance form a voltage divider that will move the output voltage towards the other rail. This is why datasheets specify the output voltage with one or more known loads/currents.

A: If you read datasheet carefully,  All the necessary conditions are given to define the effective RdsOn of the CMOS or TTL or Op Amp output impedance or any driver for that matter.
Voh,Vol {@Iol,Ioh  @Vdd @T['C]}
Thus Zol= Vol/Iol  and Zoh= (Vdd-Voh)/Ioh
For simplicity I call this ESR and it has a nominal and Max or worst case value or tolerance then  once you know total Load current of Vdd/(Zo + Load  Ω ) or use resistance divider Ohm's Law you can easily estimate Vo for any load.  THe Zo tolerance is normal to be +/-25% at a given supply, Vdd for all OEM chips then a tolerance for Vdd and temperature.
Zod rises with lower Vdd and visa versa.... except that 74ALCxxx chips rated for 3.3V are designed to be 25 Ω and 74HCxxx chips are designed @5V to be 50 Ω (nom) and more than double this Zo @3.3V .
They never specify this but it is implicit by the Vol/Iol ratio for given conditions.
This question tests your skills and experience on understanding logic Specifications with  Analog skills.
It may occur to you that this is consistent with properties of all MOSFETs where the Vgs threshold must affect Zo and is dependant on Vdd.
If you already know that CMOS is made from 2 complementary FETs each with RdsOn @ Vgs , where the turn on threshold Vgs(th) must be around <=1/3 of Vgs  to give good results. e.g. Vgs(th)<=1.5 for 5V logic and <=1V for 3.3V logic
The same applies to input threshold , gain  ΔVo/ΔVi and rise time which is current limited for a given capacitance load.
If you understood all this, then the question is trivial.
If you didn't all you needed to know was Zo was 100 Ohms in series (internal)
I used to ask these kinds of interview questions to separate the expert from the intermediates to the newbies in 1 question depending on their depth of response, for analog skills in logic.


text:
Q: Converting a shell command with $(...) for Python subprocess.Popen() I have a docker command that works from terminal and gives expected result.
Now I need to re-write this script into python. Whenever trying to run python, the following error comes up:
    unknown shorthand flag: 'a' in -a
    See 'docker logs --help'.
Below is the command. I have been trying to play with a list array but nothing seems to be working.
Original command in terminal:
docker logs $(docker ps -a -f status=exited| grep -w "dev"| awk '{print $1}')

Python equivalent:
 output = subprocess.Popen([
    "docker",
    "logs",
    "$(docker",
    "ps",
    "-a",
    "-f",
    "status=exited",
    "|",
    "grep",
    "-w",
    "'dev'",
    "|",
    "awk",
    "'{print $1}'"
])

A: In bash $(...) is run as another process and the output is substituted in its place. Everything inside is one argument from the interpreter's perspective.
You will need to run docker ps -a -f status=exited| grep -w "dev"| awk '{print $1}' first and use its output as an argument to docker logs ....
However, with python you don't need pipe through grep and awk, you can use list comprehensions to do mapping and filtering:
import subprocess
containers = subprocess.Popen(["docker", "ps", "-a", "-f", "status=exited"], stdout=subprocess.PIPE)
lines = [l.decode('utf-8') for l in containers.stdout.readlines()] # Convert bytes to strings
filtered = [line for line in lines if 'dev' in line] # Keep only lines with keyword
ids = [l.split()[0] for l in filtered]               # Select first column

for i in ids:
    print(">>>> Logs for " + i)
    subprocess.call(['docker', 'logs', i])

A: Your original bash code isn't running one command -- it's running four!

*

*First, it runs a pipeline consisting of three commands, with the stdout of each connected to the stdin of the next:

*

*['docker', 'ps', '-a', '-f', 'status=exited']

*['grep', '-w', 'dev']

*['awk', '{print $1}']

*Second, it uses the output of the last piece of that pipeline (the awk command) to construct a final docker logs command:

*

*['docker', 'logs'] + shlex.split(awk_pipeline_output) (roughly; because you didn't properly quote, it'll also evaluate each word of that split result as a glob expression).

So, if you really wanted to convert that code to Python, leaving it otherwise exactly-as-written, it would look like:
from subprocess import Popen, PIPE
import shlex

p1 = Popen(['docker', 'ps', '-a', '-f', 'status=exited'], stdout=PIPE)
p2 = Popen(['grep', '-w', 'dev'], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
pipeline_output, _ = p3.communicate()

p4 = Popen(['docker', 'logs'] + shlex.split(pipeline_outlet))


text:
Q: UTF-8 String Capitalization correction in Rails I have an application where users enter their names, often in an international format (e.g. Sarah Grüße). I would like to fix the capitalization of users' names when they enter them incorrectly due to laziness, or different international conventions.
Some users do not capitalize their names at all (e.g mario bel). When this is the case, I would like to capitalize the first letter of the first and last name (which are different columns in the DB). So the result would be Mario Bel.
Some users (often French), capitalize their last names entirely, but this does not fit how we want to display their names. For example Baptist ALBERT should become Baptist Albert.
Some names correctly have multiple capital letters, thus if a name isn't ALL CAPS or all lowercase, I would like to leave it as is. For example McDonald or von Ramstein.
Some characters in UTF-8 obviously have no sense of capitalization, thus these names would also stay the same. (Japanese names for example.)
So what I think I need is a way to detect when a name is in all caps or all lowercase, including non-latin case-sensitive characters like Ü/ü and ignoring non-latin non-case-sensitive characters like ß. Then once detected, correctly change these two cases to First Letter Capitalized.


text:
Q: Python regex, pattern-match multiple backslash characters I have a python raw string, that has five backslash characters followed by a double quote. I am trying to pattern-match using python re.
The output must print the  matching pattern. In addition, two characters before/after the pattern.
import re
command = r'abc\\\\\"abc'
search_string = '.{2}\\\\\\\\\\".{2}'
pattern = re.compile(search_string)
ts_name = pattern.findall(command)
print ts_name

The output shows,
['\\\\\\\\"ab']

I expected
['bc\\\\\"ab']

Anomalies:
1) Extra characters at the front - ab are missing
2) Magically, it prints eight backslashes when the input string contains just five backslashes

A: You can simplify (shorten) your regex and use search function to get your output:
command = r'abc\\\\\"abc'
search_string = r'.{2}(?:\\){5}".{2}'
print re.compile(search_string).search(command).group()

Output:
bc\\\\\"ab

Your regex should also use r prefix.

A: just add a capturing group around the part you want:
command = r'a(bc\\\\\"ab)c'

and access it with:
match.group(1)


text:
Q: In T-SQL how to select only the top(not max) value in a group of record I have some sample data as follows
 Name     Value   Timestamp
  a        23      2016/12/23 11:23
  a        43      2016/12/23 12:55
  b         12     2016/12/23 12:55

I want to select the latest value for a and b. When I used Last_Value, I used the following query
 Select Name, Last_Value(Value) over (partition by Name order by timestamp) from table

This returned 2 rows for a, but I wanted it grouped so that I get only the last entered value for each name. So I had to use sub queries.
select x.Name,x.Value from (Select Name, Last_Value(Value) over (partition by Name order by timestamp) ) as x group by x.Name,x.Value

This again returns 2 records for a...I just wanted to do a group by and orderby and instaed of selelcting the max() wanted to select the top record.
Can anybody tell me how to solve this problem?

A: One method doesn't use window functions:
select t.*
from table t
where t.timestamp = (select max(t2.timestamp) from table t2 where t2.name = t.name);

Otherwise, the subquery method is fine, although I would often use row_number() and conditional aggregation rather than last_value() (or first_value() with a descending order by).
Unfortunately, SQL Server does not support first_value() or last_value() as an aggregation function, only as a window function.


text:
Q: FFMPEG [h264_nvenc @ 0x56151389fe00] Cannot get the preset configuration: invalid version (15) i have issue with ffmpeg as usual :D. I have FFMPEG compiled (version N-90807-g00099ef0d0) with NVIDIA support (latest CUDA and latest NV Headers):
ffmpeg version N-90807-g00099ef0d0 Copyright (c) 2000-2018 the FFmpeg developers
  built with gcc 6.3.0 (Debian 6.3.0-18+deb9u1) 20170516
  configuration: --enable-libnpp --enable-cuda --enable-cuvid --enable-nvenc --extra-cflags=-I/usr/local/cuda/include --extra-ldflags=-L/usr/local/cuda/lib64 --enable-gpl --enable-libx264 --disable-x86asm --enable-libx265 --enable-libfdk-aac --enable-nonfree --enable-x86asm
  libavutil      56. 15.100 / 56. 15.100
  libavcodec     58. 19.100 / 58. 19.100
  libavformat    58. 13.100 / 58. 13.100
  libavdevice    58.  4.100 / 58.  4.100
  libavfilter     7. 19.100 /  7. 19.100
  libswscale      5.  2.100 /  5.  2.100
  libswresample   3.  2.100 /  3.  2.100
  libpostproc    55.  2.100 / 55.  2.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Use -h to get full help or, even better, run 'man ffmpeg'

When I try to run basic transcoding on GPU using command:
ffmpeg -i 'udp://@239.100.0.1:331?fifo_size=100000000' -map i:0x100 -g 20 -vcodec  h264_nvenc -map i:0x101 -ab 128k -ar 48k -acodec aac -f mpegts udp://@239.0.0.1:1234?overrun_nonfatal_optin=

I got this error:
    Input #0, mpegts, from 'udp://@239.100.0.1:331?fifo_size=100000000':
  Duration: N/A, start: 106.414400, bitrate: N/A
  Program 1
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #0:0[0x100]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p(progressive), 1920x1080, 23.98 fps, 23.98 tbr, 90k tbn, 47.95 tbc
    Stream #0:1[0x101](eng): Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, stereo, fltp, 64 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (h264_nvenc))
  Stream #0:1 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
[h264 @ 0x55a5edc45880] co located POCs unavailable
[h264_nvenc @ 0x55a5edc45380] Cannot get the preset configuration: invalid version (15)
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
[aac @ 0x55a5edc46d40] Qavg: 227.785
[aac @ 0x55a5edc46d40] 2 frames left in the queue on closing

I have same version of FFMPEG compiled by the same way on another testing machine and there it is working. I tried to recompile/reinstall ffmpeg with the latest version, but result is the same.
Does someone know what could be wrong on my instance?
Thanks.

A: Fixed. The issue was in nvidia headers. Used version was extremely new. If you'll get this issue, just use the headers with tag n8.0.14.1 and then compile ffmpeg.
FFmpeg version of headers required to interface with Nvidias codec APIs:
git clone https://github.com/FFmpeg/nv-codec-headers.git
git checkout n8.0.14.1
make && make install


text:
Q: Adding my template to the list of code generation items in Studio 2010 I have taken the POCO tt templates that can be used in Studio 2010 with Entity Framework and modified them to better fit my needs.  I have added a few things to make testing easier.
Now I want to be able to right click on the entity framework design surface, choose "Add Code Generation Item" and select my templates instead of the built in POCO ones so that I can use them more easily.
Where do I need to start to make this happen? Any examples anyone can point me to?

A: You can replace the template files on the disk.
They are stored at:
%program files%\Microsoft Visual Studio 10.0\Common7\IDE\
under the directories ItemTemplates and ItemTemlatesCache (one is zip files and the other is what the IDE has open).
They have names that all start with "AdoNetEntityDataModelT4".  You can replace the templates in the zip files (under ItemTemplates) and on disk (in ItemTemplatesCache).  Search around and you'll be able to find the template you wish to change.


text:
Q: SSRS Tablix space adjustment I have the following report designed in my Report Designer:

The header is a text box followed by 2 tablix controls. But when I preview the report, the text box, the first tablix and the second tablix all appear in separate pages. I want them to appear in the same page. Please help.

A: There are a few properties to check that could be causing this. But this is not the default behavior so something must have been inadvertently changed.

*

*Check the PageBreak properties for each table (textboxes don't have this). The BreakLocation should be set to "None".

*In the Report properties, check the PageSize and InteractiveSize. These are normally "8.5in, 11in" or the equivalent for your region.
If all else fails you may need to start with a fresh report.


text:
Q: How can we use a javascript variable in Fitnesse? I am trying to pass a value from a function of JavaScript to Fitnesse page. I have defined a variable in Fitnesse page using syntax " !define  {default_value} ". But I want to assign the value to this variable from Java script.  Is there any way we can pass the value from javascript to fitnesse variable??

A: This has come up recently from another FitNesse user.    As I understand FitNesse, this won't work.  The way that FitNesse runs the test page, it doesn't actually use the page that you see when it runs the test.  When you click on the test button, the following happens:

*

*The TestResponder gets the page that you want to run

*The TestResponder fetches the page that is to be run from the wiki

*The test is executed

When you click on the Test button, it is the same as if you had typed in the following URL in the browser:
http://localhost:8080/FrontPage.MyTest?test

As such, FitNesse doesn't know anything about the state of the page in the browser.
There has been a recent proposal of allowing the passing of properties as a part of the URL that could then be rendered by a ${property} variable reference.
Additionally, there are other considerations for how this would work.  One of the issues is when you run a test as a part of a suite, how would you set your drop down.
The best way to do this is probably to make sure you have either test pages for each option in that drop-down.  I recommend this because presumably they produce different results, or why would they matter?
The other way to do this would be to create a scenario for what you want to test and then call that scenario with each value.
Ultimately, the thing you want to do isn't something that FitNesse is good at.


text:
Q: HTML5 Determine drop drop object In this W3School example I can get lots of data about the event and the target object but how do I determine what object was dropped on to the target?
<!DOCTYPE HTML>

Drag the W3Schools image into the rectangle:

A: In the drop function, the ID of the element you are dropping in is defined as 'data'. You can therefore write var element = document.getElementById(data)
Now, the element variable is the object and you can get all the information you wan't about it, pass it to another function etc.


text:
Q: Is it possible to build google play service lib only for GCM in eclipse? I have created an android app in eclipse. When upload app in google play store,
Google has put a new option on their Pricing and Distribution page of their Google Play Developer Console that requires publishers to declare if they have ads or not. I got following warning message.

We detected Ad SDKs in one or more of your active APKs:
version: XXXXX, sdk: AdMob
If your app is serving ads, please change your ads declaration to
  'Yes'. Failure to accurately declare the presence of ads is a policy
  violation and may result in your app's removal from Google Play. You
  can visit our Help Center to learn more.

Our app does not have ads, yet we are being flagged as having the AdMob SDK. I think it's because we are using google play service library which  includes a transitive dependency on AdMob.
Is it possible to build google play service lib only for GCM in eclipse ?
If yes, then how ?

A: Go for android studio dude, Google play services has a separate instance for Google Could messaging and you can add it into gradle like this.
compile 'com.google.android.gms:play-services-gcm:x.x.x'

A: I don't have much idea about eclipse. But in android studio we can do that.
Google Cloud Messaging
com.google.android.gms:play-services-gcm:8.3.0

you can check more on Google developer Link


text:
Q: Checking if UTD parameter has values in stored procedure I want to check if a parameter with some User-Defined Table Type has values or is NULL but i'm receiving the following error
Msg 137, Level 16, State 1, Procedure SearchByWord, Line 63 [Batch Start Line 7]
Must declare the scalar variable "@Words".

The stored procedure is as follow (only the relevant part)
CREATE PROCEDURE [dbo].[SearchByWord]
(
    @Words Word_List READONLY
)
AS
BEGIN

    SET NOCOUNT ON;

    -- some DECLARE and SET

    IF @Words IS NOT NULL
    BEGIN
       -- stuff
    END

    -- more stuff
END

The User-Defined Table type is
CREATE TYPE [dbo].[Word_List] AS TABLE(
    [element] [varchar](512) NULL
)

A: Use
IF EXISTS(SELECT * FROM @Words)

Not
IF @Words IS NOT NULL

The table valued parameter will always be present and can't be NULL like a scalar parameter.
If you call exec [dbo].[SearchByWord] without passing anything for the parameter the result is that @Words will be empty table.


text:
Q: Selenium python script in eclipse I am facing the following error, while running the python script with Selenium.  Kindly help me to solve this.
(Traceback (most recent call last):
File "C:\Users\WaheGuru\workspace\test\new\first.py", line 8, in <module>
from selenium.common.keys import Keys ModuleNotFoundError: No module named
'selenium.common.keys')

A: Well if you have Python and selenium installed... then something like this should work.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def someCode():
#Some Code to do something with some URL
    elem = driver.find_element_by_name("<Some_Elem_With_Input>")
    elem.send_keys("FOO")
    elem.send_keys(Keys.RETURN)

if selenium is not installed then run the following command
pip install selenium

Check out http://selenium-python.readthedocs.io/installation.html


text:
Q: Google colab always shows connecting, how can I solve it? This is the status of the problem in the picture

A: Based on my understanding, 'Connecting' can be due to many things. The most common reasons are

*

*Your internet connection is unstable

*You become idle* and the session was disconnected

*Either you are away from keyboard or you are doing something else instead of looking at the colab tab.
For 1, you can try using a different internet connection and see if that improves.
For 2, you can either move your mouse every now and then in the colab tab to prevent yourself from becoming idle.. or you can consider subscribing a premium version colab which help with that situation in theory.


text:
Q: Ubuntu 16.04 won't start with linux-image-4.4.0-119-generic My ubuntu 16.04 computer has stopped booting following an update, which updated to linux-image-4.4.0-119-generic. It will only start if I go into advanced grub options and select the previous linux image version, linux-image-4.4.0-116-generic.
Has anybody else encountered this problem, and does anyone know how to fix it?

A: I have noticed the sames issue today. After the question "A new version of boot/grub/menu.lst is available...." you can choice to "keep the local version" or "the package maintainer´s version".
I have tried both options, but either way after the first reboot of UBUNTU OS there is an issue! :(
Also related with upgrade to kernel 4.4.0-119 (but only from 4.4.0-112).
"
...
title           Ubuntu 16.04.4 LTS, kernel 4.4.0-119-generic
root            (hd0)
kernel          /vmlinuz-4.4.0-119-generic root=LABEL=cloudimg-rootfs ro console=hvc0
initrd          /initrd.img-4.4.0-119-generic

title           Ubuntu 16.04.4 LTS, kernel 4.4.0-119-generic (recovery mode)
root            (hd0)
kernel          /vmlinuz-4.4.0-119-generic root=LABEL=cloudimg-rootfs ro  single
initrd          /initrd.img-4.4.0-119-generic

title           Ubuntu 16.04.4 LTS, kernel 4.4.0-112-generic
root            (hd0)
kernel          /vmlinuz-4.4.0-112-generic root=LABEL=cloudimg-rootfs ro console=hvc0
initrd          /initrd.img-4.4.0-112-generic

title           Ubuntu 16.04.4 LTS, kernel 4.4.0-112-generic (recovery mode)
root            (hd0)
kernel          /vmlinuz-4.4.0-112-generic root=LABEL=cloudimg-rootfs ro  single
initrd          /initrd.img-4.4.0-112-generic
"

A: If we skip the "cloud-init" updates, we still get the question about the /boot/grub/men.lst, but if we choose the first option (maintainer's version) we have no issues anymore!
See also https://forums.aws.amazon.com/thread.jspa?messageID=844280&tstart=0


text:
Q: duplicate row based on cell value I want to duplicate row based on cell value then delete the cell value(in red) so that when rerun the script wont work on the same row again
I've tried script but it has 2 problems
1- the cell value remain so when rerun script it will cause duplication of same row again and again
2- remove the formulas that I wrote from the entire sheet
the script if you want to check it is still exist in appscript
https://docs.google.com/spreadsheets/d/1fJc2ymAADaZ4jtEGRAkUkWRape24Un7OE4jYcgcd9FM/edit#gid=0

A: Auto Dupe for Single Row
function AutoDuplicate() {
  var ss=SpreadsheetApp.getActive()
  var sh=ss.getActiveSheet();
  var rg=sh.getDataRange();
  var vA=rg.getDisplayValues();
  var bA=rg.getBackgrounds();
  var v=[];
  var b=[]
  for(var i=0;i<vA.length;i++){
    var t1=bA[i][7];
    var t2=vA[i][7];
    if(bA[i][7]=='#ff0000' && !isNaN(vA[i][7]) && Number(vA[i][7])>0) {
      bA[i][7]='#ffffff';
      for(var j=0;j<vA[i][7];j++) {
        v.push(vA[i]);
      }
      b.push(bA[i]);
      sh.getRange(1,1,v.length,v[0].length).setValues(v);
      sh.getRange(1,1,b.length,b[0].length).setBackgrounds(b);
    }
  }
}

Animation:

Auto Dupe For Multiple Rows
function autoDupeForMultipleRows() {
  var ss=SpreadsheetApp.getActive()
  var sh=ss.getActiveSheet();
  var rg=sh.getDataRange();
  var vA=rg.getDisplayValues();
  var bA=rg.getBackgrounds();
  var v=[];
  var b=[];
  var a=0;
  for(var i=0;i<vA.length;i++){
    if(bA[i][7]=='#ff0000' && !isNaN(vA[i][7]) && Number(vA[i][7])>0) {
      bA[i][7]='#ffffff';
      for(var j=0;j<=vA[i][7];j++) {
        v.push(vA[i]);
        b.push(bA[i]);
      }
    }
  }
  sh.clearContents();
  var org=sh.getRange(1,1,v.length,v[0].length).setValues(v);
  org.setBackgrounds(b);
}

Animation:


text:
Q: MVC Route not found although declared I got the following routes declared:
        routes.MapRoute(
             name: "SurveyContent",
             url: "Survey/{action}/{id}",
             defaults: new { controller = "Contents", action = "List", id = 3, type = 3 }
         );

         );
        routes.MapRoute(
             name: "ItemCreation",
             url: "{controller}/Create",
             defaults: new { controller = "Contents", action = "Details", id = 0 }
         );
        routes.MapRoute(
             name: "OpenContent",
             url: "Open/{code}",
             defaults: new { controller = "Courses", action = "OpenContent", code = "" }
         );

I am trying to access the link localhost/Survey/Create, but returns me a 404 error. Later on I added
        routes.MapRoute(
             name: "SurveyContent1",
             url: "Survey/Create",
             defaults: new { controller = "Contents", action = "Details", id = 0, type = 3 }
         );

under the SurveyContent, but that didn't change anything. What am I doing wrong?

A: The route:
url: "Survey/{action}/{id}",

Will match Survey/Create, before:
url: "{controller}/Create",

So place ItemCreation before SurveyContent.
In the route table, order matters.


text:
Q: Full screen in multiple windows in single screen I have 65 inch tv which I use as monitor for windows.
I want to open multiple windows and each windows must have full screen , which I use for Stock market trading charts.I can hide address bar and bookmark etc , but can I do full screen of 4 windows in single screen ?
It can be in firefox , chrome , IE or any browser.

A: In a single screen, to get multiple windows, you must use Windowed mode (full screen will not work). Set up your applications and then size them to fit your screen and with each other
If you have Windows 10 you can use Snap to Edge, Snap to Half screen and Snap to Quadrant.  That may help you, but I think Windowed mode is better.
https://www.howtogeek.com/198230/how-to-use-snap-assist-and-2x2-snap-on-windows-10/


text:
Q: i'm new to preg_split and regex, am I doing this right? function(){
return preg_split('/[-]/', $_COOKIE[$cookie_login]);
}

I have this being returned, $_COOKIE[$cookie_login] is "1-blahblahblah"
yet when I try to retrieve this using the function above like so:
$string = function();

I get empty strings, such as $string[0] and $string[1] are both empty, what am I doing wrong?
i'm trying to figure out how to use preg_split just like I used the old split since i'm changing to php 5.4
Edit: here is the full function:
    function get_session(){
    global $cookie_login;
    if (isset($_COOKIE[$cookie_login])){
        return preg_split('/[-]/', $_COOKIE[$cookie_login]);
    }
}

and
$string = get_session();

$string[0] is empty as well as $string[1], but print_r($string) works.

A: You're using $cookie_login within the function, but that variable's not defined anywhere. Perhaps it should be just
$_COOKIE['cookie_login']

instead?
As well, [-] in a regex is the same as just -. This isn't "wrong", it's just somewhat redundant to specify a character class for a single character.

followup: Ok, now that you've posted more, here's a major change you could do
DON'T USE GLOBALS You're already got a function, so pass in the cookie name as a paramter:
function get_sesssion($name) {
   return preg_split('/-/', $_COOKIE[$name]);
}
$sess = get_session('cookie_login');

A: function(){
  return explode('-', $_COOKIE[$cookie_login]);
}

A: Use isset to check that cookie exists, i assumes that its cookie_login instead of $cookie_login, or its really $cookie_login, try using global $cookie_login inside your function, or pass it as a function argument (thats better choice than setting global)
<?php
  function get_session() {
    global $cookie_login;
    if ( $cookie_login && isset( $_COOKIE[$cookie_login] ) ) {
      return explode( "-", $_COOKIE[$cookie_login] );
    }
    return false;
  }

  $string = get_session( 'some_cookie' );
  var_dump( $string );
?>

or as a function argument
<?php
  function get_session( $cookie_login = null ) {
    if ( $cookie_login && isset( $_COOKIE[$cookie_login] ) ) {
      return explode( "-", $_COOKIE[$cookie_login] );
    }
    return false;
  }
?>

when doing var_dump if you got bool(false) that means that cookie is not set, otherwise you will get at least an array :\

A: preg_split('/[-]/', $_COOKIE[$cookie_login]);

As - is a special RegEx character, consider escaping it like this \\-.
preg_split('~[\\-]~', $_COOKIE[$cookie_login]);

^ I use ~ as a wrapper character for RegEx patterns as / is too widely used in HTML/XML.


text:
Q: MongoDb: How to drop a database using shell using authentication? I have a authenticated user with all required privileges to drop a database. I want to drop the database from the shell and tried following command
mongo -uuser -ppass newdb --eval "db.dropDatabase();"

I got following:-
MongoDB shell version: 2.4.9
connecting to: newdb
[object Object]

That's it I got no errors and no results. The database still exists with all values.

A: Your command should work
mongo -uuser -ppass newdb --eval "db.dropDatabase();"

If you access to mongo after that with
mongo -uuser -ppass newdb

The database is created again but empty, so when you said:

The database still exists with all values.

Are you sure that has all collections inside ?
To check if has been deleted you can do:
mongo -uuser -ppass
> show dbs

The "newdb" shouldn't appear.
I've tested it with Mongo 2.4.2.

A: You may try this:
mongo -u USER -p PASS --eval "db=db.getSiblingDB('DB_NAME');db.dropDatabase();"

Reference:
http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/


text:
Q: Selecting os after wake on lan using sub-os Recently I had an idea: what if I install a mini os that grub starts by default, that listen for a packet sent by my phone and then it modify the grub configuration files changing the default os to boot?
For example: I wake my pc and I want to take a file from my ubuntu installation via ftp or doing things with Vnc viewer. But the default grub entry is windows 7, then with a linux based mini os can I modify the grub config files, so it boots up ubuntu?
Then, which method can I assume to listen for a packet from my phone?
Thank you all.
Edit: Then this setup it'll be able to reverse thing back


text:
Q: How can I sharpen an image in OpenCV? How can I sharpen an image using OpenCV?
There are many ways of smoothing or blurring but none that I could see of sharpening.

A: You can try a simple kernel and the filter2D function, e.g. in Python:
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
im = cv2.filter2D(im, -1, kernel)

Wikipedia has a good overview of kernels with some more examples here - https://en.wikipedia.org/wiki/Kernel_(image_processing)

In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.

A: To sharpen an image we can use the filter (as in many previous answers)
kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32)

kernel /= denominator * kernel

It will be the most when the denominator is 1 and will decrease as increased (2.3..)
The most used one is when the denominator is 3.
Below is the implementation.
kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32)

kernel = 1/3 * kernel

dst = cv2.filter2D(image, -1, kernel)

A: You can also try this filter
sharpen_filter = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharped_img = cv2.filter2D(image, -1, sharpen_filter)

A: You can sharpen an image using an unsharp mask. You can find more information about unsharp masking here. And here's a Python implementation using OpenCV:
import cv2 as cv
import numpy as np

def unsharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):
    """Return a sharpened version of the image, using an unsharp mask."""
    blurred = cv.GaussianBlur(image, kernel_size, sigma)
    sharpened = float(amount + 1) * image - float(amount) * blurred
    sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))
    sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))
    sharpened = sharpened.round().astype(np.uint8)
    if threshold > 0:
        low_contrast_mask = np.absolute(image - blurred) < threshold
        np.copyto(sharpened, image, where=low_contrast_mask)
    return sharpened

def example():
    image = cv.imread('my-image.jpg')
    sharpened_image = unsharp_mask(image)
    cv.imwrite('my-sharpened-image.jpg', sharpened_image)

A: One general procedure is laid out in the Wikipedia article on unsharp masking:
You use a Gaussian smoothing filter and subtract the smoothed version from the original image (in a weighted way so the values of a constant area remain constant).
To get a sharpened version of frame into image: (both cv::Mat)
cv::GaussianBlur(frame, image, cv::Size(0, 0), 3);
cv::addWeighted(frame, 1.5, image, -0.5, 0, image);

The parameters there are something you need to adjust for yourself.
There's also Laplacian sharpening, you should find something on that when you google.

A: You can find a sample code about sharpening image using "unsharp mask" algorithm at OpenCV Documentation.
Changing values of sigma,threshold,amount will give different results.
// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowContrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);

A:
Any Image is a collection of signals of various frequencies. The
higher frequencies control the edges and the lower frequencies control
the image content. Edges are formed when there is a sharp transition
from one pixel value to the other pixel value like 0 and 255 in
adjacent cell. Obviously there is a sharp change and hence the edge
and high frequency. For sharpening an image these transitions can be
enhanced further.

One way is to convolve a self made filter kernel with the image.
    import cv2
    import numpy as np

    image = cv2.imread('images/input.jpg')
    kernel = np.array([[-1,-1,-1],
                       [-1, 9,-1],
                       [-1,-1,-1]])
    sharpened = cv2.filter2D(image, -1, kernel) # applying the sharpening kernel to the input image & displaying it.
    cv2.imshow('Image Sharpening', sharpened)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

There is another method of subtracting a blurred version of image from bright version of it. This helps sharpening the image. But should be done with caution as we are just increasing the pixel values. Imagine a grayscale pixel value 190, which if multiplied by a weight of 2 makes if 380, but is trimmed of at 255 due to the maximum allowable pixel range. This is information loss and leads to washed out image.
    addWeighted(frame, 1.5, image, -0.5, 0, image);

A: For clarity in this topic, a few points really should be made:

*

*Sharpening images is an ill-posed problem. In other words, blurring is a lossy operation, and going back from it is in general not possible.

*To sharpen single images, you need to somehow add constraints (assumptions) on what kind of image it is you want, and how it has become blurred. This is the area of natural image statistics. Approaches to do sharpening hold these statistics explicitly or implicitly in their algorithms (deep learning being the most implicitly coded ones). The common approach of up-weighting some of the levels of a DOG or Laplacian pyramid decomposition, which is the generalization of Brian Burns answer, assumes that a Gaussian blurring corrupted the image, and how the weighting is done is connected to assumptions on what was in the image to begin with.

*Other sources of information can render the problem sharpening well-posed. Common such sources of information is video of a moving object, or multi-view setting. Sharpening in that setting is usually called super-resolution (which is a very bad name for it, but it has stuck in academic circles). There has been super-resolution methods in OpenCV since a long time.... although they usually dont work that well for real problems last I checked them out. I expect deep learning has produced some wonderful results here as well. Maybe someone will post in remarks on whats worthwhile out there.

A: Try with this:
cv::bilateralFilter(img, 9, 75, 75);

You might find more information here.


text:
Q: Sending data over chrome extension to REST I am trying to send my selection to a server using post and server need REST, Tested my data with Advanced Rest Client and all works well, But when I try from my chrome extension I am getting undefinded error. Here is what I am trying
chrome.runtime.sendMessage({
            method: 'POST',
            action: 'REST',
            headers: {'Remote-User':'myuser'},
            url: 'http://myserver/data/add/',
            data: {'content': 'the paste content'}
        }, function(responseText) {
            alert(responseText);
        });

Any help much appreciated, thanks
Update
Based sdc, I changed my code like this and still responseText is undefined :(
function genericOnClick(info, tab)
{
    var url = 'http://mysite/data/add/';
    var data = $.toJSON({'content': 'the paste content'});
    $.ajax({
      headers: {
        'Remote-User':'username',
        'Content-Type':'application/json;charset=utf-8'
      },
      url: url,
      data: data,
      method: 'POST',
      dataType: 'json',
      error:  function(xhr, status, error){
        alert(xhr.responseText);
      },
      success: function(data){
        console.log('succes: '+data);
      }

    });
}

A: I think you misunderstand the purpose of chrome.runtime.sendMessage. See the first two paragraphs of the Message Passing documentation. sendMessage is used for "communication between extensions and their content scripts" it is not designed for sending an HTTP request.
A content script must also "set up a runtime.onMessage event listener to handle the message" only then will you receive a valid response from the sendMessage request
The result from their example is undefined
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
   console.log(response.farewell);
});
<- undefined

If you are attempting to perform a HTTP request from within your chrome extension, you should use XHR
var data = $.toJSON({'content': 'the paste content'});

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myserver/data/add/", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.setRequestHeader('Remote-User', 'myuser');
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
      console.log('xhr response: '+ xhr.responseText);
  }
}
xhr.send(data);


text:
Q: How do I assign a Vue object's properties, one by one, from a bunch of computed values? I'm trying to build a bunch of Vue objects from some jumbled JSON. I can create a clean array for each type of properties, but I don't know how to take these arrays and map them to the Vue objects.
Trying to stick to ES6. jsfiddle: https://jsfiddle.net/rachidmrad/rfuLxgpz/1/
HTML

Brewery: {{ brewery.name }}

    Location: {{ brewery.location }}

    Specialities: {{ brewery.speciality }}

    Tier: {{ brewery.tier }}

JS
data() {
  return {
    breweries:
      {
        name: [],
        location: [],
        speciality: [],
        tier: []
      }
  }
},

mounted() {
  let thisBrewery = this.name,
      thisLocation = this.location,
      thisSpeciality = this.speciality,
      thisTier = this.tier;

// Get values from JSON - pretty sure I go this part right
  get('https://spreadsheets.google.com/feeds/cells/1CTlh5HuhQd44_bTuQF_X02QzJpa0ReQJB5jb8MSFvO8/od6/public/values?alt=json')
    .then((data) => {
      let json = JSON.parse(data);
      maxEntry = json.feed.entry.length /4 - 1;
      for (let i = 0; i < maxEntry; i++) {
          thisBrewery[i] = json.feed.entry[j].content.$t;
          thisLocation[i] = json.feed.entry[j + 1].content.$t;
          thisSpeciality[i] = json.feed.entry[j + 2].content.$t;
          thisTier[i] = json.feed.entry[j + 3].content.$t;
          j = j + 4;
      }
    })
    .catch((err) => {
      console.log('oops');
  });
}

I basically need to map thisBrewery to breweries.name, thisLocation to breweries.location, etc.
I don't believe the JSON is relevant here (I tested the arrays I'm calculating in a non-Vue app and they check out) but feel free to beautify and look at the data: https://spreadsheets.google.com/feeds/cells/1CTlh5HuhQd44_bTuQF_X02QzJpa0ReQJB5jb8MSFvO8/od6/public/values?alt=json (this is a Google Sheet JSON)

A: Your HTML suggests you are expecting an array of brewery objects with each object containing name, location properties etc. But, you have one breweries object with an array for each values in your data. So, create an array of brewery objects and push it to breweries.

let app = new Vue({
  el: '#app',
  data() {
    return {
      breweries: []
    }
  },
  mounted() {
    fetch('https://spreadsheets.google.com/feeds/cells/1CTlh5HuhQd44_bTuQF_X02QzJpa0ReQJB5jb8MSFvO8/od6/public/values?alt=json')
      .then(data => data.json())
      .then(json => {
        for (let j = 4; j < json.feed.entry.length; j += 4) {
          const name = json.feed.entry[j].content.$t,
            location = json.feed.entry[j + 1].content.$t,
            speciality = json.feed.entry[j + 2].content.$t,
            tier = json.feed.entry[j + 3].content.$t;

          // push an object to the array
          this.breweries.push({ name, location, speciality, tier });
        }
      })
      .catch((err) => {
        console.log('oops');
      });
  }
})

Brewery: {{ brewery.name }}

          Location: {{ brewery.location }}
 Specialities: {{ brewery.speciality }}
 Tier: {{ brewery.tier }}

Note:

*

*With your old structure, you could've done v-for="(name, index) in breweries.name" and use the index to get other properties like {{ breweries.location[index] }}

*let thisBrewery = this.name should've been this.breweries.name

*You can skip the get function and use the native fetch instead

*You can directly use j in the for loop and increment it with 4

*How do I create a runnable stack snippet?


text:
Q: Maxwell equations: exterior derivative vs partial derivative In the language of differential forms, Maxwell's equations are
$$dF=0,\quad d\star F= J,\quad dJ=0.$$
If we write the dual field as
$$\star F=\epsilon_{\alpha\beta\mu\nu}F^{\alpha\beta}\,dx^\mu\wedge dx^\nu,$$
by the Bianchi identity one can see that
$$\partial_\mu\,(\star F)^{\mu\nu}=0,$$
such that $(\star F)^{\mu\nu}$ is a conserved quantity. Please correct me if the indices on this are wrong however
Some authors seem to equate this equation to $d\star F=0$, however this doesn't seem right to me as then the second Maxwell equation listed would always be equal to zero (I don't see where I have made assumptions of the absence of sources so far), and also if we explicitly write it out we have
$$d\star F=\frac{1}{2}\epsilon_{\alpha\beta\mu\nu}\frac{\partial}{\partial x^{\lambda}}F^{\alpha\beta}\,dx^\lambda\wedge dx^\mu\wedge dx^\nu,$$
which is not the same. Furthermore, the index of the derivative is not present in the levi civita and so the Bianchi identity cannot be used. So my question is if there is a relation between the exterior and partial derivative here, or if in any situation the two equations
$$\partial_\mu\,(\star F)^{\mu\nu}=0,\quad d\star F=0,$$
mean the same thing.
Another confusion I have here however is that the result for this computation on Wikipedia is the following
$$d\star F=\frac{1}{6}\epsilon_{\beta\gamma\delta\eta}\frac{\partial}{\partial x^{\alpha}}F^{\alpha\beta}\,dx^\gamma\wedge dx^\delta\wedge dx^\eta,$$
so I am unsure if I am doing the calculation correct.

A: In standard notation, $F=\frac{1}{2}F_{ab}dx^a \wedge dx^b$ and $\star F =\frac{1}{4}F^{ab}\epsilon_{abcd}dx^c\wedge dx^d$.
Then $d \star F = \frac{1}{4}\partial_a(F^{bc}\epsilon_{bcde})dx^a \wedge dx^d \wedge dx^e$. This is what we have called $J$. (Note that sometimes what we have defined to be $J$ is defined as $\star J$ instead).
$\partial_\mu(\star F)^{\mu\nu}$ is identically zero as you mention, which ultimately arises from $F=dA$.
$d \star F$ is $\bf{not}$ equivalent to $\partial_\mu(\star F)^{\mu\nu}$. But obviously in the absence of any source, they happen to take the same value of zero.
As for what you have found on wikipedia, I believe you have missed out a factor of $\sqrt{-g}$, which then gives the corresponding result for EM in curved spacetime ($g$ is the metric).


text: Q: How to hide the apps menu and odoobot in odoo 12 i want to hide the apps menu and the odoobot. did some research on this and found out that hiding is done by inheriting the view(xml) and customizing. I have no idea  where to find the views for these. I don't want to delete , just need to hide. Can someone please tell me where to find these views?


text:
Q: Objective-C runtime code generation I want to create an Objective-C application which lets you specify a class implementation at runtime.
I want the user to type some code (correctness of the code is out of scope for now).
When the user is done i want to create a class of the typed code and use it in the application.
So i want to dynamically add code in runtime of the application. Is this possible?
If so, how can i achieve this? If not, why not and are there any alternatives to create the same effect which i want to create?
Thanks.

A: You can dynamically load classes at runtime, but to get there you'd first need to handle distributing a compiler, its compilation dependencies (headers, ...), setup its enviroment, etc.
Usually applications use scripting languages that are painlessly embeddable (Lua, Python, ...) or already available on the platform (JavaScript, AppleScript, ...).

A: I'd check out F-Script. It's closer to smalltalk than Obj-C, but IMO it's closer to Obj-C than JavaScript or Lua :-)

A: On iOS devices, this isn't possible. On a Mac you could link against the clang+llvm libraries and use them to generate code into a buffer, then mprotect() the buffer to be executable, I believe.


text:
Q: ASP.NET dll on .jsp page Is it possible to build a .dll created from a class library in ASP.NET and use it's functionality on a .jsp page?  I know how to create the .dll, but I am not very familiar with .jsp pages.
If you could provide an example of the entire .jsp page, that would be great.  Thanks!
Edit: I guess what I'm trying to say is that I made a new project in Visual Studio (a class library) that has one public function (returns a string) and when it is compiled, it creates a .dll. I would like to use that .dll on a .jsp page.

A: Java and ASP.NET don't work together in this case.
You could make a ASP.NET webservice and consume that from your jsp site.

A: You can use jnbridge to use the class library from jsp. See www.jnbridge.com.

A: There is mainsoft grasshopper, which is a .NET runtime for a Java Servlet container.


text:
Q: Use of dbplyr for in-database processing vs directly writing SQL code We are planning to explore use of dbplyr for Snowflake and would like get more insight.

*

*dbplyr converting SQL code for in-database processing will be equally efficient than directly writing SQL code ?

*does dbplyr supports complex multi-level (at least 3 level) sub-query ?

Over question is that ....Does it make sense to use dbplyr for enterprise level application for big data analysis ?

A: dbplyr works by translating dplyr code into SQL. This has some advantages:

*

*elegance of R tools

*access to other parts of R programming language (e.g. loops, plots, packages)

*the same code can be translated to a different database type

and some disadvantages:

*

*not all R commands have translations defined

*some restrictions on how R code can be written for translation

*presentation of translated commands is less elegant than human written SQL code

*error messages in R are not always sufficient to debug problems that occur in the database

Whether it is right for your application is a practical question you will need to test.
Regarding sub-queries:

*

*dbplyr uses sub-queries throughout its translation, but not in the same way developers write sub-queries

*SQL has an upper limit on the number of sub-queries it can handle, if you write your dplyr code badly then you can encounter this limit

Other answers you might find relevant:

*

*Inserting your own SQL queries into dbplyr

*What should you expect of auto-generated queries

*Layers of nesting and readability of queries


text:
Q: Get value from dialog without closing it? I have an application that uses a JDialog to get input from the user, and then searching for files, not a browse dialog, but a more specialized one using metadata.
All this works fine. The only problem is I would like to be able to let the user input the search values, press Ok, and receive these values to do the search and some other operations (from the calling class that opened the dialog) without closing the dialog?
It's necessary to do these operations from the calling class, because that's part of a plugin in an editor.
Basically, in short it's sort of like the way a Find dialog works in any editor - the find dialog stays open while you skip from one found item to the next...
It seems like I'm missing something simple, but I cannot see how to do this.
EDIT:
I tried this in a simple test application according to the tutorial suggested by Nick Rippe, but I think I'm misunderstanding it somehow, because I cannot get it to work. I added a field with getters and setters, and then try to get it:
Main class:
public class TestJFrames {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        TestForm frame = new TestForm();
        frame.setDefaultCloseOperation(frame.DO_NOTHING_ON_CLOSE);
        frame.addPropertyChangeListener("fileSelected", new FileSelectedListener());
        frame.setVisible(true);
    }
}

class FileSelectedListener implements PropertyChangeListener {

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("TEST");
    }
}

From the form class:
  private String fileSelected;
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        this.setFileSelected("Test");
    }

    public String getFileSelected() {
        return fileSelected;
    }

    public void setFileSelected(String fileSelected) {
        this.fileSelected = fileSelected;
    }

I ended up finding a different solution. Posting it here if it could help someone else with a similar difficulty:
It hit me that I could listen to the button event from the calling class, by registering it as a listener to the dialog class. I pretty much followed this example: Create a custom event in Java

A: The Java Tutorials have a section specifically devoted to this.  I'd suggest checking that out.
Combine that with the Getting User Input section, and you have exactly what you wanted.
EDIT
Here's an example from messing with the tutorials a little:
import java.awt.event.*;
import javax.swing.*;

public class Temp extends Box{
    JFrame frame;
    JTextArea text;

    public Temp(JFrame frame){
        super(BoxLayout.Y_AXIS);
        this.frame = frame;
        text = new JTextArea("Clickity Clack, down't the track.\nspam");
        add(text);
        JButton button = new JButton("Click Me");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                launchDialog();
            }
        });
        add(button);
    }

    public void launchDialog(){
        //What you want the find button to do
        JButton findButton = new JButton("Find");
        findButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int start = text.getText().indexOf("spam");
                int end = start + "spam".length();
                if(start != -1){
                    text.requestFocus();
                    text.select(start, end);
                }
            }
        });

        //Cancel button hides the dialog
        JButton cancelButton = new JButton("Cancel");

        // Create the options displayed in the dialog
        final JOptionPane optionPane = new JOptionPane(
                "Find \"spam\"?\n"
                + "Do you understand?",
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION, null, new Object[]{findButton, cancelButton});

        // Build the dialog window
        final JDialog dialog = new JDialog(frame,
                                     "Click a button",
                                     false);

        //Add action to close button
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        });

        //Finish up and make it visible
        dialog.setContentPane(optionPane);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setLocation(100, 100);
        dialog.pack();
        dialog.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new Temp(frame));
                frame.pack();
                frame.setVisible(true);
            }});
    }

}


text:
Q: Assigning data to variables in the component so it could be used anywhere within the component in angular 2 I have a function in my angular 2 project which fetches data from database through an api. I have created the following function that stores the data succesfully in the variable "ReqData" that has been assigned as type "any".
 this._visitService.getchartData().subscribe(data =>
{ this.ReqData = data
  console.log("ISubscribe", this.ReqData );

});
console.log("OSubscribe", this.ReqData );
this.ImpoData = this.getData( this.ReqData);

But the problem is although that the data can be successfully passed on within the subscribe, calling the value outside of the subscribe gives out the output undefined. Is there a way to get to use the data outside the subscribe too.

A: As it is, this.ReqData is already accessible everywhere in the component. But you just need to make sure that you call it only after that the code inside subscribe has been called, which is when this._visitService.getchartData() has retrieved the data. This is because the code inside subscribe will be executed asynchronously.
If you want to use the value straight after, just do it in the subscribe block
 this._visitService.getchartData().subscribe(data =>
{ this.ReqData = data
  console.log("ISubscribe", this.ReqData );
  this.ImpoData = this.getData( this.ReqData);

});
//Here this.ReqData is not defined

Edit: If you really want to use that value outside of the subscribeblock, you can convert the observable to a promise and use the await/async pattern
import 'rxjs/add/operator/toPromise';

//...
async yourMethod()
{
    try
    {
        this.ReqData = await this._visitService.getchartData().toPromise();
        //Here this.ReqData is accessible
        this.ImpoData = this.getData( this.ReqData);
    }
    catch(e)
    {
        //Handle your error here
    }

}