text:
Q: Method that accepts both float[] and double[] arrays I have a method that accepts an array (float or double), start and end index and then does some element manipulations for indexes in startIndex to endIndex range.
Basically it looks like this:
public void Update(float[] arr, int startIndex, int endIndex)
{
   if (condition1)
   {
     //Do some array manipulation
   }
   else if (condition2)
   {
     //Do some array manipulation
   }
   else if (condition3)
   {
       if (subcondition1)
       {
         //Do some array manipulation
       }
   }
}

Method is longer than this, and involves setting some elements to 0 or 1, or normalizing the array.
The problem is that I need to pass both float[] and double[] arrays there, and don't want to have a duplicated code that accepts double[] instead.
Performance is also critical, so I don't want to create a new double[] array, cast float array to it, perform calcs, then update original array by casting back to floats.
Is there any solution to it that avoids duplicated code, but is also as fast as possible?

A: You have a few options. None of them match exactly what you want, but depending on what kind of operations you need you might get close.
The first is to use a generic method where the generic type is restricted, but the only operations you can do are limited:
public void Update<T>(T[] arr, int startIndex, int endIndex) : IComarable
{
   if (condition1)
   {
     //Do some array manipulation
   }
   else if (condition2)
   {
     //Do some array manipulation
   }
   else if (condition3)
   {
       if (subcondition1)
       {
         //Do some array manipulation
       }
   }
}

And the conditions and array manipulation in that function would be limited to expressions that use the following forms:
if (arr[Index].CompareTo(arr[OtherIndex])>0)
arr[Index] = arr[OtherIndex];

This is enough to do things like find the minimum, or maximum, or sort the items in the array. It can't do addition/subtraction/etc, so this couldn't, say, find the average. You can make up for this by creating your own overloaded delegates for any additional methods you need:
public void Update<T>(T[] arr, int startIndex, int endIndex, Func<T,T> Add) : IComarable
{
   //...
   arr[Index] = Add(arr[OtherIndex] + arr[ThirdIndex]);
}

You'd need another argument for each operation that you actually use, and I don't know how that will perform (that last part's gonna be a theme here: I haven't benchmarked any of this, but performance seems to be critical for this question).
Another option that came to mind is the dynamic type:
public void Update(dynamic[] arr, int startIndex, int endIndex)
{
     //...logic here
}

This should work, but for something called over and over like you claim I don't know what it would do to the performance.
You can combine this option with another answer (now deleted) to give back some type safety:
public void Update(float[] arr, int startIndex, int endIndex)
{
    InternalUpdate(arr, startIndex, endIndex);
}
public void Update(double[] arr, int startIndex, int endIndex)
{
    InternalUpdate(arr, startIndex, endIndex);
}
public void InternalUpdate(dynamic[] arr, int startIndex, int endIndex)
{
     //...logic here
}

One other idea is to cast all the floats to doubles:
public void Update(float[] arr, int startIndex, int endIndex)
{
    Update( Array.ConvertAll(arr, x => (double)x), startIndex, endIndex);
}

public void Update(double[] arr, int startIndex, int endIndex)
{
   //...logic here
}

Again, this will re-allocate the array, and so if that causes a performance issue we'll have to look elsewhere.
If (and only if) all else fails, and a profiler shows that this is a critical performance section of your code, you can just overload the method and implement the logic twice. It's not ideal from a code maintenance standpoint, but if the performance concern is well-established and documented, it can be the worth the copy pasta headache. I included a sample comment to indicate how you might want to document this:
/******************
   WARNING: Profiler tests conducted on 12/29/2014 showed that this is a critical
            performance section of the code, and that separate double/float
            implementations of this method produced a XX% speed increase.
            If you need to change anything in here, be sure to change BOTH SETS,
            and be sure to profile both before and after, to be sure you
            don't introduce a new performance bottleneck. */

public void Update(float[] arr, int startIndex, int endIndex)
{
    //...logic here
}

public void Update(double[] arr, int startIndex, int endIndex)
{
    //...logic here
}

One final item to explore here, is that C# includes a generic ArraySegment<T> type, that you may find useful for this.

A: Just an idea. I have no idea what the performance implications are, but this helped me to go to sleep :P
public void HardcoreWork(double[] arr){HardcoreWork(arr, null);}
public void HardcoreWork(float[] arr){HardcoreWork(null, arr);}

public struct DoubleFloatWrapper
{
    private readonly double[] _arr1;
    private readonly float[] _arr2;

    private readonly bool _useFirstArr;

    public double this[int index]
    {
        get {
            return _useFirstArr ? _arr1[index] : _arr2[index];
        }
    }

    public int Length
    {
        get {
            return _useFirstArr ? _arr1.Length : _arr2.Length;
        }
    }

    public DoubleFloatWrapper(double[] arr1, float[] arr2)
    {
        _arr1 = arr1;
        _arr2 = arr2;
        _useFirstArr = _arr1 != null;
    }
}

private void HardcoreWork(double[] arr1, float[] arr2){

    var doubleFloatArr = new DoubleFloatWrapper(arr1, arr2);
    var len = doubleFloatArr.Length;

    double sum = 0;

    for(var i = 0; i < len; i++){
        sum += doubleFloatArr[i];
    }
}

Don't forget that if the amount of elements you have is ridiculously small, you can just use pooled memory, which will give you zero memory overhead.
ThreadLocal<double[]> _memoryPool = new ThreadLocal<double[]>(() => new double[100]);

private void HardcoreWork(double[] arr1, float[] arr2){

    double[] array = arr1;
    int arrayLength = arr1 != null ? arr1.Length : arr2.Length;

    if(array == null)
    {
        array = _memoryPool.Value;

        for(var i = 0; i < arr2.Length; i++)
            array[i] = arr2[i];
    }

    for(var i = 0; i < 1000000; i++){
        for(var k =0; k < arrayLength; k++){
            var a = array[k] + 1;
        }
    }
}

A: What about implementing the method using generics? An abstract base class can be created for your core business logic:
abstract class MyClass<T>
{
    public void Update(T[] arr, int startIndex, int endIndex)
    {
        if (condition1)
        {
            //Do some array manipulation, such as add operation:
            T addOperationResult = Add(arr[0], arr[1]);
        }
        else if (condition2)
        {
            //Do some array manipulation
        }
        else if (condition3)
        {
            if (subcondition1)
            {
                //Do some array manipulation
            }
        }
    }

    protected abstract T Add(T x, T y);
}

Then implement per data type an inheriting class tuned to type-specific operations:
class FloatClass : MyClass<float>
{
    protected override float Add(float x, float y)
    {
        return x + y;
    }
}

class DoubleClass : MyClass<double>
{
    protected override double Add(double x, double y)
    {
        return x + y;
    }
}

A: John's comment about macros, although completely inaccurate characterization of C++ templates, got me thinking about the preprocessor.
C#'s preprocessor is nowhere near as powerful as C's (which C++ inherits), but it still is able to handle everything you need except the duplication itself:
partial class MyClass
{
#if FOR_FLOAT
    using Double = System.Single;
#endif

    public void Update(Double[] arr, int startIndex, int endIndex)
    {
        // do whatever you want, using Double where you want the type to change, and
        // either System.Double or double where you don't
    }
}

Now, you need to include two copies of the file in your project, one of which has an extra
#define FOR_FLOAT

line at the top.  (Should be fairly easy to automate adding that)
Unfortunately, the /define compiler option applies to the entire assembly, not per-file, so you can't use a hardlink to include the file twice and have the symbol only defined for one.  However, if you can tolerate the two implementations being in different assemblies, you can include the same source file into both, using the project options to define FOR_FLOAT in one of them.
I still advocate using templates in C++/CLI.

A: Most code isn't so performance-critical that taking the time to convert from float to double and back causes a problem:
public void Update(float[] arr, int startIndex, int endIndex)
{
    double[] darr = new double[arr.Length];
    for(int i=startIndex; i<endIndex; i++)
        darr[i] = (double) arr[i];
    Update(darr, startIndex, endIndex);
    for(int j=startIndex; j<endIndex; j++)
        arr[j] = darr[j];
}

Here's a thought experiment. Imagine that instead of copying, you duplicated the code of the double[] version to make a float[] version. Imagine that you optimized the float[] version as much as necessary.
Your question is then: does the copying really take that long? Consider that instead of maintaining two versions of the code, you could spend your time improving the performance of the double[] version.
Even if you had been able to use generics for this, it's possible that the double[] version would want to use different code from the float[] version in order to optimize performance.


text:
Q: Flutter - Render new Widgets on click The title basically says it all. A very nooby question... I have this basic code to create the initial state of my app :
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Some title'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(title: new Text(config.title)),
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          new InputWidget(),
        ]
      ),
    );
  }
}

Now, how can I render a new Widget when the user clicks on a button? Let's say I want to instantiate another InputWidget.
thanks

A: Your build function is "just code", so you can build the array you pass to the column dynamically, using something like
var children = [];
children.add(new InputWidget());
if (_showAnother)
  children.add(new InputWidget());
...
  body: new Column(
    ...
    children: children,
...

...where _showAnother is some sort of bool field that you set when the button is tapped.

A: I hope I understand your question correctly...
I think the main point is that you should not think of "another" widget - if you change the content of MyHomePage from having first one child and then two you don't really keep the first child and then add another child. You simply first say "I want one child" and then you change your mind and say "I want two children".
In your code you do this by calling setState inside _MyHomePageState. Flutter takes care of keeping the first and adding the second child.
import 'dart:core';
import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Some title'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  int count = 1;

  @override
  Widget build(BuildContext context) {
    List<Widget> children = new List.generate(count, (int i) => new InputWidget(i));

    return new Scaffold(
        appBar: new AppBar(title: new Text(widget.title)),
        body: new Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: children
        ),
        floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.add),
          onPressed: () {
            setState(() {
              count = count + 1;
            });
          },
        )
    );
  }
}

class InputWidget extends StatelessWidget {

  final int index;

  InputWidget(this.index);

  @override
  Widget build(BuildContext context) {
    return new Text("InputWidget: " + index.toString());
  }
}

Is this what you meant?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to override material design in WPF MVVM for a single control and use default style of WPF I am developing a WPF MVVM application.
I have used material design for text box, button and tab design.  I am using a data grid inside the tab control.
I would like:

*

*to override material design style for data grid.

*to use default WPF style only for data grid.

*Scroll bar is not visible and want to make it visible.

How can we achieve that?

A: This is not an ideal way, but it works:
<DataGrid
    [...]
    RowBackground="White"
    CellStyle="{x:Null}"
    ColumnHeaderStyle="{x:Null}"
    RowStyle="{x:Null}"
    RowHeaderStyle="{x:Null}"
    Style="{x:Null}"
    [...]>
</DataGrid>

Output:

MaterialDesign Styles for DataGrid Control

A: In my case override style for a type not working in window ,but when I tried in App.xml it works. In my case the control is toggle button. you can change the style for data grid. the code is :
  <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/IG/IG.MSControls.Core.Implicit.xaml" />
                <ResourceDictionary Source="Themes/IG/IG.MSControls.Toolkit.Implicit.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Indigo.xaml" />

            </ResourceDictionary.MergedDictionaries>

            <Style TargetType="{x:Type ToggleButton}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ToggleButton">
                            <Border CornerRadius="8" BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                                <ContentPresenter HorizontalAlignment="Center"
                                              VerticalAlignment="Center"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Background" Value="#FF0F0F4B" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Background" Value="#FF73ADDE" />
                        <Setter Property="Foreground" Value="#FF150404" />
                    </Trigger>
                </Style.Triggers>
            </Style>

        </ResourceDictionary>
    </Application.Resources>


text:
Q: Onclick prepend link to image src I have this code below that consist of a HTML tab with a image inside of it. What i'm currently trying accomplish is to create a onclick function for when i click the capture button it will prepend a link infront of my image src to make it something like this

And it will remove the link after the image is downloaded what i have done below is that i try to prepend a text to my link but it doesn't seem to work. Is there an easy way to accomplish this? Any help would be greatly appreciated thanks!

function sendData() {
  html2canvas(document.getElementById('capture'), {
    allowTaint: false,
    useCORS: true
  }).then(function(canvas) {
    var openList = $('[data-target="#openly"]');
    $('#testaroni').prepend('src', 'https://cors-anywhere.herokuapp.com/' + openList.attr('src'));
    $('#test').attr('href', canvas.toDataURL('image/png'));
    $('#test').attr('download', 'Test.png');
    $('#test')[0].click();
  });
}

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

document.getElementById("defaultOpen").click();
body {
  font-family: Arial;
}

.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  margin-top: 10px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

/* Style the buttons inside the tab */

.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
  border-bottom: 8px;
}

/* Change background color of buttons on hover */

.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */

.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 25px;
  border: 1px solid #ccc;
  border-top: none;
  -webkit-animation: fadeEffect 1s;
  animation: fadeEffect 1s;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  background-color: white;
}

.jobs-panel {
  display: table;
  max-height: 100%;
  width: 85%;
  background-color: #b7bcbe;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  padding-top: 20px;
}

.tabwidth {
  width: 85%;
  margin: 0 auto;
}
<!DOCTYPE html>

  <meta charset="utf-8" />

  <link rel="shortcut icon" href="//#" />

          <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>

  <button type="button" onclick="sendData()" ;>Capture!</button>


text:
Q: Bearing angle of the vehicle I have logged some data from OBD-II port of a vehicle using Torque app. One of the parameters logged via GPS is "Bearing" which I suppose is the angle between North and vehicle direction of motion (?). If that is true, should the difference between each two consecutive data points give me the turning angle of the vehicle?
Thanks for reading.


text:
Q: Modalpopupextender with usercontrol I am using different user controls with Modalpopupextender (within page, repeater etc.) and it took some time to figure all the tricks how to get this two togeather.
I have now ended up with the following problem
When I pass a param into user control
UserControl.ParamID = 1;

I am able to receive it in user control, but at the strange step of page cycle.
When I try to do
protected void Page_PreRender(object sender, EventArgs e)
{
     throw new Exception(ParamID);
}

I get null for ParamID!?
But when I do
<% throw new Exception(ParamID); %>

from html, I get a correct ParamID value.
I tryied to store ParamID as ViewState, as a HiddeField, and it is always doing the same error.
Also, when I use this user control wihout mpe, just in regular aspx page, it all works just fine.
What is the catch?


text:
Q: Cannot drop the currently open database Я только начал изучать Docker и пытаюсь создать базу данных из скрипта sql, но получаю ошибку.
2022-04-08 08:27:25.874 UTC [84] ERROR:  cannot drop the currently open database

2022-04-08 08:27:25.874 UTC [84] STATEMENT:  DROP DATABASE demo;

psql:/docker-entrypoint-initdb.d/demo.sql:17: ERROR:  cannot drop the currently open database

Команда которую я использую.
docker run --name demodb -p 5432:5432 -e POSTGRES_USER="test_sde" -e POSTGRES_PASSWORD="@sde_password012" -e POSTGRES_DB="demo" -e PGDATA=/var/lib/postgresql/data/pgdata -d -v "/Users/anton/Desktop/sde_test_db1/":/var/lib/postgresql/data -v "/Users/anton/Desktop/sde_test_db1/sql/init_db/":/docker-entrypoint-initdb.d postgres:13.3

Часть скрипта sql на котором происходит ошибка
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

DROP DATABASE demo;
--
-- Name: demo; Type: DATABASE; Schema: -; Owner: -
--

CREATE DATABASE demo;

A: Ошибка возникает, потому что в момент выполнения команд из скрипта, вы уже присоединены к БД.
Официальный докер образ postres так устроен, что при первом старте он сам создает БД указанную в переменной окружения POSTGRES_DB (или POSTGRES_USER если POSTGRES_DB не установлена) и потом присоединяется к этой БД и выполняет скрипты из каталога /docker-entrypoint-initdb.d.
Это значит, что при запуске вашего скрипта БД с именем demo уже создана, и вам не нужно ни удалять ее ни создавать заново. Либо используйте другого пользователя, если вы хотите создать дополнительную БД.


text:
Q: Fade-in a control in when a view is loaded (and not inserted after a state change) What I'm after is for a control to be faded in when the view it's contained in appears for the first time. I've tried everything but have had no luck.
withAnimation(.default) {
    Text("hey")
        .transition(.opacity)
}

// as well as

Text("hey")
    .transition(.opacity)
    .animation(.default)

// and finally

@State var opacity:Double = 0.0
Text("hey")
    .opacity(self.opacity)
    .transition(.opacity)
    .animation(.default)
[...]
.onAppear() {
    self.opacity = 1.0
}

I can get the animation to work if the view is made visible via a button press that changes the value of the self.opacity, and I imagine the above methods would work in general if the control isn't meant to appear initially but gets inserted instead.

A: Here is possible solution (you can tune parameters to have desired effect)
Tested with Xcode 12.1 / iOS 14.1

struct DemoFadeInView: View {
    @State var isShown = false
    var body: some View {
        VStack {
            if isShown {
                Text("hey")
                     .transition(.opacity)
            }
        }
         .animation(Animation.easeInOut(duration: 1).delay(0.5))  // delay is optional, for demo
        .onAppear() {
             self.isShown.toggle()
        }
    }
}


text:
Q: Get model values with adding specific items in Laravel I'm using Laravel as an API, but have some troubles with getting posts with the specific updated value.
Here is my code. Any help to fix the code regarding both syntax and inefficiencies?
use Controller;
use Post;
use User;
use Comment;

class HomeController extends Controller{
    public function index(){
        $posts = $this->getPosts('home');

        return view('template', ['posts' = $posts]);
    }

    public function getPosts($slug){
        $posts = Post::where('slug', '=', $slug)->get();

        foreach($posts as &$post){
            $post->user = User::find($post->user_id);
            $post->comments = Comment::where('post_id', '=', $post->post_id)->get();

            foreach($post->comments as &$comment){
                $comment->user = User::find($comment->user_id);
            }
        }

        return $posts;
    }
}

Model
class Post extends Model
{

    protected $table = 'post';

    protected $primaryKey = 'post_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'html', 'slug', 'user_id'
    ];
}

A: If you define the relationships in your Models, your getPosts function could be reduced to just
$posts = Post::with(['user', 'comments.user'])->where('slug', $slug)->get();

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id');
    }
}

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function post()
    {
        return $this->belongsTo(Post::clsas, 'post_id');
    }
}

A: As suggested by other people that it would be nice if you could use relationships instead. However for your question about your code, I think the problem lies at the code below.
        $post->comments = Comment::where('post_id', '=', $post->post_id)->get();

$post->post_id should be $post->id instead.


text:
Q: Bind custom component store config to ViewModel store I'm writing a custom component in Ext JS which needs a store as a part of its configuration. I want to keep this store in the component's ViewModel, and I also want it to be bindable. Currently I have code like this:
Ext.define('CustomComponent', {
    extend: 'Ext.container.Container',
    xtype: 'customcomponent',
    viewModel: {
        type: 'customcomponent'
    },
    config: {
        store: 'ext-empty-store'
    },
    initComponent: function() {
        var store = Ext.getStore(this.getConfig('store'));
        this.lookupViewModel().set('myStore', store);
        this.callParent(arguments);
    }
});

Ext.define('CustomComponentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.customcomponent',
    data: {
        myStore: null
    }
});

This is not ideal for a number of reasons:

*

*The store config option isn't bindable.

*The store is contained in the data of the ViewModel, not the stores. This means it can't be accessed via the getStore method of the ViewModel.

To make the store bindable, I could write code like this:
Ext.define('CustomComponent', {
    extend: 'Ext.container.Container',
    xtype: 'customcomponent',
    viewModel: {
        type: 'customcomponent'
    },
    config: {
        store: 'ext-empty-store'
    },
    publishes: 'store'
});

Ext.define('CustomComponentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.customcomponent',
    data: {
        store: null
    },
    formulas: {
        myStore: function(get) {
            return Ext.getStore(get('store'));
        }
    }
});

This is not ideal either, though:

*

*The ViewModel is polluted with the store config, which is not necessarily an Ext.data.Store. It could be a store's ID or a config object. Essentially, it's an implementation detail, and I'd like to keep it out of the ViewModel where it will be inherited by every child component.

*The store is still not a part of the ViewModel's store configuration and so is still not accessible via getStore.

Essentially, I'm looking for a way to set up my View and ViewModel (and ViewController, if it would help) so that I can meet these three criteria:

*

*The store config on the view is bindable.

*The store config option is not kept in the ViewModel, or is somehow prevented from polluting the ViewModels of the component's children.

*The store in the ViewModel is accessible via getStore.

Is it possible to meet all three of these criteria simultaneously? If not, what is the most canonical way to transform a bindable store config into a ViewModel store? The Ext JS source code doesn't use the View-ViewModel architecture to define components, so I can't just look at what they do.

A: I believe you could use the store like this.
Ext.define('CustomComponentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.customcomponent',
    formulas: {
        myStore: function(get) {
            return Ext.getStore(get('store'));
        }
    },
    stores: {
        myStore: {
            fields: [
                {
                    name: 'id'
                },
                {
                    name: 'name'
                },
                {
                    name: 'description'
                }
            ]
        }},

});

Ext.define('CustomComponent', {
    extend: 'Ext.container.Container',
    xtype: 'customcomponent',
    viewModel: {
        type: 'customcomponent'
    },
    config: {
        bind: {
            store: '{myStore}'
        }
    }
});

A: After reading the Ext JS 6.0.2 source code more thoroughly, I have come to the conclusion that meeting all three criteria I want is not possible without overriding or subclassing Ext.app.ViewModel. I'll go through the criteria one by one, and then discuss what I think is the best current practice.
Criteria
The store config must be bindable
This is actually accomplished by default; all config options are bindable. What I had meant when I said the store must be bindable was "binding to the store config will update the store in my ViewModel". The value of the store config will be sent to the ViewModel if the publishes option is set appropriately, i.e. publishes: 'store'. This will send the raw value of the store config back to the ViewModel as store, though, which is not what we want. I think the cleanest way to work around this is via the applyConfigName template method provided for each config option. Here's an example:
Ext.define('CustomComponent', {
    extend: 'Ext.container.Container',
    xtype: 'customcomponent',
    viewModel: {
        type: 'customcomponent'
    },
    config: {
        store: 'ext-empty-store'
    },
    publishes: 'store',
    applyStore: function(store) {
        return Ext.getStore(store);
    }
});

The applyStore function will be applied to the value of store before it gets set, transforming it from a store ID or config object into an actual store. This brings us to the second criterion:
The store config option is not kept in the ViewModel
By using the applyStore template method we can keep the store config option out of our ViewModel. (Indeed, it even keeps it out of our View!) Instead the value of store which is published to our ViewModel is the actual store which it defines. Unfortunately, however, publishing config values adds them to the data object of the ViewModel, not the stores object. This brings us to the final criterion:
The store in the ViewModel is accessible via getStore
This criterion is currently impossible to satisfy. The reason is two-fold:
getStore retrieves only stores added via the stores config option
In Ext JS 6.0.2, getStore retrieves stores by looking them up in the storeInfo private property of Ext.app.ViewModel. The storeInfo property is itself set via the setupStore private method, which is called only on each member of the stores config.
The stores config option only allows config objects
Unlike the store config of Ext.grid.Panel, the stores config option of Ext.app.ViewModel only allows the values of each store to be config objects; Store IDs and actual stores are not permitted. Setting the value to a binding directly seems like it works, e.g.:
Ext.define('CustomComponentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.customcomponent',
    data: {
        dataStore: null
    },
    stores: {
        storeStore: '{dataStore}'
    }
});

But in actuality, the storeStore is a new Ext.data.ChainedStore which is configured with source: dataStore. This means that setting filters and sorters on storeStore will not affect dataStore, which is probably not what was desired.
The combination of these two restrictions means it is impossible to set a store in a ViewModel which can be retrieved with getStore.
So what should I do?
I think that with the available options, the best practice is to give up the ability to retrieve the store with getStore. While this is an annoying inconsistency, it is less likely to cause subtle bugs the way that allowing an implicit ChainedStore might. This gives us our final code:
Ext.define('CustomComponent', {
    extend: 'Ext.container.Container',
    xtype: 'customcomponent',
    viewModel: {
        type: 'customcomponent'
    },
    config: {
        store: 'ext-empty-store'
    },
    publishes: 'store',
    applyStore: function(store) {
        return Ext.getStore(store);
    }
});

Ext.define('CustomComponentViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.customcomponent',
    data: {
        store: null
    }
});


text:
Q: How to restore Regolith i3xrocks status bar Here is what I did to mess things up.  I followed the process of removing regolith as this was during an upgrade of Ubuntu 18 to 20.04

*

*Install regolith-desktop-complete with apt install regolith-desktop-complete

*The status bar had too many items so I started removing config files from /etc/regolith/i3xrocks/conf.d

*The status bar got really messed up so I deleted all files from /etc/regolith/i3xrocks/conf.d
I have followed the process to apt purge regolith and remove all i3xrocks related packages.  After reinstalling I still have an empty /etc/regolith/i3xrocks/conf.d directory and no status bar.
Could anyone advise on how to completely start from scratch with regolith desktop?   Thanks!

A: *

*I completely uninstalled Regolith using apt purge regolith-*

*Delete ~/.config/regolith

*Delete /etc/regolith

Reinstalled apt install regolith-desktop-complete now the status bar is back.


text:
Q: My Bukkit Timer runs once and when i do the command again it, its faster My Bukkit plugin does a timer that puts on armor, counts down and then removes armor then when i run it again the timer is faster? Why is this? I want users to be able todo the command multiple times without having to login again. Can someone help me?
    if(args[0].equalsIgnoreCase("BlackWing") )
        {
            final ItemStack[] oldarmor1;
            oldarmor1 = p.getInventory().getArmorContents();
            ItemStack ib = new ItemStack(Material.CHAINMAIL_BOOTS, 1);
            ib.addEnchantment(Enchantment.PROTECTION_FALL, 4);
            ib.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
            ItemStack il=new ItemStack(Material.CHAINMAIL_LEGGINGS, 1);
            il.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
            ItemStack ic = new ItemStack(Material.CHAINMAIL_CHESTPLATE, 1);
            ic.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
            ItemStack ih = new ItemStack(Material.CHAINMAIL_HELMET, 1);
            ih.addEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 1);
            ItemStack[] armors1 = { ib ,
              il,
              ic,
               ih};
            p.getInventory().setArmorContents(armors1);
            PotionEffect pe = new PotionEffect(PotionEffectType.JUMP, 600, 5);
            p.addPotionEffect(pe);
            ItemStack ironsword = new ItemStack(Material.IRON_SWORD,1);
            ironsword.addEnchantment(Enchantment.DAMAGE_ALL, 3);
            p.getInventory().setItem( 0,  ironsword);
            getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Runnable(){

                public void run(){

                    if (number != 0){

                        p.sendMessage(ChatColor.RED + "[FairyTail] " + ChatColor.GRAY + number + " seconds left");
                        number=number -1;
                    }else{
                        p.getInventory().setArmorContents(oldarmor1);

                    }
                    }

            }, 0L, 20L);

        }
        number=30;

A: Looking at the code snippet you provided, the scheduled task that counts down is never cancelled. The second time the command is executed by the same player, there will actually be two tasks running in the background, both decrementing number (amount of seconds) and therefore causing the countdown to be twice as fast. To fix this you could make sure that once the task is done counting down the seconds it gets cancelled. Writing a new class that extends BukkitRunnable might be really helpful in this case because these can cancel themselves (for example in the case when the 30 seconds are over).


text:
Q: How to get Wi-Fi on Ubuntu with secure boot enabled? I have installed Ubuntu 18.04 along side windows 10 on HP desktop. The Wi-Fi of the system works well on windows 10 , but on Ubuntu 18.04 it shows no wi-fi adaptor found. After going through internet I was able to get Wi-Fi on Ubuntu but for this I have to disable secure boot from BIOS settings. Is there any way to get Wi-Fi on Ubuntu 18.04 with secure boot enabled?
Desktop have Realtek drivers


text:
Q: ASP.NET C# scope issue OK, so I'm tyring to work with some simple stuff in ASP.NET and C# to get the hang of the super super basics, and I'm having trouble finding out how I can get this scope issue to work.  At least, I think it's a scope issue! :)
So, here is my Default.aspx presentation markup:
<%@ Page Language="C#" Inherits="project1.Tree" %>
<!DOCTYPE html>

    <title>project1_test</title>

    <form runat="server">

<asp:label runat="server" id="lblOutput" />

        <asp:TextBox ID="txtGrowBy" runat="server" />
        <asp:Button id="btnGrow" runat="server" Text="Grow!!!" />
    </form>

And here is my CodeBehind file:
using System;
using System.Web;
using System.Web.UI;

namespace project1
{
    public partial class Tree : System.Web.UI.Page
    {

        public int height = 0;

        public void Grow(int heightToGrow) {
            height += heightToGrow;
        }

        protected void Page_Load(Object Source, EventArgs E)
        {
            Tree tree1 = new Tree();

            string msg = "Let's plant a tree!
";

            msg += "I've created a tree with a height of " +
            tree1.height + " metres.
";

            lblOutput.Text = msg;
        }

        public virtual void btnGrowClicked (object sender, EventArgs args)
        {
            txtGrowBy.Text = tree1.heightToGrow;
        }

    }
}

Now, I believe the issue lies with the fact that I'm not using a getter and sender, but I'm not 100% sure.

A: I take it you're variable height is not being maintained between postbacks?
This is because the web is stateless. Your variables are not maintained between postbacks unless you store the values in Session, ViewState or Hidden Fields. So you could do the following to maintain your height value between PostBacks:
ASPX:
<form runat="server">
    <asp:HiddenField id="hd_Height" runat="server" />
</form>

Code Behind:
public int Height
{
    get
    {
       return int.Parse(hd_Height.Value).ToString();
    }
    set
    {
        hd_Height.Value = value.ToString();
    }
}

A: There's several immediate problems with your code; in the Page_Load method, you're creating a new Tree instance - you don't have to do this, as one was automatically created by IIS when the ASP.NET page was accessed. Use the this keyword in the Page_Load method to get access to that instance.
Further, nothing ever seems to call the Grow method; is this intentional? Shouldn't you be calling that from within the btnGrowClicked method?
And finally as GenericTypeTea points out, your height field won't be maintained between Postbacks. Easiest way to do this is with session state, eg:
private void PersistHeight(int height)
{
    this.Session["height"] = height;
}

private int RestoreHeight()
{
    return (int)this.Session["height"];
}

A: You could use viewstate as well (if Mono supports it); simply add the updated value to viewstate before giving control back to the browser. Then read from viewstate the original value saved in the last postback and incrementing the new value to it:
public int MyValue
{
   get {return Convert.ToInt32(viewstate["myVal"]);}
   set {viewstate["myVal"] = value;}
}
I hope that makes sense.


text:
Q: Scrolling NSString in NSView I'm using the method posted here to scroll an NSString across the screen. However, as shown in the image below, the string doesn't seem to be drawing correctly. Anyone have any ideas? Thanks.

EDIT: I forgot to mention that I modified the scrolling text class to use an attributed string rather than a regular string.
EDIT 2: I think the problem is that the string is repeating before it can finish the first time. How can I add some spacing before the string repeats itself?

A: Try clearing the area before drawing by adding
NSRectFillUsingOperation(dirtyRect, NSCompositeClear);

at the beginning of drawRect:.

A: I figured it out. I had to change this line in drawRect::
otherPoint.x += dirtyRect.size.width;

to
otherPoint.x += (stringWidth + 20.0);

EDIT: You can change 20.0 depending on how much of a gap you want before the string repeats.


text:
Q: Disallow Clang-Format From Messing With Comments I'm having trouble getting my clang-format to quite cooperate with multi-line comments. I have tried:
CodePragmas: '^[^ ]'

But this still results in the following. Before formatting:
class Test
{
/* =======
 * Public Functions
 * ======== */
public:
};

After formatting:
class Test
{
  /* =======
 * Public Functions
 * ======== */
public:
};

Any help would be greatly appreciated. Thanks.

A: I have a slightly different comment format, but same situation.  If you know the format of your block comments all use the same pattern, I think something like this will work:
CommentPragmas:  '/\* =======\n((.+\n.+)+)======== \*/'

If you want to exclude all multi-line block comments, I think this will work:
CommentPragmas:  '/\*(.+\n.+)+\*/'

I found that the ColumnLimit still applies to those comments, causing them to wrap in undesirable ways.  Otherwise, clang-format (3.8) leaves those blocks untouched.


text:
Q: How can I replace a start a Intent(Intent.ACTION_SENDTO) activity with org.jetbrains.anko.startActivity? I have read the artical https://github.com/Kotlin/anko/wiki/Anko-Commons-%E2%80%93-Intents
The Code A is to  open a send email activity,  I hope to replace it with org.jetbrains.anko.startActivity, how can I do? Thanks!
Code A
fun sendFeedbackByEmail(mContext: Context) {
    val data = Intent(Intent.ACTION_SENDTO)
    data.data = Uri.parse("mailto:" + mContext.getString(R.string.FeedbackEmailAddress))
    data.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.FeedbackEmailSubject))
    data.putExtra(Intent.EXTRA_TEXT, mContext.getString(R.string.FeedbackEmailFirstContent))
    mContext.startActivity(data)
}

A: You should not try to replace with the startActivity function. There is function available in Anko. It goes like this
email(email, [subject], [text])

Arguments in square brackets ([]) are optional. Methods return true if the intent was sent.
You can call it like
email("youremail@yourdomain.com","Your Subject","Your Text")

Right now  they don't have feature where you can send same email to multiple email id. You have to make another call.
Anki is achieving is by writing extension over Context and Fragment classes. So this function is available for both Activity and Function


text:
Q: How to recycle/reuse/continue Time Machine for a new Mac? I have been backing up a MacBook Pro to an external hard disk with Time Machine. I got a new laptop, used the firewire connector to pull the universe across to it, and started it up. It does not want to just pick up where I left off with the backups; it wants to start a new backup sequence and thus I need a ton of additional disk space.
Does anyone know a way to force it to just incrementally back up to the existing backup set?

A: It turns out that under Snow Leopard, Apple has allowed for this. When you turn on TM for the first time, it will ask you:

Would you like to reuse the backup [..] with this computer?
The backup was created on a different computer. If you reuse this backup it can no longer be used by the original computer.

I was mislead by the wording, but it turns out to mean just what's called for here: continuing the backup sequence on the new machine as if it were the old machine.

Image from blog.gerrior.com, in an article about logic board replacement (probably using the very same hard drive!)

A: This came up on Mac OS X Hints under the title 10.5: Repair Time Machine after logic board changes. Never tried it and I'm not sure if it would work on 10.6. Use with care.

A: Would comment, but I lack the rep...
bmargulies is correct about this function in Snow Leopard. It actually works quite well- when the logic board is changed, as described the MAC address of the network interface also changes, "breaking" the association w/ TM. In the case where the TM backup prefs are managed by Snow Leopard Server, you'll have to update the MAC address of the relevant computer record in Workgroup Manager before the machine with the new logic board will "remember" that its associated with Time Machine and popup the dialog mentioned by bmargulies.

A:  "Reconnecting"  to  your  backups article has very good information.


text:
Q: JavaScript event handler not working when second item is added to a div? So basically when I run this code it adds a button to a div and when you press the button it removes itself as expected.

document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>'
document.getElementById("remove").addEventListener("click", function () {
    document.getElementById("remove").remove();
});

However when you add two buttons X1 event handler stops working but X2 works fine?
I believe when the second button is added it some how effects there first button event handler but not sure why?

document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>'
document.getElementById("remove").addEventListener("click", function () {
    document.getElementById("remove").remove();
});

document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove2">X2</button>'
document.getElementById("remove2").addEventListener("click", function () {
    document.getElementById("remove2").remove();
});

A: innerHTML does not append instead reloads the full DOM. That's why the event does not work. You can use insertAdjacentHTML() instead:

document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>'
document.getElementById("remove").addEventListener("click", function () {
    document.getElementById("remove").remove();
});

document.getElementById("inputdiv").insertAdjacentHTML('beforeend', '<button type="button" id="remove2">X2</button>');
document.getElementById("remove2").addEventListener("click", function () {
    document.getElementById("remove2").remove();
});


text:
Q: Converter texto dentro de uma  em links com codigo! Tenho uma div com o seguinte aspecto

1
https://link1.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link2.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link3.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link4.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt

2
https://link1.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link2.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link3.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt
https://link4.com/qweeqweqw,https://segundolink.com/qweeqweqw.srt

queria transformar em algo do tipo abaixo... é possivel com php?
<?php
// codigo aqui
?>

1ª temporada
Episódio 1
Episódio 2
Episódio 3
<--!poderá ter mais de 24 episódios -->
Episódio 24

2ª temporada
Episódio 1
Episódio 2
Episódio 3
<--!poderá ter mais de 24 episódios -->
Episódio 24

A: Supondo que os links serão relativamente "seguidos", você pode utilizar um loop para gerar os finais de cada episódio em sequência. Veja o exemplo a seguir:

var i;

for (i = 1; i < 30; i++) {

  //Declarando variáveis
  var a = document.createElement('a');
  var linha = document.createElement("BR");
  var link = document.createTextNode("Episodio " + i);

  //Aplicando funções e descrições do link
  a.appendChild(link);
  a.title = "Episodio " + i;
  a.href = "http://www.examplo.com/episodio/" + i;
  a.insertBefore(linha, a.nextSibling); //Aqui você vai adicionar a quebra de linha após cada resultado do loop
  document.body.appendChild(a); //Aqui você vai gerar os links com todas as configurações acima

}


text:
Q: Laravel 5 routes ( couple non-required parameters) I need to make functionality, when action has two non-required parameters.
So action could be called like this:
site/man/process/age/30/weight/80,

site/man/process/age/30,

site/man/process/weight/80,

site/man/process/

I am trying to use route like this:
Route::get('man/process/age/{age?}/weight/{weight?}', 'ManController@process');

But have no success. Anybody knows how to do this correctly?
Thanks for any help and advise.

A: Route::get('man/process', 'ManController@process');
URL : /man/process?age=10&weight=20

A: I would take an entirely different approach to passing these variables via route parameters.
Consider sending a POST request with age and weight in the body of the request, then accessing these values in your controller with $request->all();
edit with example:
Route::post('man/process', 'ManController@process');
Then in your controller process() method:
process(Request $request)
{
  // Data in this case would contain age and weight
  $data = $request->all();
}

A: You can use GET request, And pass the parameters as query string.
Route::get('man/process', 'ManController@process');
URL : /man/process?age=10&weight=20

Or use POST Request and pass along the stuff you want to receive:
public function getData(Request $request)
{
  // Data in this case would contain age and weight
  $data = $request->all();
}


text:
Q: How do I fetch data from a database, in MATLAB, with where clause using "and" operator? conn= database ('test', '  ' , '  ');
sql = ' SELECT * from  table1 WHERE column1= value1 and column2 = value2';
results = fetch(conn, sql);
results

This piece of code gives output as follows
results = [ ]


text:
Q: How to pass child class into controller in spring-mvc? I have a parent class and its child in my application model.
And have the following controller method:
@RequestMapping(method=RequestMethod.POST, value="/page")
public String postMethod(Model model, Parent obj, BindingResult result) {
     // do something
}

but I want it to be able to handle instances of the child class, that was posted by form.
How can I do this?

A: You can create an object of required type as an implicit model attribute:
@ModelAttribute("parent")
public Parent createChild(@RequestParam("type") String type) {
    if ("foo".equals(type)) return new Foo();
    else if ("bar".equals(type)) return new Bar();
    else return null;
}

Since Spring doesn't remember type of the object passed to the form automatically, you need to do it yourself, by adding a hidden form field whose value specifies type of the object (a type field in the example above).
Another option is to avoid creating object from scratch by storing it in a session. It can be configured using @SessionAttributes annotaton, see 15.3.2.9 Specifying attributes to store in a session with @SessionAttributes.


text:
Q: How to use the binary push notifications format by C? I use the The Push Notification Binary Interface cmd=2
This is format :

Q1: Can I send some device_id in one frame? For example:
item id = 1 , device_tocken #1
item id = 1 , device_tocken #2
item id = 1 , device_tocken #3
item id = 2 , message
item id = 3 ...
 and etc
Q2: How I can receive the response error ?

The documentation said: If you send a notification that is accepted by APNs, nothing is returned.
If I make SSL_read after SSL_write and package was accepted by APNs, the program is waiting in SSL_read command.
r = SSL_write(ssl, out_buffer, size);
int len = SSL_read(ssl, in_buff, 6);

If I read from ssl channel into single thread - I have segmentation fault.
Q3: Do You know the link to example of use this protocol?

A: *

*It's not clear from the documentation, but I don't think you can send multiple device tokens in the same frame, simply because if you get an error response of an invalid device token, you won't be able to know which device token it refers to. If, on the other hand, your frame contains a single device token and a single message identifier, then an error response containing that message identifier will tell you exactly which message caused the error.

*You should use a non-blocking read for attempting to read the error response. I don't know how you write that in C, but there must be a way to specify some timeout or to call a read method that specifies a timeout. If there is nothing to read, the method will return after the timeout is elapsed.

*The APNS docs contain samples for sending notifications in the older formats (0 and 1). I suggest you use format 1 (which supports error responses), since I don't see any advantage of using the newer format 2.


text:
Q: One of my Browserify modules is not recognizing another

var gulp = require('gulp'),
    order = require('gulp-order'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    concat = require('gulp-concat'),
    jshint = require('gulp-jshint'),
    notify = require('gulp-notify'),
    uncss = require('gulp-uncss'),
    purify = require('gulp-purifycss'),
    sourcemaps = require('gulp-sourcemaps'),
    browserSync = require('browser-sync').create(),

    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),

    paths = {
        HTML: 'app/*.html',
        SCSS: 'app/_scss/main.scss',
        JS: 'app/_js/*.js',
        tsHTML: 'app/REPSuite/web/static/',
        tsCSS: 'app/REPSuite/web/static/css/modules/',
        tsJS: 'app/REPSuite/web/static/js/',
};

/*
gulp.task('browserify', function() {
    return browserify('./app/_js/main')
        .bundle()
        //Pass desired output filename to vinyl-source-stream
        .pipe(source('main.js'))
        // Start piping stream to tasks!
        .pipe(gulp.dest('./app/REPSuite/web/static/js/'));
});
*/

gulp.task('scripts', function() {
    return browserify('./app/_js/main')
        .bundle()
        .pipe(jshint.reporter('fail'))
//        .pipe(concat('main.js'))
        .pipe(source('main.js'))
        .pipe(streamify(sourcemaps.init()))
        .pipe(streamify(sourcemaps.write('.')))
        .pipe(gulp.dest(paths.tsJS))
        //.pipe(streamify(uglify()))
        //.pipe(gulp.dest(paths.tsJS))
        .pipe(notify({
            message: 'Scripts task complete'
        }));
});

gulp.task('copy-html', function() {
    gulp.src('./app/index.html')
        // Perform minification tasks, etc here
        .pipe(gulp.dest('./app/REPSuite/web/static'));
});

gulp.task('uncss', function() {
    gulp.src('app/REPSuite/web/static/css/main.css')
        .pipe(uncss({
            html: ['./app/index.html']
        }))
        .pipe(gulp.dest('./out'));
});

gulp.task('purify-css', function() {
  return gulp.src('app/REPSuite/web/static/css/main.css')
    .pipe(purify(['./app/_js/*.js', './app/index.html']))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('styles', function() {
    return sass('app/_scss/main.scss', {sourcemap: true, style:'expanded'})
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .on('error', function(err) {
            console.error('Error!', err.message);
        })
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(paths.tsCSS))
        .pipe(browserSync.stream())
        .pipe(notify({
            message: 'Styles task complete'
        }));
});

gulp.task('js-watch', ['scripts'], browserSync.reload);

gulp.task('serve', ['styles', 'scripts'], function() {

    browserSync.init({
        server: "./app"
    });
    gulp.watch('app/_scss/main.scss', ['styles']);
    gulp.watch('app/_js/*.js', ['js-watch']);
    gulp.watch(paths.HTML).on('change', browserSync.reload);
});

gulp.task('default', ['serve']);

I am using gulp with browserify and I am loading jquery just fine, however I am loading a library which depends on jquery and I am getting a Uncaught ReferenceError: jQuery is not defined
This is my main.js file:
var $ = require('jquery');
    mixitup = require('./../bower_components/mixitup/build/jquery.mixitup.min.js');

Strange thing is in my output file I can see the jQuery library!
What am I missing?

A: This was the syntax used which solved the error:
var $ = jQuery = require('jquery');
var mixitup = require('./../bower_components/mixitup/build/jquery.mixitup.min.js');


text:
Q: How can I get the session values from an external.js by using Struts2 jQuery I need to recover a value from session in my external JS. Before, I did it in a script embedded in the JSP with this lines and it worked properly:
$(window).load(function(){
    var selectedServer = "<s:property value='%{#session.selectedServer}'/>";
    var selectedMarket = "<s:property value='%{#session.selectedMarket}'/>";
});

but now, I want to do it from an external JS and an alert(selectedServer); after these lines, show me the literal: <s:property value='%{#session.selectedServer}'/>, but not the value.
Is the syntax different in an external.js?

A: You can use javascript global variables in the external script, or use function parameters to pass the values that you should obtain in the JSP to the external function.
<script>
    var selectedServer = "<s:property value='%{#session.selectedServer}'/>";
    var selectedMarket = "<s:property value='%{#session.selectedMarket}'/>";
</script>

function(selectedServer, selectedMarket){
}


text:
Q: Selenium WebDriver - Ruby Assert Statement Sorry for the obvious Noob question. I am trying to confirm a certain piece of text is on the page.
HTML:

Please provide a little more information about your enquiry

I am using the following assert statement
Then(/^The website should show the following error message "([^"]*)"$/) do |website_error|
  SuccessMessage = driver.find_element(:class,"errormsg")
  website_error.eql? SuccessMessage.text
end

From the following step:
Then The website should show the following error message "Please provide a little more information about your enquiry"

When I run this it passed. If I change the step to:
Then The website should show the following error message "Please provide a little more information about your enquiry00000"

It also passes. Am I missing something here? I cannot seem to find an ASSERT EXACT Text

A: Then(/^The website should show the following error message "([^"]*)"$/) do |website_error|
  SuccessMessage = driver.find_element(:class,"errormsg")

expect(website_error).to eq(SuccessMessage.text)


text:
Q: Wordpress custom taxonomy page I've got a question that I've seen being asked before, but none of the answers solved my problems. It's something I've run into before, but never managed to solve.
I've got a clean Wordpress installation and in the functions.php file I've created a custom post type
register_nav_menu('main', 'Main navigation menu');

function add_custom_post_type() {
    $labels = array(
        'name' => _x('Books', 'post type general name'),
        'singular_name' => _x('Book', 'post type singular name'),
        'add_new' => _x('Add New', 'book'),
        'add_new_item' => __('Add New Book'),
        'edit_item' => __('Edit Book'),
        'new_item' => __('New Book'),
        'all_items' => __('All Books'),
        'view_item' => __('View Book'),
        'search_items' => __('Search Books'),
        'not_found' =>  __('No books found'),
        'not_found_in_trash' => __('No books found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => __('Books')
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'has_archive' => true,
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
    );

    register_post_type('book', $args);
}

I've made an archive-book.php and single-book.php template files for those and everything works okay. I can view the books when I go to "http://localhost/wordpress/book"
Now I want to create a custom taxonomy, so I did this in functions.php as well:
add_action('init', 'add_custom_post_type');

function add_custom_taxonomy() {
    register_taxonomy(
        'rating',
        'book',
        array(
            'label' => 'Rating',
            'hierarchical' => true,
            'show_ui' => true,
            'query_var' => 'book',
            'has_archive' => true,
            'rewrite' => array(
                'slug' => 'book/rating'
            )
        )
    );
}

And the taxonomy shows up in the admin page, I can add new terms, and add them to books. But now comes the problem. I've I want to go to an overview of all books with, let's say, rating "nice", I would go to "http://localhost/wordpress/book/rating/nice". I've created the following template files: taxonomy-rating-nice.php, taxonomy-rating.php and taxonomy.php.
But somehow wordpress just shows the index.php file and doesn't list any books.
I've tried flushing the rewrite rules with:
add_action('init', 'custom_taxonomy_flush_rewrite');
function custom_taxonomy_flush_rewrite() {
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

And:
flush_rewrite_rules(false);

But nothings seems to help.
So, anybody who can help me? If you need more information, please tell, cause I really want to fix this problem!

A: You have a few issues -

*

*You're setting query_var to 'book' in your custom taxonomy, which is clashing with the query var for your custom post type. change that to true and it will default to the name of the taxonomy, 'rating'.

*There is no has_archive argument for register_taxonomy, though this is probably not effecting anything. This makes sense if you think about it, since a taxonomy term is always a form of archive.

*The last issue you may encounter is one of precedence - if multiple rewrite rules apply to a given URL, the one with highest precedence will be chosen. If you register your post type first, then your taxonomy, using your example http://localhost/wordpress/book/rating/nice, WordPress will think you want to load an attachment named nice belonging to a book named rating. If you register your taxonomy first, then register your post type, your taxonomy will take precedence in this case and everything should work as expected.


text:
Q: Measure how Straight/Smooth the Text Borders are Rendered in an Image I have two images:

I want to measure how straight/smooth the text borders are rendered.
First image is rendered perfectly straight, so it deserves a quality measure 1. On the other hand, the second image is rendered with a lot of variant curves (rough in a way) that is why it deserves a quality measure less than 1. How will I measure it using image processing or any Python function or any function written in other languages?
Clarification :
There are font styles that are rendered originally with straight strokes but there are also font styles that are rendered smoothly just like the cursive font styles. What I'm really after is to differentiate the text border surface roughness of the characters by giving it a quality measure.
I want to measure how straight/smooth the text borders are rendered in an image.
Inversely, it can also be said that I want to measure how rough the text borders are rendered in an image.

A: I don't know any python function, but I would:
1) Use potrace to trace the edges and convert them to bezier curves. Here's a vizualisation:

2) Then let's zoom to the top part of the P for example:

You draw lines perpendicular to the curve for a finite length (let's say 100 pixels). You plot the color intensity (you can convert to HSI or HSV and use one of those channels, or just convert to grayscale and take the pixel value directly) over that line:

3) Then you calculate the standard deviation of the derivative. Small standard deviation means sharp edges, large standard deviation means blurry edges. For a perfect edge, the standard deviation would be zero.
4) For every edge were you drew a perpendicular line, you now have a "smoothness" value. You can then average all the smoothness values per edge, per letter, per word or per image, as you see fit. Also, the more perpendicular lines you draw, the more accurate your smoothness value, but the more computationally intensive.

A: I would try something simple like creating a 'roughness' metric using a few functions from the opencv library, since it's easy to work with in Python (and C++, as well as other wrappers).
For example (without actual source, since I'm typing on my phone):

*

*Preprocess to create binary images (many standard ways).

*Use cv2.findContours to get outlines of the letters.

*Use cv2.arcLength on each contour as denominators.

*Use cv2.approxPolyDP to simplify each contour.

*Use cv2.arcLength on each simplified contour as numerators.

*Calculate ratios of simplified over full arc lengths.

In step 5, ratios closer to 1.0 require less simplification, so they're presumably less rough. Ratios closer to 0.0 require a lot of simplification, and are therefore probably very rough. Of course, you'll have to tweak the contour finding code to get appropriate outlines to work with, and you'll need to manage numerical precision to keep the math calculations meaningful, but hopefully the idea is clear enough.
OpenCV also has the useful functions cv2.convexHull and cv2.convexityDefects that you might find interesting in related work. However, they didn't seem appropriate for the letters here, since internal features on letters like M for example would be more challenging to address.
Speaking of rough things, I admit this algorithmic outline is incredibly rough! However, I hope it gives you a useful idea to try that seems straightforward to implement quickly to start getting quantitative feedback.

A: One idea might be simply to get the average of the number of vertices per character in Python/OpenCV using cv2.CHAIN_APPROX_SIMPLE.
Since you have the same characters and you want to know how straight they are, the CHAIN_APPROX_SIMPLE measures only horizontal and vertical corner vertices. For your first image, there should be much fewer vertices than for your second image.

CHAIN_APPROX_SIMPLE compresses horizontal, vertical, and diagonal
  segments and leaves only their end points. For example, an up-right
  rectangular contour is encoded with 4 points.

import cv2
import numpy as np

# read image
img = cv2.imread('lemper1.png')
#img = cv2.imread('lemper2.png')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# invert
thresh = 255 - thresh

# get contours and compute average number of vertices per character (contour)
result = img.copy()
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
num_contours = 0
sum = 0
for cntr in contours:
    cv2.drawContours(result, [cntr], 0, (0,0,255), 1)
    num_vertices = len(cntr)
    sum = sum + num_vertices
    num_contours = num_contours + 1

smoothness = (sum / num_contours)
print(smoothness)

# save resulting images
cv2.imwrite('lemper1_contours.png',result)
#cv2.imwrite('lemper2_contours.png',result)

# show thresh and result
cv2.imshow("thresh", thresh)
cv2.imshow("contours", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

First image average number of vertices: 49.666666666666664

Second image average number of vertices: 179.14285714285714

So smaller number of vertices means straighter characters.

A: Preface
There's a few nice ideas presented here based around the properties of the character contours as polylines. Whilst there is some inherent flaws in this approach due to them being a function of resolution and scale, I would like to offer one further interruption of the same. My algorithm is still susceptible but it may offer a different perspective.
Theory
The method I propose is to compare common characters by the number of inflections in their contours. In this context, what I mean by inflection, is a sign change between the cross products of successive polyline segments as vector. For example; consider a polyline contour of a circle, starting at the mid y coordinate and the x+ most coordinate. If we were to trace the polyline contour CW (clockwise) around the perimeter, each line segment would be incrementally a CW transform of the prior. If at any time a segment turned "away" or "outwards", this transform would be CCW (counter-clockwise) and the cross product will invert. A "rough" circle will therefore have inflections, a "perfect" or "smooth" circle will have none.
Algorithm
The algorithm follows the steps below using the Emgu.CV. C# code below that:

*

*The images are loaded and converted to binary by means of thresholding

*The binary images then undergo contour detection and these contours are sort by their bounding box, left to right, so and their indices match the occurrence order of the character they contour.

*Each contour is then re-pointed to an equal number of segments in order to normalize for scale and resolution differences between images/characters.

*Each contour is "walked" and its number of inflections counted.

// [Some basic extensions are omitted for clarity]
// Load the images
Image<Rgb, byte> baseLineImage = new Image<Rgb, byte>("BaseLine.png");
Image<Rgb, byte> testCaseImage = new Image<Rgb, byte>("TestCase.png");
// Convert them to Gray Scale
Image<Gray, byte> baseLineGray = baseLineImage.Convert<Gray, byte>();
Image<Gray, byte> testCaseGray = testCaseImage.Convert<Gray, byte>();
// Threshold the images to binary
Image<Gray, byte> baseLineBinary = baseLineGray.ThresholdBinaryInv(new Gray(100), new Gray(255));
Image<Gray, byte> testCaseBinary = testCaseGray.ThresholdBinaryInv(new Gray(100), new Gray(255));
// Some dilation required on the test image so that the characters are continuous
testCaseBinary = testCaseBinary.Dilate(3);

// Extract the the contours from the images to isolate the character profiles
// and sort them left to right so as the indicies match the character order
VectorOfVectorOfPoint baseLineContours = new VectorOfVectorOfPoint();
Mat baseHierarchy = new Mat();
CvInvoke.FindContours(
    baseLineBinary,
    baseLineContours,
    baseHierarchy,
    RetrType.External,
    ChainApproxMethod.ChainApproxSimple);
var baseLineContoursList = baseLineContours.ToList();
baseLineContoursList.Sort(new ContourComparer());

VectorOfVectorOfPoint testCaseContours = new VectorOfVectorOfPoint();
Mat testHierarchy = new Mat();
CvInvoke.FindContours(
    testCaseBinary,
    testCaseContours,
    testHierarchy,
    RetrType.External,
    ChainApproxMethod.ChainApproxSimple);
var testCaseContoursList = testCaseContours.ToList();
testCaseContoursList.Sort(new ContourComparer());

var baseLineRepointedContours = RepointContours(baseLineContoursList, 50);
var testCaseRepointedContours = RepointContours(testCaseContoursList, 50);

var baseLineInflectionCounts = GetContourInflections(baseLineRepointedContours);
var testCaseInflectionCounts = GetContourInflections(testCaseRepointedContours);

Inflection Detection/Counting
static List<List<Point>> GetContourInflections(List<VectorOfPoint> contours)
{
    // A resultant list to return the inflection points
    List<List<Point>> result = new List<List<Point>>();

    // Calculate the forward to reverse cross product at each vertex
    List<double> crossProducts;
    // Points used to store 2D Vectors as X,Y (I,J)
    Point priorVector, forwardVector;
    foreach (VectorOfPoint contour in contours)
    {
        crossProducts = new List<double>();
        for (int p = 0; p < contour.Size; p++)
        {
            // Determine the vector to the prior to this vertex
            priorVector = p == 0 ?
            priorVector = new Point()
            {
                X = contour[p].X - contour[contour.Size - 1].X,
                Y = contour[p].Y - contour[contour.Size - 1].Y
            } :
            priorVector = new Point()
            {
                X = contour[p].X - contour[p - 1].X,
                Y = contour[p].Y - contour[p - 1].Y
            };

            // Determine the vector to the next vector
            // If this is the lst vertex, loop back to vertex 0
            forwardVector = p == contour.Size - 1 ?
            new Point()
            {
                X = contour[0].X - contour[p].X,
                Y = contour[0].Y - contour[p].Y,
            } :
            new Point()
            {
                X = contour[p + 1].X - contour[p].X,
                Y = contour[p + 1].Y - contour[p].Y,
            };

            // Calculate the cross product of the prior and forward vectors
            crossProducts.Add(forwardVector.X * priorVector.Y - forwardVector.Y * priorVector.X);
        }

        // Given the calculated cross products, detect the inflection points
        List<Point> inflectionPoints = new List<Point>();
        for (int p = 1; p < contour.Size; p++)
        {
            // If there is a sign change between this and the prior cross product, an inflection,
            // or change from CW to CCW bearing increments has occurred. To and from zero products
            // are ignored
            if ((crossProducts[p] > 0 && crossProducts[p-1] < 0) ||
                (crossProducts[p] < 0 && crossProducts[p-1] > 0))
            {
                inflectionPoints.Add(contour[p]);
            }
        }
        result.Add(inflectionPoints);
    }
    return result;
}

Output
L: Baseline Inflections:0 Testcase Inflections:22
E: Baseline Inflections:1 Testcase Inflections:16
M: Baseline Inflections:4 Testcase Inflections:15
P: Baseline Inflections:11 Testcase Inflections:17
E: Baseline Inflections:1 Testcase Inflections:10
R: Baseline Inflections:9 Testcase Inflections:16

Contours (Blue) and Inflections (Red)


text:
Q: 404 Error on Activate / Deactivate Plugin I have a standard WP install (3.5.1) and am trying to activate a new plugin (WP Super Cache) however each time I try to activate it, I get my site's 404 error page... which is strange as it's the same page (wp-admin/plugins.php) as the plugin list page I'm activating from, but with a query string. Stranger still is that I cannot deactivate, or activate any of my other plugins?!?
I haven't changed the .htaccess file or made any changes to the permalink structure and can't seem to nail down what is going on?
There doesn't seem to be any resource on this anywhere; anyone have any ideas?
Any help would be greatly appreciated!

A: For anyone running into a similar problem, it came down to a plugin conflict; in my case Capability Manager Enhanced and Access which is part of the Toolset plugin. Unfortunately no error_log of /var/log/httpd log files were generated as it was an internal permissions conflict within WordPress.
If you find yourself in this situation, simply FTP / SSH into the server and rename / delete the plugin you don't want from the /wp-content/plugins/ directory and reload your Admin -> Plugins page.
I hope this helps someone!


text:
Q: How can I move my RSS Feeds folder in Outlook 2010? When I try dragging my RSS Feeds folder in Outlook 2010 to a local PST file I get a message saying "Special and default folders cannot be moved".
I need to move it as it is taking up too much space in my mailbox on the server. What other options are there?

A: Quite easy really - File - Account Settings - RSS Feeds tab.
duh


text:
Q: jsf make backing bean method synchronized i have a method in backing bean that adds a product in to db. it checks if product is duplicate. however, it's a slow process and JSF UI could fire multiple requests at same time, and it fails to check duplicate when adding stuff in db due to multiple thread run this application at same time. what's best way to make this method thread safe. make it as a synchronized method?
public int addProduct(final ActionEvent event){
// check duplicates code....long process
// insert product in db code....long process
}

A: Do not make it synchronized in the following cases - it will either have no effect (request-scoped bean) or will kill your application (application-scoped bean). For a session-scoped bean it won't have significant side-effects.
But usually the way to counter this is to disable the UI component that fires the request.


text:
Q: How to increment a variable every time the user inputs data? I have a program that prompts a user for integers until they type a value to continue the program onto the next step. How would I increment a variable called count every time the user inputs an integer? I'm using count++ to increment the count amount by the way, I just don't know how to make it go up when the user puts in data.
Code so far
//variables
        int num, count = 0, high, low;
        Scanner userInput = new Scanner(System.in);

        //loop

        do {
                    System.out.print("Enter an integer, or -99 to quit: --> ");
                    num = userInput.nextInt();

                    high = num;
                    low = num;

                    //higher or lower
                    if(count > 0 && num > high)
                    {
                       high = num;
                    }
                    else if(count > 0 && num < low)
                    {
                        low = num;
                    }
                    else
                    {
                       System.out.println("You did not enter any numbers.");
                    }

                } while (num != -99);

        System.out.println("Largest integer entered: " + high);
        System.out.println("Smallest integer entered: " + low);

A: You can put count++; anywhere in your do loop.

A: It's simple. Just put count++ inside the while loop as follows,
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);

// loop
do {
   System.out.print("Enter an integer, or -99 to quit: --> ");
   num = userInput.nextInt();

   count++; // here it goes

   high = num;
   low = num;

   // higher or lower
   if(count > 0 && num > high)
   {
      high = num;
   }
   else if(count > 0 && num < low)
   {
      low = num;
   }
   else
   {
       System.out.println("You did not enter any numbers.");
   }

} while (num != -99);

System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);

A: I understand why you're using it but why use the counter at all?
The code below uses a different technique to acquire integers from the User. It also ensures that the supplied number is indeed a integer that falls within the Integer.MIN_VALUE and Integer.MAX_VALUE range:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();

int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
    System.out.print("Enter an integer, (q to quit): --> ");
    input = userInput.nextLine().toLowerCase();
    if (input.equals("q")) {
        if (low == Integer.MAX_VALUE) {
            low = 0;
        }
        break;
    }
    if (!input.matches("^-?\\d+$")) {
        System.err.println("Invalid Entry (" + input + ")! "
                         + "You must supply an Integer (int) value!" + ls);
        input = "";
        continue;
    }

    boolean invalidInteger = false;
    long tmpVal=0;
    try {
        tmpVal = Long.parseLong(input);
    } catch(NumberFormatException ex) {
        invalidInteger = true;
    }
    if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
        System.err.println("Invalid Entry (" + input + ")! " + ls
                         + "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
                         + "  Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
                         + "You must supply an Integer (int) value!" + ls);
        input = "";
        continue;
    }
    num = Integer.parseInt(input);
    if (num > high) {
        high = num;
    }
    if (num < low) {
        low = num;
    }
    input = "";
}
System.out.println("Largest integer entered:  " + high);
System.out.println("Smallest integer entered: " + low);

If you want to keep track of how many entries the User made then you can still apply a counter if you like.


text:
Q: bootstrap text inside div always at the bottom I have the following HTML using bootstrap in my code.

name_of_item

 quick_summary

            £ price

            Add To Wish List

                Check It Out

And i have the top div (image_div) height defined as below
    .image_div{
    height: 450px;
     }

In the above code, i want the inside div with "bottom" class to always to stay at the bottom of the top div (image_div). Please suggest, how i can achieve this?

A: I think the proper solution would be to position the bottom div absolute. Something like this:
.bottom {
    position: absolute;
    bottom: 0;
}

You will also have to set the position of the image_div to relative to make it work, as the position absolute needs to know what it should use as a reference for positioning.
There are properties like vertical-align: bottom, but I would advise against them as they require you to use display: table-cell and/or other ugly css.
edit:
To make the price appear to the top I would change this:

    £ price

into this:
£ price

and then position it absolute in the same way:
.price {
 position: absolute;
 top: 0;
 right: 0;
 display: block:
}

I am also pretty sure the .row-fluid on the bottom div is not required.


text:
Q: Solving integral (expectation) with indicator function I would like to learn how to solve integrals with indicator functions of the type
$$ E[X \cdot I_{ \{X\ge2 \}}] = \int_0^4 \frac{1}{4} [X \cdot I_{ \{X\ge2 \}}] dX $$
where $E$ the expectation function and $X$ a uniform random variable with $X \sim U(0,4)$.
From a paper I derive the solution as 1.5. What is the correct way of arriving at this result, and to address integrals like these involving the indicator function. Thank you.

A: $$ E[X \cdot I_{ \{X\ge \eta \}}] = \frac{1}{4} \int_{2}^{4} X dX = \frac{1}{8} (4^2 - 2^2) = \frac{12}{8} = 1.5. $$
We can do this with the limits of integration since the random variable $X$ is $0$ when it is less than $2$, which is shown in the indicator function.

A: After comment by @Rumpelstiltskin the answer follows as
$$ E[X \cdot I_{ \{X\ge2 \}}] = \int_2^4 \frac{1}{4} X \ dX $$
which evaluates to 1.5. More generally
$$ E[X \cdot I_{ \{X\ge \eta \}}] = - \frac{1}{8} \eta^2 + 2$$
where $X \sim U(0,4)$.


text:
Q: How does Python 3 buffer big int objects? When reading the CPython source code of Python 2, we can find PyIntBlock in intobject.c.
In Python 3, there is no intobject.c, integer objects are created by longobject.c. In this file, we can find small int buffer pool small_ints, which is the same as small_ints in Python 2.
However, I can't find something like PyIntBlock. And here is the question: how does Python 3 buffer big integer objects? If there is no such mechanism in Python 3, will it be slow?


text:
Q: Setting a static (constant) POST parameter with netflix feign I'm using a REST api that requires a few fields to be set. My application should always set some of the fields to the same value. Is it possible to make those values "hard coded" in the interface with the feign definition (or somewhere else)?
My feign declaration looks like the example. Let's say I always want to use the same agent from this application. Is that doable?
@RequestLine("POST /files")
@Headers("Content-Type: application/json")
default FileMetadata addFile(@Param("file_name") String fileName,
                             @Param("agent") String agent,
                             @Param("md5") String md5,
                             @Param("file_type") String fileType) {
    return new FileMetadata.Builder().build();
}

A: You have different alternatives, in the case you are using the Spring Annotations you could use defaultValue annotation property to determine the default value
@RequestParam(value = "agent", required = false, defaultValue = "AnyAgent") String agent

But in the case you are using the netflix-feign annotations, and seems it is what you are doing, you would need to add in the path, i.e. in the @RequestLine annotation:
static final String DEFAULT_VALUE_AGENT = "agent";
@RequestLine("POST /files?agent=" + DEFAULT_VALUE_AGENT)
....

But if you are refering to Body POST, you could do it using annotation @Body:
@RequestLine("POST /files")
@Body("%7B\"file_name\": \"{user_name}\", \"agent\":  \"" + DEFAULT_VALUE_AGENT  +"\"%7D") //... other params..
....

Edit
Based on the Github repository documentation, if you are using Java 8, you could do a default method which calls the other method with a param constant. Just like next
@RequestLine("POST /files")
@Headers("Content-Type: application/json")
FileMetadata addFile(@Param("file_name") String fileName,
                         @Param("agent") String agent,
                         @Param("md5") String md5,
                         @Param("file_type") String fileType);

@RequestLine("POST /files")
@Headers("Content-Type: application/json")
default FileMetadata addFileConstant(@Param("file_name") String fileName,
                         @Param("md5") String md5,
                         @Param("file_type") String fileType) {
    addFile(fileName, "constant_value", md5, fileType);
}

Personally, I think is more flexible than the other options I proposed before. And the idea works in POST Body as well if they are params.

A: I had the same situation.
The problem is solved as follows:
added this to the main api on the server that I was knocking on (i.e., on the receiving side, and not on the sending side request).
for example:
@RequestParam(value = "code", required = false, defaultValue = "AAA") String code

Required is required = false (instead of required = true).


text:
Q: Bibliography does not appear In my .tex document I have
[...]
\nocite{*}
\bibliographystyle{amsplain}
\bibliography{bibliografie}

\end{document}

And I have the bibliografie.bib file in the same folder. However, why the bibliography does not appear at the end of the document?
And bibliografie.bib contains the following:
@BOOK{texbook,
   author = "Donald E. Knuth",
   title= "The {{\TeX}book}",
   publisher = "Addison-Wesley",
   year = 1984
   }

@BOOK{latexbook,
   author = "Leslie Lamport",
   title = "{\LaTeX \rm:} {A} Document Preparation System",
   publisher = "Addison-Wesley",
   year = 1986
   }

A: In my case it was fault of editing tool. I was using TexMaker and it did not showed bibliography, because it was not enabled in build settings (preferences). Hope this helps somebody using TexMaker.

A: I had the exact same problem as you, and was already doing what the other answers suggest doing.
I'm using TexMaker, and found that the problem was the option 'Use a "build" subdirectory for output files', found in the tab 'Commands' in the "Configure TexMaker" dialog window. When checked, all the citations appear as question marks, and the bibliography doesn't show. After I unchecked it, citations started working and the bibliography appeared.

A: The following minimal example works well.
\RequirePackage{filecontents}
\begin{filecontents*}{bibliografie.bib}
@BOOK{texbook,
   author = "Donald E. Knuth",
   title= "The {{\TeX}book}",
   publisher = "Addison-Wesley",
   year = 1984
   }

@BOOK{latexbook,
   author = "Leslie Lamport",
   title = "{\LaTeX \rm:} {A} Document Preparation System",
   publisher = "Addison-Wesley",
   year = 1986
   }

\end{filecontents*}
\documentclass[english]{amsbook}
\usepackage{babel}
\usepackage{blindtext}

\begin{document}
\tableofcontents
\Blinddocument
\nocite{*}
\bibliographystyle{amsplain}
\bibliography{bibliografie}
\end{document}

Please learn how to create a minimal example.

A: As far as I am aware, you have to include some other content (in this case an invisible \mbox).
\documentclass{article}
\begin{document}
\mbox{}
\nocite{*}
\bibliographystyle{amsplain}
\bibliography{bibliografie}
\end{document}


text:
Q: Conditionally Required Fields MS Access I have been digging for answers on this all day and I can't seem to find a good answer. I am no good with VBA and I am certain there is a solution to my problem if I could figure out how to use VBA, but for now I am hopeful there is a simpler solution.
I have a lookup field called Incidents.Incident Type and a few other fields that I want to be populated on the same table when the Incidents.Incident Type field is equal to a certain value.
I have tried within the table properties, variations of
([Incident Type] In ("Value")) Or ([Required Field] Is Not Null)

but this trips an error.
The multi-valued field " cannot be used in a WHERE or HAVING clause.

Any thoughts about this? I am desperate at this point lol
Thanks! :)

A: The question is light on information.  It appears you have selected a multi-valued field based on the error message and that is typically not recommended.  Here is a link that provides further explanation on the topic:
Multivalued Fields a Good Idea?
Assuming that Incident Type is stored as text (single value), you can accomplish what you are looking for by using a validation rule.  The following will require that the required field be populated for Value1 and Value3 incidents:
[Incident Type] NOT IN ('Value1', 'Value3') OR [Required Field] IS NOT NULL


text:
Q: navigation Prop is missing for this navigator 3 The navigation Prop is missing for this navigator. In react-navigation 3 you must set up your navigation more directly. I took a look at the documentation regarding this but I'm still having trouble figuring out how I will implement this into my code. What is it that I am doing wrong and how would I fix it. Please provide some assistance.
This is my RootStack.js
import React from 'react';
import { createStackNavigator, createSwitchNavigator } from 'react-navigation';
import SignInScreen from './App/screens/SignInScreen';
import Account from './App/screens/Account';
import Inventory from './App/screens/Inventory';
import Settings from './App/screens/Settings';
import SignUp from './App/screens/SignUp';
import ForgotScreen from './App/screens/ForgotScreen';
import Tournament from './App/screens/Tournament';
import TournamentRsvp from './App/screens/TournamentRsvp';
import Shop from './App/screens/Shop';
import Game from './App/screens/Game';

const routes = {
  SignInScreen: {
    screen: SignInScreen
  },
  Account: {
    screen: Account
  },
  Tournament: {
    screen: Tournament
  },
  TournamentRsvp: {
    screen: TournamentRsvp
  },
  Shop: {
    screen: Shop
  },
  Game: {
    screen: Game
  },
  SignUp: {
    screen: SignUp
  },
  ForgotScreen: {
    screen: ForgotScreen
  },
  Settings: {
    screen: Settings
  },
  Inventory: {
    screen: Inventory
  }
};

class AuthLoadingScreen extends React.Component {
  constructor() {
    super();
  }
}

const AppStack = createStackNavigator(routes, {
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false
  },
  initialRouteName: 'SignInScreen'
});
const AuthStack = createStackNavigator(
  {
    SignInScreen: {
      screen: SignInScreen
    }
  },
  {
    headerMode: 'none',
    navigationOptions: {
      headerVisible: false
    }
  }
);

export default createSwitchNavigator(
  {
    AuthLoading: AppStack,
    App: AppStack,
    Auth: AuthStack
    // AuthLoading: AppStack,
    // Auth: AuthStack
  },
  {
    initialRouteName: 'AuthLoading'
  }
);

This is my App.js below
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import * as firebase from 'firebase';
import { createStackNavigator, createSwitchNavigator } from 'react-navigation';
import { firebaseConfig } from './config.js';
import RootStack from './RootStack';

firebase.initializeApp(firebaseConfig);

export default class App extends React.Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <RootStack />
      </View>
    );
  }
}

A: Try to wrap in createAppContainer.
import { createAppContainer, createStackNavigator } from 'react-navigation';

export default createAppContainer(createSwitchNavigator(
  {
    AuthLoading: AppStack,
    App: AppStack,
    Auth: AuthStack
    // AuthLoading: AppStack,
    // Auth: AuthStack
  },
  {
    initialRouteName: 'AuthLoading'
  }
));


text:
Q: Configuring PHP Memcached sessions for clustering I already had a look to a few posts about this but can't get it to work
I have 2 ubuntu servers, for testing, I installed the following:
apt-get install memcached
apt-get install apache2
apt-get install php5
apt-get install libapache2-mod-php5
apt-get install php5-memcached

my /etc/memcached.conf has
Server 1
-m -p 11211 -l 192.168.0.1

Server 2
-m -p 11211 -l 192.168.0.2

my /etc/php5/apache2/php.ini
Server 1
session.save_handler = memcached
session.save_path = "192.168.0.1:11211,192.168.0.2:11211"

Server 2
session.save_handler = memcached
session.save_path = "192.168.0.2:11211,192.168.0.1:11211"

and my small test on both /var/www/
session_start();

echo "Session save_handler is: ".ini_get("session.save_handler")."
";
echo "Session save_path is: ".ini_get("session.save_path")."
";

if(isset($_SESSION['KEY']))
{
echo "KEY found: ".$_SESSION['KEY'];
}
else
{
$_SESSION['KEY'] = 'test';
echo 'KEY set to: '.$_SESSION['KEY'];
}

It works for each individual server, meaning it does save the session. But i do not get the session "copy" in the opposite server (it starts a new session no matter what)
I really don't know if I have a whoopsie on the test code or if I'm missing a conf. I also tried memcache (withouth d) and adding tcp:// to the paths, but the result is the exact sth
Update:
To be more clear, I want my session to be saved on both servers, the problem is it only saves on their local memcqched, never on the remote one. According to http://www.php.net/manual/en/memcache.ini.php it should be working

A: Memcached does not replicate data onto each server. You can increase memcache storage capacity by adding additional memcache servers, but it does not replicate.  If you want that functionality you should look into repcached.
http://repcached.lab.klab.org/.


text:
Q: Drupal 7 LDAP module and AD global catalog Does anybody successfully authenticate against AD global catalog using http://drupal.org/project/ldap? I've got the following configuration:

LDAP server:
ldaps://service.mydomain.com
LDAP port:
3269
Binding Method:
Service Account Bind
Base DNs for LDAP users:
DC=service,DC=mydomain,DC=com
DC=otherdomain,DC=mydomain,DC=com
AuthName attribute:
userPrincipalName

The module successfully authenticate users, which are members of parent domain called "service", but LDAP search can't find any user from "otherdomain", which is connected to parent domain inside AD domain forest. I´m able to test LDAP search using ldp.exe and using this tool I can find any user from any domain.
Also, there is the following error message in the Drupal watchdog:
ldap_search() function error. LDAP Error: Referral, ldap_search() parameters: ldap_search() call: base_dn: DC=otherdomain,DC=mydomain,DC=com, filter = (userPrincipalName=somebody@otherdomain.mydomain.com), attributes: , attrsonly = 0, sizelimit = 0, timelimit = 0, deref = , scope = 3
Any help will be greatly appreciated.

A: The LDAP client should follow the referral that is being returned in the search result - or an LDAP directory proxy server should be installed to automatically follow referrals.
When the LDAP directory server was unable or unwilling to perform the search operation, it may return a referral indicating that another server may be able to perform the requested operation. It is the responsibility of the LDAp client to "chase" referrals. Referrals are indicated by the presence of the referral field and the search result code being set to 10.

A: You have to write: ldaps://ldapserver:3269 in the LDAP server field and keep the same port number in LDAP port field.


text:
Q: Express with Q deferred not responding to requests I'm trying to use a node backend with my angular script using Q to promise-fy an fs method. Using the normal callback method works, however here, nothing is returned to Angular. Nothing is printed in the console, and no error is returned in the console or in the terminal where node is running. What have I missed?
var express = require('express');
var app = express();
var router = express.Router();
var FS = require('fs');
var Q = require('q');

app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/dist', express.static(__dirname + '/dist'));

app.get('/', function(req, res) {
    res.sendfile('./index.html');
});

app.get('/test', function(req, res){
    // res.send('asdf')
    var deferred = Q.defer();
    FS.readFile("gulpfile.js", "utf-8", function (error, text) {
        console.log('error', error);
        console.log('in read file')
        if (error) {
            deferred.reject(new Error(error));
        } else {
            res.send(text);
            deferred.resolve(text);
        }
    });
    return deferred.promise;
});

app.listen(5000);

A: Express does not support promises out of the box. Returning a promise from a handler means nothing to it. You still have to call res.send explicitly (although there are modules such a express-promise to ease this).
This is what your code should look like:
app.get('/test', function(req, res){
    var promise = Q.ninvoke(FS, "readFile", "gulpfile.js", "utf-8");
    promise.then(function (text) {
        res.status(200).send(text);
    }, function(error) {
        console.error(error);
        res.status(500).send("oops");
    });
});