text:
Q: SAPUI5 bind element without backend call I have a SAPUI5 app with two views. One overview page with a smart table and a details page that also contains a smart table. When navigating from overview to detail page I am binding the detail view to a context with:
oView.bindElement("Product(1)");
In the smart table of the detail view product details should be displayed which are available over a Navigation Property.
"Product(1)/ProductDetails"
The problem is that now two sequential backend calls will be triggered. One from the bindElement and the other one is triggert from the smart table.
Is there any possibility to not trigger a backend call when binding the view or can that call be deferred and executed in parallel with the one from the smart table?

A: I think it's good to separate the backend calls (not put them in the same batch), so that you can have the detail view ready, without waiting for the Smart Table to retrieve the results of the smart table of the detailed view.
However, if you do want to batch all the backend calls, just have a look on class sap.ui.model.odata.v2.ODataListBinding. It's used by the smart table of the detail page. You can use the parameter batchGroupId to specify that you want the request to be bundled in the specified batch. Use the same batch that the one used in bindElement.
Changing the batch of the Smart Table should be possible in callback routine of onBeforeRebindTable, if you do:
oEvent.getParameter("bindingParams").parameters.batchGroupId = "MyBatch"


text:
Q: List of distinct types without casting to common superclass How do I store objects in a list, but have them retain their original type? Without being casted to their common superclass.
So that the below code can work:
using System;
using System.Collections.Generic;

public class Test
{
    public static void Main(string[] args)
    {
        var list = new List<Super>()
        {
            new Type1 { Number = 1, Info = "infomatin" },
            new Type2 { Number = 2, Prop = "propty" }
        };
        foreach (var t in list)
        {
            Doer.Do(t);
        }
    }
}

public class Super
{
    public int Number { get; set; }
}

public class Type1 : Super
{
    public string Info { get; set; }
}

public class Type2 : Super
{
    public string Prop { get; set; }
}

public static class Doer
{
    public static void Do(Type1 arg)
    {
        Console.WriteLine($"Got type 1 with {arg.Info}");
    }

    public static void Do(Type2 arg)
    {
        Console.WriteLine($"Got type 2 with {arg.Prop}");
    }
}

Wanted output:
Got type 1 with infomatin
Got type 2 with propty

Actual output, compiler error:
Test.cs(15,21): error CS1503: Argument 1: cannot convert from 'Super' to 'Type1'

I could do this inside the foreach
if (t instanceof Type1)
    Doer.Do((Type1) t);
else if (t instanceof Type2)
    Doer.Do((Type2) t);

But I don't want to have to write so much code. Especially as I add more subclasses of Super.
I would like to have to add only an additional method to my Doer to handle the new type, then the rest is taken care of.

A: You can use pattern matching, with only one Do() method
public static void Do(Super arg)
{
    switch(arg)
    {
        case Type1 t1:
            Console.WriteLine($"Got type 1 with {t1.Info}");
            break;
        case Type2 t2:
            Console.WriteLine($"Got type 2 with {t2.Prop}");
            break;
        default:
            throw new NotSupportedException();
    }
}

As far as avoiding casting, I feel you have misunderstood how C# works. When you store in a base class, the memory contents are still the of the derived class and there is not casting in the sense of copying data from one type to another
This type of operation does not involve any data copy
Super obj = new Type1();

Neither does this
Type1 t1 = (Type1)obj;

It just the reference t1 putting on a different "mask" than obj, and the data behind the mask is the same.
Edit 1
A any casting (of the form (type)value in C#) is cast that might include a conversion or not. Some examples where obj is if type object, sup is of type class Super, t1 is of type class Type1 : Super and t2 is of type class Type2 : Super.

*

*No conversion, or identity casts

*

*obj = sup;

*sup = t1;

*sup = t2;

*sup = t1; t1 = (Type1)sup;

*obj = t1; sup = (Super)obj;

*obj = t1; sup = (Type1)t1;
The code below requires the following custom conversion code to be added to Type1 and Type2 respectively.
public static implicit operator Type1(Type2 t2) => new Type1() { Info = t2.Prop };
public static explicit operator Type2(Type1 t1) => t1.Info.StartsWith("prop") ? new Type2() { Prop = t1.Info } : throw new NotSupportedExpection();

*

*Implicit Conversion casts (data copy, may fail)
 {   // Implicit conversion Type2 -> Type1
     object obj = new Type2() { ID = 2, Prop = "propval" };
     Type1 t1 = (Type2)obj;
 }

*Explicit Conversion casts (data copy, may fail)
 {
     // Explicit conversion Type1 -> Type2
     object obj = new Type1() { ID = 1, Info = "propInfo" };
     Type2 t2 = (Type2)(Type1)obj;
 }

Read https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions. for more accurate information.

A: If you find yourself using switch/case and casting, there's a good chance you're doing it wrong. With a properly designed object model, it shouldn't be necessary.
For example
abstract public class Super
{
    public int Number { get; set; }
    public abstract void Do();
}

public class Type1 : Super
{
    public string Info { get; set; }

    public override void Do()
    {
        Console.WriteLine($"Got type 1 with {this.Info}");
    }
}

public class Type2 : Super
{
    public string Prop { get; set; }

    public override void Do()
    {
        Console.WriteLine($"Got type 2 with {this.Prop}");
    }
}

Now you can just do this in your loop:
public static void Main(string[] args)
{
    var list = new List<Super>()
    {
        new Type1 { Number = 1, Info = "infomatin" },
        new Type2 { Number = 2, Prop = "propty" }
    };
    foreach (var t in list)
    {
        t.Do();
    }
}

The above is consistent with Tell, Don't Ask which is a traditional object-oriented philosophy.
If you are worried about separation of concerns (for example, you don't want your classes to have knowledge of "Console") then you can inject the external functionality:
abstract public class Super
{
    public int Number { get; set; }
    public abstract void Do(Action<int> action);
}

public class Type1 : Super
{
    public string Info { get; set; }

    public override void Do(Action<int> action)
    {
        action(this.Info);
    }
}

public class Type2 : Super
{
    public string Prop { get; set; }

    public override void Do(Action<int> action)
    {
        action(this.Prop);
    }
}

public static void Main(string[] args)
{
    var list = new List<Super>()
    {
        new Type1 { Number = 1, Info = "infomatin" },
        new Type2 { Number = 2, Prop = "propty" }
    };
    foreach (var t in list)
    {
        t.Do( x => Console.WriteLine("The value that we're interested in is {0}", x));
    }
}

There is one more situation which may apply here (based on your comments). Let's say you have "clean" DTO objects that have no methods, and you don't want to add any for whatever reason, e.g. maybe the DTOs are code-generated and you can't modify them. This is actually a common situation (I like methodless DTOs too).
To make the situation more real, let's use more meaningful examples. Let's say you have a variety of objects that might contain an end user's name, but with various different identifiers:
abstract public class Super
{
}

public class Type1 : Super
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Type2 : Super
{
    public string FullName { get; set; }
}

The temptation here is to write a switch case like this:
foreach (var t in list)
{
    switch (t)
    {
         case Type1 type1 : Console.WriteLine("Name is {0} {1}", type1.FirstName, type1.LastName);
         case Type2 type2: Console.WriteLine("Name is {0}", type2.FullName);
         default:
             throw new InvalidOperationException();
    }
}

The problem here is that runtime throw, which will occur any time someone adds a different object type but doesn't remember to update your switch statement. This might not be a problem, but it also might be a huge problem, e.g. if your DTOs are held in a separate library from your Do processor and you would rather not have to update both at the same time (which could be a deployment concern under certain architectures).
What is missing here is a business concept of "Name" agnostic of where it came from. Somewhere, some code has to translate these various objects into something that has a name, and preferably that logic would be encapsulated somewhere.
That's where I would use an adapter class.
class NameHolder
{
    public string FullName { get; }

    public NameHolder(Type1 type1)
    {
        this.FullName = type1.FirstName + " " + type1.LastName;
    }

    public NameHolder(Type2 type2)
    {
        this.FullName = type2.FullName;
    }
}

With the addition of this missing business concept, the logic become very simple:
public static void Main(string[] args)
{
    var list = new List<NameHolder>()
    {
        new NameHolder(new Type1 { Number = 1, Info = "infomatin" }),
        new NameHolder(new Type2 { Number = 2, Prop = "propty" })
    };
    foreach (var t in list)
    {
        Do(t.FullName);
    }
}

Notice the lack of throw. The advantage of this approach is that all types are resolved at compile time, so if you forget to add logic to map the proper fields, you will get a compile time error, which you can detect and fix immediately.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgres composite PK where one component is sequence different for each value of other field Let's say I have a a_table with following fields:

*

*id_a: bigint

*id_b: int

*some_third_value: text

I'd like to create a composite primary key on id_a and id_b so that id_a would be a sequence, but it would be a different sequence depending on the value of id_b and this all would work automatically with inserts. So lets say I would insert:
insert into a_table (id_b, some_third_value) values (1, 'Hello');
insert into a_table (id_b, some_third_value) values (1, 'World');
insert into a_table (id_b, some_third_value) values (2, 'Me here!');

Then the resulting rows would be:
id_a|id_b|some_third_value
1   |1   |Hello
2   |1   |World
1   |2   |Me here!

And every time I'd insert a new row with a new id_b which is not present before, it would create a new sequence for this new id_b's id_a.
Can this be done? And if it can be done then is it a bad idea if let's say I had few million rows in that table and few hundred different id_b's?


text:
Q: Can't Xcode7.1 code sign with certificate? When I run my project with device in Xcode 7 & 7.1. There is a dialog tips to input the private key password,after that, another dialog tips code sign confirm like this page .
The Problem is the buttons in this dialog don't work except for "Refuse". In that I can't run my project on my device.
Is that a bug of Xcode?

A: You can try as follow steps.

*

*Open the "钥匙串访问"

*Find the "privateKey"

*Right Click the key

*Open the "访问控制"

*"允许所有应用程序访问此项目"


text:
Q: List sorting except specific element I made nested list
information = [['name', 'age', 'sex', 'height', 'weight'], ['sam', '17', 'm', 155, 55], [...]] to make table.

and I want to sort data according to height. but when I use .sort() method, because of information[0], this error message comes out
"TypeError: '<' not supported between instances of 'float' and 'str'"

how can I sort data except first element?

As you can see first picture, i made table to see in excel file.
ans I want to sort elements according to G column. (this is the code of movie info)
but when I tried sorting using sort(), because the top element is "러닝타임+평점"(str type), sorting is not able.

A: You can use sorted with the 4th element as key on a slice of information that doesn't hold the headers
information[1:] = sorted(information[1:], key=lambda x: x[3])

A: if using of pandas library is acceptable then you can do this
create as dataframe.
import pandas as pd
df = pd.DataFrame(information)

# make the first row as column names
headers = df.iloc[0]
# create a updated dataframe with those new column names
updated_df = pd.DataFrame(df.values[1:], columns=headers)

# sort the values based on height
updated_df.sort_values('height', inplace=True)


text:
Q: How to modify (correct) values that are poorly written in a DataFrame with python I have a csv file that contains values that are badly written.
I want to correct these mistakes. for example replace Toyouta by toyota, maxda by mazda, in the column named carCompany. .
The job I need to do is to predict the car price using these independent variables

A: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
eg.
>>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
...                    'B': [5, 6, 7, 8, 9],
...                    'C': ['a', 'b', 'c', 'd', 'e']})
>>> df.replace(0, 5)
   A  B  C
0  5  5  a
1  1  6  b
2  2  7  c
3  3  8  d
4  4  9  e

df.replace('Toyouta','toyota')

should work.


text:
Q: Fixing proof that if $\overline{A}\cap B=A\cap\overline{B}=\varnothing$, there exists $U,V$ such that $A\subset U$ and $B\subset V$ I tried to prove the following theorem:

Let $X$ be a metric space and $A,B\subset X$. Suppose that $\overline{A}\cap B=A\cap\overline{B}=\varnothing$. Then there exists two disjoint open sets $U$ and $V$ such that $A\subset U$ and $B\subset V$.

My proof was the following:

If $a\in A$, there exists $r_a>0$ such that $B(a,r_a)\cap B=\varnothing$. Otherwise, we would have $a\in\overline{B}$. (We could construct a sequence in $B$ that converges to $A$.) Similarly, if $b\in B$, there exists $r_b>0$ such that $B(b,r_b)\cap A=\varnothing$. Let
      $$\;\;U=\bigcup_{a\in A}B(a,\epsilon r_a) \;\text{ et }\; V=\bigcup_{b\in B} B(b,\epsilon r_b),$$
      where $\epsilon>0$ will be chosen later. Clearly, $A\subset U$ and $B\subset V$. If $U\cap V$ were not empty, there would exist $x\in B(a,\epsilon r_a)\cap B(b,\epsilon r_b)$, where $a\in A$ and $b\in B$. So, by the triangular inequality:
      $$d(a,b)\leq d(a,x)+d(b,x)<\epsilon(r_a+r_b).$$
      Since $a\notin \overline{B}$, $d(a,B)>0$. However, if we take $\epsilon=d(a,B)/(r_a+r_b)$ we have
      $$f_B(a)\leq d(a,b)<\epsilon (r_a+r_b)=f_B(a),$$
      which is absurd!

Now, I realised that I cannot take such $\epsilon$ since $a$ and $b$ depend on it. It seems intuitive to me that every $0<\epsilon<1$ would work but I can't figure out how to prove it.

A: Your proof is almost fine, but however it does not work for any $\varepsilon \in ]0,1[$ : in $\mathbb{R}$, take $A=\{0\}$ and $B=\{1\}$. Then you can have $r_0=r_1=1$, but with $\varepsilon > \frac{1}{2}$, the open sets $B(0,\varepsilon\cdot r_0)$, $B(1,\varepsilon\cdot r_1)$ are not disjoint !
To make your proof correct : note that it works with $\varepsilon\in ]0,\frac{1}{2}]$.
Indeed, it would give you at the end of your proof $d(a,b)<\frac{1}{2}(r_a+r_b)$, but by definition, $A$ does not intersect $B(b,r_b)$, so you have $d(a,b) \ge r_b$ and similarly $d(b,a) \ge r_a$.
This gives you $d(a,b) < d(a,b)$ : absurd.

A: As a remark into general topology: being able to separate such sets $A$ and $B$ by open sets, is called being "completely normal" and in all spaces this is equivalent to the fact that all subspaces of $X$ are normal (hereditarily normal). See e.g. here or here.
And as all metrisable spaces are normal, and all subspaces of metrisable spaces are metrisable, all metrisable spaces are hereditarily normal so completely normal: we can separate all $A$ and $B$ with $\overline{A} \cap B = \emptyset = A \cap \overline{B}$ by disjoint open sets.


text:
Q: How to make CustomScrollView has 2 or multiple row Right now my solution is using a combination of SliverToBoxAdapter, Row, and ShrinkWrappingViewport to make the layout I want.
return CustomScrollView(
  slivers: [
    SliverToBoxAdapter(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Flexible(
            flex: 2,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ShrinkWrappingViewport(
                slivers: _renderContent(context, main),
                offset: ViewportOffset.zero(),
              ),
            ),
          ),
          Flexible(
            flex: 1,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ShrinkWrappingViewport(
                slivers: _renderContent(context, sidebar),
                offset: ViewportOffset.zero(),
              ),
            ),
          ),
        ],
      ),
    ),
    Footer(),
  ],
);

Is there any elegant solution or sliver adapter that can be used as an alternative to row in CustomSrollView?

A: TLDR – use this widget, it takes two slivers as arguments which will be shown in the row layout
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class TwoSideSliver extends MultiChildRenderObjectWidget {
  final double leftSize;
  final Widget left;
  final Widget right;

  TwoSideSliver({
    super.key,
    required this.leftSize,
    required this.left,
    required this.right,
  }) : super(children: [left, right]);

  @override
  _RenderTwoSideSliver createRenderObject(BuildContext context) {
    return _RenderTwoSideSliver(leftSize: leftSize);
  }

  @override
  void updateRenderObject(BuildContext _, _RenderTwoSideSliver renderObject) {
    renderObject.leftSize = leftSize;
  }
}

extension _TwoSideParentDataExt on RenderSliver {
  /// Shortcut for [parentData]
  _TwoSideParentData get twoSide => parentData! as _TwoSideParentData;
}

class _TwoSideParentData extends SliverPhysicalParentData
    with ContainerParentDataMixin<RenderSliver> {}

class _RenderTwoSideSliver extends RenderSliver
    with ContainerRenderObjectMixin<RenderSliver, _TwoSideParentData> {
  _RenderTwoSideSliver({required double leftSize}) : _leftSize = leftSize;

  double get leftSize => _leftSize;
  double _leftSize;

  set leftSize(double value) {
    if (_leftSize == value) return;
    _leftSize = value;
    markNeedsLayout();
  }

  @override
  void setupParentData(RenderSliver child) {
    if (child.parentData is! _TwoSideParentData) {
      child.parentData = _TwoSideParentData();
    }
  }

  RenderSliver get left => _children.elementAt(0);

  RenderSliver get right => _children.elementAt(1);

  Iterable<RenderSliver> get _children sync* {
    RenderSliver? child = firstChild;
    while (child != null) {
      yield child;
      child = childAfter(child);
    }
  }

  @override
  void performLayout() {
    if (firstChild == null) {
      geometry = SliverGeometry.zero;
      return;
    }

    left.layout(
      parentUsesSize: true,
      constraints.copyWith(crossAxisExtent: leftSize),
    );

    right.layout(
      parentUsesSize: true,
      constraints.copyWith(
        crossAxisExtent: constraints.crossAxisExtent - leftSize,
      ),
    );

    right.twoSide.paintOffset = Offset(leftSize, 0);

    if (left.geometry!.scrollExtent > right.geometry!.scrollExtent) {
      geometry = left.geometry;
    } else {
      geometry = right.geometry;
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (!geometry!.visible) return;
    context.paintChild(left, offset);
    context.paintChild(right, Offset(offset.dx + leftSize, offset.dy));
  }

  @override
  bool hitTestChildren(
      SliverHitTestResult result, {
        required double mainAxisPosition,
        required double crossAxisPosition,
      }) {
    for (final child in _childrenInHitTestOrder) {
      if (child.geometry!.visible) {
        final hit = child.hitTest(
          result,
          mainAxisPosition: mainAxisPosition,
          crossAxisPosition: crossAxisPosition - child.twoSide.paintOffset.dx,
        );

        if (hit) return true;
      }
    }
    return false;
  }

  Iterable<RenderSliver> get _childrenInHitTestOrder sync* {
    RenderSliver? child = lastChild;
    while (child != null) {
      yield child;
      child = childBefore(child);
    }
  }

  /// Important!
  /// Otherwise Widgets like [Slider] or [PopupMenuButton] won't work even
  /// though the rest of Widget will work (like [ElevatedButton])
  @override
  void applyPaintTransform(RenderSliver child, Matrix4 transform) {
    child.twoSide.applyPaintTransform(transform);
  }
}

Well, it's not really a Row analog because it doesn't support Flex widgets (Flexible, Expanded), but you still can use two different slivers in a row layout and combine them as many times as you wish.
Though you need to provide size to the left one, which can be either hardcoded or calculated based on SliverLayoutBuilder's constraints
Here's the live example https://dartpad.dev/?id=d8513c8d6438e628f7efa6e7866983ee
P.S. I tested it only for vertical lists and only from top to bottom direction so in a reversed list could be strange behavior.
Feel free to modify this solution to provide better support for described scenarios.


text:
Q: The scale factor of $\Lambda$CDM as a function of time From Friedmann equation for flat universe:
$$
\left(\frac{\dot{a}}{a}\right)^2= \frac{8\pi G}{3} ~~ \left( \rho_m + \rho_r + \rho_\Lambda \right),
$$
can we simply get the scale factor $a$ as a function of time?
I'm following this thread
numerically solving for cosmological scale factor..
But there's the Hubble constant $H_0$, whose value is given in units of GeV by $\sim 10^{-42}$. I think this is the value we should substitute by in the Friedmann equation to have units balance, since in natural units GeV equivalent for $s^{-1}$, and $[\frac{\dot{a}}{a}]= s^{-1}$.
But this value is so small!! Will we get the right scale factor so, even in eV it's $H_0\sim 10^{-33}$ , this means we will get $a(t)$ multipled by this small factor!
Also in the first answer of the thread they say:

You should use  $H_0$ in terms of its normal units, $[H] = kms^{-1}Mpc^{-1}$. Or simply $H_0 \approx 70 km/s/Mpc$.

Any help to understand that is appreciated!

A:
Dr. phy asked: "can we simply get the scale factor $\rm a$ as a function of time?"

For the complete solution containing $\rm \Omega_{r}, \ \Omega_{m}, \ \Omega_{\Lambda}$ simultaneously you have to integrate numerically, but since at all stages of the universe only one or two components dominate while at least one component can be neglected you can use the analytical 1- and/or 2-component solutions for the specific times and glue them together where their values approach each other.
The full solution where you set your neglible components to $0$ and solve for $\rm a $ is
$$\rm \frac{\dot{a}}{a}=H=H_0 \sqrt{\Omega_{r}/a^4+\Omega_{m}/a^3+\Omega_{k}/a^2+\Omega_{\Lambda }}$$
For the purely radiation dominated era right after the big bang you get ↘
$$ \rm a=\sqrt{2 \ H_{0} t} \ \Omega_{r}^{1/4} $$
When matter becomes relevant too we have two solutions, the first is ↘
$$ \rm a=(-i \left(\sqrt{3}-i\right) \sqrt[3]{\sqrt{3} \ \Omega_{m} \left| f-4 \ \Omega_{r}^{3/2}\right|  \sqrt{H_{0} \ t \left(f-8 \ \Omega_{r}^{3/2}\right)}+f^2-8 \ f \ \Omega_{r}^{3/2}+8 \ \Omega_{r}^3}$$
$$ \rm +(4 \ i \left(\sqrt{3}+i\right) \Omega_{r}^2)/(\sqrt[3]{\sqrt{3} \  \Omega_{m} \left| f-4 \ \Omega_{r}^{3/2}\right|  \sqrt{H_{0} \ t \left(f-8  \ \Omega_{r}^{3/2}\right)}+f^2-8 \ f \ \Omega_{r}^{3/2}+8 \ \Omega_{r}^3})$$
$$ \rm +2 \left(1+i \ \sqrt{3}\right) \Omega_{r}+2 \left(1-i \ \sqrt{3}\right) \Omega_{r})/(4 \ \Omega_{m})$$
The 2nd solution is valid for the 2nd part of the radiation and matter dominated era ↘
$$ \rm a=(\sqrt[3]{\sqrt{3} \ \Omega_{m} \left| f-4 \ \Omega_{r}^{3/2}\right|  \sqrt{H_{0} \ t \left(f-8 \ \Omega_{r}^{3/2}\right)}+f^2-8 \ f \ \Omega_{r}^{3/2}+8 \ \Omega_{r}^3}$$
$$ \rm +\frac{4 \ \Omega_{r}^2}{\sqrt[3]{\sqrt{3} \ \Omega_{m} \left| f-4 \ \Omega_{r}^{3/2}\right|  \sqrt{H_{0} \ t \left(f-8 \ \Omega_{r}^{3/2}\right)}+f^2-8 \ f \ \Omega_{r}^{3/2}+8 \ \Omega_{r}^3}}+2 \ \Omega_{r})/(2 \ \Omega_{m})$$
When radiation becomes neglible and matter alone dominates we have ↘
$$ \rm a=\left(\frac{3}{2}\right)^{2/3} \ (H_{0} \ t)^{2/3} \ \Omega_{m}^{1/3} $$
When dark energy and matter play together it becomes ↘
$$ \rm a=\sqrt[3]{\frac{1}{\Omega_{\Lambda} }-1} \ \sinh ^{2/3}\left(3 \ H_{0} \ t \ \sqrt{\Omega_{\Lambda} }/{2} \right)$$
The function $\rm f$ which was used for brevity  is
$$ \rm f = 3 \ H_{0} \ t \ \Omega_{m}^2$$
Since the radiation dominated era is so short, on a linear plot the last equation for $\rm a$ is good enough if you don't zoom in on the first few million years.
On a logarithmic plot however it makes a difference if you also show the early times. The $\rm x$-axis is $\rm t$ in years, $\rm y$ is the dimensionless scale factor $\rm a$:

The two component solution is not exact and with my method it deviates about $\rm 0.1 \% $ from the numerical solution (so on a diagram you won't see any difference larger than a pixel on a monitor). Right after the big bang the numerical solution is more exact though, the oscillations in the deviation come from the numerical integration, see the deviation
$$\rm |1-\frac{a_{analytic}}{a_{numeric}}|$$

The numerical precision depends on your method and computional ressources, but at some point when $\rm t$ is small enough the analytical solution will be better, since the radiation really dominates at very small $\rm t$.


text:
Q: Is this an error in htaccess or apache config? I was using xampp before but switch to individual setup for php-mysql. In my xampp everything works perfectly. But when I migrated my code to my new setup I can't login to my application.
This is the step
1. http://localhost/login - //user input username & password
2. http://localhost/login/validate_credentials - //error occurred URL NOT FOUND:     localhost/login/validate_credentials

I traced the problem this what I found out. If I add index.php before the 1st segment(http://localhost/index.php/login/validate_credentials) in my uri I am now able to login. But what is really mess up is I can't access all my other methods without adding index.php first. So I guess my problem is my htaccess.
This is my htaccess:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php/$1 [L]

I enabled the mod_rewrite in my http.conf. In my xampp 1.7.3 all my methods works without index.php.

A: try this:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>


text:
Q: MySQL dynamic JOIN Let's say that I have these tables on my db:
items
categories
weapons
shields
swords

And I need to create a join like this:
SELECT items.*, {swords}.*
FROM items
INNER JOIN categories
  ON categories.id = items.category_id # <-- here I know that the item is a sword
INNER JOIN {swords}
  ON {swords}.item_id = item.id
WHERE items.id = 12

But the {swords} part is dynamic since I found that an item is a sword checkgin the categories.name field.
The query will change if the categories.name is "shield" to this:
SELECT items.*, shields.*
FROM items
INNER JOIN categories
  ON categories.id = items.category_id
INNER JOIN shields
  ON shields.item_id = item.id
WHERE items.id = 13

I used { and } around the swords to show it like a variable
Thank you for your answer and sorry about my english! :)

A: Technically, you can only do this with dynamic SQL - which means MySQL's Prepared Statement syntax, or string concatenation to create the query prior to submitting it to the database.  Prepared Statements are the preferable choice, due to better SQL injection defense.
You could use LEFT JOINs to the various tables, but it would mean including numerous columns from each of the tables (weapons, shields, swords...) that would be null if the category didn't match.  It'd be horrible to try to pull out data from a single query...
PS: Why is there a SWORD table?  Wouldn't that be covered by the WEAPON table?


text:
Q: PostgreSQL - Before Update Trigger determine which columns were updated I have a table with many columns.
Need to find which columns value have changed.
I am using the following code. I am having a performance problem.
Can I do this with a different method?
   CREATE OR REPLACE FUNCTION public.mytable()
      RETURNS trigger AS $$
    DECLARE
      _rec record;
    BEGIN
      FOR _rec IN
        SELECT
          o.key
          , o.value AS old_value
          , n.value AS new_value
        FROM json_each(to_json(new)) n
          INNER JOIN json_each(to_json(old)) o ON o.key = n.key
      LOOP
        IF (_rec.old_value::text IS DISTINCT FROM _rec.new_value::text) THEN
          /*
             field name: _rec.key,
             old values: _rec.old_value,
             new value : _rec.new_value
          */
        END IF;
      END LOOP;

      RETURN NEW;
    END;
    $$
    LANGUAGE 'plpgsql';


text:
Q: Swift protocol inside of protocol I am running into a problem with Swift protocols. I have something like this:
protocol OnboardingPage {
  var viewModel: OnboardingPageViewModel! { get }
}

protocol OnboardingPageViewModel {
  func getValue() -> Bool
}

// ---

class FirstNameViewController: UIViewController, OnboardingPage {
  var viewModel: FirstNameViewModel!
}

class FirstNameViewModel: OnboardingPageViewModel {
  func getValue() -> Bool {
    return true
  }
}

class GenderViewController: UIViewController, OnboardingPage {
  var viewModel: GenderViewModel!
}

class GenderViewModel: OnboardingPageViewModel {
  func getValue() -> Bool {
    return false
  }
}

I have a bunch of view controllers that confirm to the OnboardingPage protocol, and they all have a view model that all conform to the OnboardingPageViewModel protocol.
But sadly the code above doesn't work: it says FirstNameViewController doesn't confirm to the OnboardingPage protocol, since its viewModel property has type FirstNameViewModel instead of OnboardingPageViewModel - even though FirstNameViewModel IS a OnboardingPageViewModel.
How can I solve this?

A: Use associated type OnboardingPageViewModel type ViewModel
Edited
protocol OnboardingPage {
    associatedtype ViewModel: OnboardingPageViewModel

    var viewModel: ViewModel { get }
}

protocol OnboardingPageViewModel {
    func getValue() -> Bool
}

class FirstNameViewController: OnboardingPage {
    let viewModel: FirstNameViewModel

    init(viewModel: FirstNameViewModel) {
        self.viewModel = viewModel
    }
}

class FirstNameViewModel: OnboardingPageViewModel {
    func getValue() -> Bool {
        return true
    }
}

class GenderViewController: OnboardingPage {
    let viewModel: GenderViewModel

    init(viewModel: GenderViewModel) {
        self.viewModel = viewModel
    }
}

class GenderViewModel: OnboardingPageViewModel {
    func getValue() -> Bool {
        return false
    }
}

A: You may solve your pages array issue with deletion of associatedtype:
protocol OnboardingPage {
    var viewModel: OnboardingPageViewModel { get }
}

protocol OnboardingPageViewModel {
    func getValue() -> Bool
}

class FirstNameViewModel: OnboardingPageViewModel {
    func getValue() -> Bool {
        return true
    }
}

class FirstNameViewController: OnboardingPage {
    let viewModel: OnboardingPageViewModel

    init(viewModel: FirstNameViewModel) {
        self.viewModel = viewModel
    }
}

class GenderViewModel: OnboardingPageViewModel {
    func getValue() -> Bool {
        return false
    }
}

class GenderViewController: OnboardingPage {
    let viewModel: OnboardingPageViewModel

    init(viewModel: GenderViewModel) {
        self.viewModel = viewModel
    }
}

Usage:
let nameModel = FirstNameViewModel()
let genderModel = GenderViewModel()

let array: [OnboardingPage] = [FirstNameViewController(viewModel: nameModel), GenderViewController(viewModel: genderModel)]

for page in array {
    print(page.viewModel.getValue())
}

However, in such manner concrete types of your models will not be available for callers of OnboardingPage conforming classes. You may try to solve it with implementing visitor pattern within OnboardingPage or enhancing its capabilities.
Of course, you can always write let pages: [Any] = [FirstNameViewController(), GenderViewController()] using Cruz example, but it is ugly as it goes, and I strongly discourage you from using Any in your API if possible.


text:
Q: Extracting text nodes or elements with relative XPath in Scrapy So I'm relatively new to using XPath and I am having a little difficulty honing in on the exact syntax that I need to use for my specific application. The scraper that I have built is working perfectly fine, (when I use a less complicated path it works). Once I try to get more specific with my path, it isn't returning the proper values.
A simplified model of the document structure that I am trying to manipulate is

        Text That I want to Grab

      Some
      Text

        Text That I want to Grab

      Some
      Text

        Text That I want to Grab

      Some
      Text

        Text That I want to Grab

      Some
      Text

Basically, I would like to grab the href values and the text with the links.
This is the portion of my scraper regarding this and what I have tried so far:
  import scrapy
  from scrapy.selector import HtmlXPathSelector
  from scrapy.http import HtmlResponse

  def parse(self, response):
    for sel in response.xpath('//table[@class="rightLinks"]/tbody/tr/*[1]/a'):
      item = DanishItem()
      item['company_name'] = sel.xpath('/text()').extract()
      item['website'] = sel.xpath('/@href').extract()
      yield item

Edit: new paths I'm using
def parse(self, response):
  for sel in response.xpath('//table[@class="rightLinks"]/tr/*[1]/a'):
    item = DanishItem()
    item['company_name'] = sel.text
    item['website'] = sel.attrib['href']
    yield item

Final Edit: Working code (thanks guys!)
 def parse(self, response):
  for sel in response.xpath('//table[@class="rightLinks"]/tr/*[1]/a'):
    item = DanishItem()
    item['company_name'] = sel.xpath('./text()').extract()
    item['website'] = sel.xpath('./@href').extract()
    yield item

Any suggestions or hints would be much appreciated!
Joey

A: sel.xpath('/text()') and sel.xpath('/@href') are both absolute paths; if you wanted relative paths, this would be ./text() or ./@href.
If this is lxml -- and sel is an lxml Element object -- just use sel.text, or sel.attrib['href'] -- no XPath needed.


text:
Q: Django - Custom model cannot appear on User model I have created a model in Django v4, and I want to show the information inside the User admin view. After migrating, a new table was created successfully and data is being stored. Here is the code:
models.py
from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )

    address = models.CharField(
        max_length=20,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.user.username

admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profile

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Extra Information'

@admin.register(ProfileInline)
class UserAdmin(admin.ModelAdmin):
    inlines = [
        ProfileInline,
    ]

The table that has been created has the following stored:

id
address
user_id

3
Test
2

Where the user_id column, is a foreign key from the auth_user table, which is created automatically (I guess?).
Now, when I try to run, makemigrations, etc, it shows me the following:
AttributeError: type object 'ProfileInline' has no attribute '_meta'
What is the proper way to have the information appended to the User, as the default sections do?

A: I figured out the solution. The admin.py should look like this:
from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profile

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Extra Information'

class UserAdmin(admin.ModelAdmin):
    inlines = [
        ProfileInline,
    ]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

A: A better approach in this case would be to inherit Django's AbstractUser class, add your additional fields then set Django's AUTH_USER_MODEL in settings so that django uses your model for authentication.
https://docs.djangoproject.com/en/4.0/ref/settings/#std-setting-AUTH_USER_MODEL
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    address = models.CharField(
        max_length=20,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.username

settings.py
AUTH_USER_MODEL = "<your_app_name>.Profile"


text:
Q: How to implement content track using piwik/matomo + angulartics2 Technology Angular 6.0.9, Angular CLI: 6.0.8
Plugin angulartics2 ^6.2.0
Vendor plugin angulartics-piwik
I'm about to capture my page specific block content into piwik/matomo using angulartics2 but I can't figure out OR unable to do that.
I reviewed the plugin code from github So, I think that it seems like no support given by angulartics2 for block content kinds of stuff.
I also drill into matomo given introduction about How to Content Tracking and I'm now helpless. However, event tracking is working fine!
Can anybody tell me that I'm on wrong way OR How to accomplish that?
HTML Example:

{{data.name}}

    {{data.catalog}}

    /*
    Also tried below structure but it's not working too:

{{data.name}}

        {{data.catalog}}
        Buy Now
    */

Please...
Help would be much appreciated! Thank you!


text:
Q: Maintaining SynchronizationContext for nested (not first or last) methods in Blazor Using the default project that loads with Visual Studio 2019 when you create a new blazor server-side project in .NetCore 3.1, consider the following example (a slight change to their own counter example page):
<button class="btn btn-primary" @onclick="SingleMethodUpdate">Click Me</button>
Update from same method: @result
<button class="btn btn-primary" @onclick="NestedMethodUpdate">Click Me</button>
Update from nested method: @nestedResult

And the code-behind to look like this:
int result = 0;
int nestedResult = 0;
int nestedCounter = 0;

protected async Task SingleMethodUpdate()
{
    result++;
}

protected async Task NestedMethodUpdate()
{
    await NestedUpdate(++nestedCounter);
    await Task.Delay(1000);
    await NestedUpdate(++nestedCounter);
    await Task.Delay(1000);
    await NestedUpdate(++nestedCounter);
}

protected Task NestedUpdate(int update)
{
    nestedResult = update;
    return Task.FromResult(0);
}

The first button and label is simple, press a button and the count on the UI updates as soon as you press it as expected. However, the second button is more complicated.
It is the middle await NestedUpdate(++nestedCounter) call that doesn't get reflected on the UI. The first call and the last call (first and last nested method call) are both reflected in real-time on the UI, so what you see is:
Update from nested method: 1
*2 seconds go by
Update from nested method: 3

I realize this is because of the caveats with SynchronizationContext but I am more curious as to how I would go about capturing and maintaining that context such that every awaited method that is called within my button press event uses that same context so that the UI will update in real-time as the code executes. Is there a nice/pretty way to do this?

A:
I realize this is because of the caveats with SynchronizationContext

No, not really. All this code should run async but sequentially on the main thread.
Nothing wrong or in need of fixing with the SyncContext here.
What you see is due to the StateHasChanged() logic, which really is about a State, presumably just a boolean flag.
The Blazor framework will set this flag before and after it calls your eventhandler but in the middle you will have to do so your self.
A quick fix and explanation:
protected async Task NestedMethodUpdate()
{
    // the flag is pre-set here
    await NestedUpdate(++nestedCounter);
    // the thread is available and Blazor will render '1' and reset the flag
    await Task.Delay(1000);

    await NestedUpdate(++nestedCounter);
    // the thread is available but the flag is down: the '2' is not shown
    await Task.Delay(1000);

    await NestedUpdate(++nestedCounter);
    StatehasChanged();  // <<-- add this
    // the thread is available and the flag is up: the '3' is shown
    await Task.Delay(1000);

    // you can add more steps
    await NestedUpdate(++nestedCounter);
    StatehasChanged();  // <<-- set the flag
    await Task.Delay(1000);  // show '4'

    // this result will show '5' after the method has completed
    await NestedUpdate(++nestedCounter);
}


text:
Q: One database field is not update in EntityFramework I have an Stored Procedure in SQL Server 2012:
CREATE procedure [dbo].[GetEmailThread]
(
@id int
)
AS
SELECT e.Id, e.Created, e.MailFrom, e.MailTo, e.Body, e.Sended, ip.Ip, e2.Sended as ReplySended, e2.Body as ReplyBody, e2.Id as ReplyId
FROM Emails e
LEFT JOIN IpAddress ip ON (ip.Id = e.IpId)
LEFT JOIN Emails e2 ON (e.Id = e2.ParentEmailId)
WHERE e.RealtyId = @id
ORDER BY e.Sended, ReplySended

Definition of Email Table:
CREATE TABLE [dbo].[Emails](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Created] [datetime] NOT NULL,
    [MailFrom] [nvarchar](100) NOT NULL,
    [MailTo] [nvarchar](500) NOT NULL,
    [Subject] [nvarchar](500) NULL,
    [Body] [nvarchar](max) NULL,
    [Sended] [datetime] NULL,
    [Ip] [varchar](15) NULL,
    [ReplyTo] [nvarchar](100) NULL,
    [IpId] [int] NULL,
    [RealtyId] [int] NULL,
    [ParentEmailId] [int] NULL,
    [IsBodyHtml] [bit] NOT NULL CONSTRAINT [DF_Emails_IsBodyHtml]  DEFAULT ((0)),

And EntityFramework model in C#. Whenever I right-click in Visual Studio Model Browser to this EntityFramework model and choose the menu "Update Model from Database", the model gets updated, but the field MailTo in GetEmailThread_Result is always missing.
I need to add it manually to the model GetEmailThread_Result.cs to get it working.
Why? Why this? I cannot see anything special in this field. Why not MailFrom?

A: The solution was to manually edit EF files in the project as they were corrupted, for details see Updating Entity Framework Model


text:
Q: in ERB Inline code to fetch first non nil array value I need to fetch first non nil value in an array.
I tried this code but doesnt seem to be work
entity['perattr.firstname'].to_s.find{|x|!x.nil?}
it is giving me below error. Please let me know how to get the value?

find' for "[]":String

A: To get the first non-nil value in an array, use detect:
arr = [nil, nil, "foo", "bar", nil]
arr.detect{|x| !x.nil?}
=> "foo"

If entity['perattr.firstname'] is an array, you can therefore just do
entity['perattr.firstname'].detect{|x| !x.nil?}

Don't call to_s on it, this will turn it into a string.

A: to_s is generally used to convert an object to String. Therefore irrespective of what value entity['perattr.firstname'] holds, entity['perattr.firstname'].to_s will always be a String. Since there is no find method for String, you are getting error.

find' for "[]":String


text:
Q: Error input type when using webview to make IOS application I have a ruby on rails website which is designed mobile's view. In this web, I have 2 input: email and zip code which is define input[type=email] and input[type=tel] respectively. I checked this view in Safari browser and 2 above inputs work correctly - it mean the keyboard display @ in email field and numeric keyboard in zip code field. I used this website (or webview exactly) to make IOS webview application, however 2 above inputs is still input[type=text] and the keyboard only display text keyboard. This is html my code:
- email field:
<input type="email" name="user_email" id="user_mail" maxlength="300" size="30" >

zip code field:

<input type="tel" name="zip_code" id="zip_code" maxlength="8" size="10" placeholder="1050001" >

What are reasons and solution of this issue? Please help me. Thank you.

A: For iOS webview to display numeric only, you have to have pattern="[0-9]*" at the zip code field.
<input type="tel" name="zip_code" pattern="[0-9]*" id="zip_code" maxlength="8" size="10" placeholder="1050001">

Reference: iPhone / iOS : Presenting HTML 5 Keyboard for Postal Codes


text:
Q: How to access aliased attributes in ActiveRecord class? Is there a better way I'm missing? I'm interfacing with an older database and have mapped the old column names to the new ones using alias_attribute.
It works great, but I also want to get a list of all the attributes for a record too. Using record.attributes only gives me the original attributes, not the aliased ones too. Is there a way I can list all these through a similar method?
Maybe I would be better off just making a lookup hash?
Thanks in advance!

A: I'm afraid it isn't possible to get the list of aliased attributes. The alias_attribute method does nothing beyond creating few getters/setters. This method doesn't "mark" these methods in any way.


text:
Q: List USB ports in linux I want to list usb ports in linux and then send a message to the printer connected to it. That message is sensed by the printer to open the cash drawer. I know I can use echo - e and a port name, but my difficulty is finding the port name. How can I list the available ports or the ports that are currently used?

A: The lsusb command will yield the list of recognised usb devices.  Here is an example:
$ lsusb
Bus 002 Device 003: ID 1c7a:0801 LighTuning Technology Inc.
Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 04ca:f01c Lite-On Technology Corp.
Bus 001 Device 003: ID 064e:a219 Suyin Corp.
Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

You can note that the information provided include the bus path as well as the vendorId/deviceId.
I'm not sure what "the ports that are currently used" actually means.
Edit
To write a message to the device on bus 1 device 2 you must access the device
$ ls -l /dev/bus/usb/001/002
crw-rw-r-- 1 root root 189, 1 2011-06-04 03:11 /dev/bus/usb/001/002


text:
Q: How do you do continuous delivery in an unstable environment? We're Scrum teams building microservices. Our GitHub repositories are single-branch, each of us integrates his/her code into master several times a day, with no feature branches. Our Jenkins pipelines compile the code, run automatic tests, supply the code to other services for static code scans, and deploy our software across a CloudFoundry landscape for further testing. If all the steps succeed, our pipelines automatically deploy the software into production spaces on Amazon Web services. We live Uncle Bob's Clean Code, write reliable unit tests with > 90% mutation coverage, and honor Jez Humble's ideas from Continuous Delivery. We think we are doing everything right.
It doesn't work.
99% of our builds fail on their way through the pipelines. In many weeks our velocity is nearly 0.
Now the first impulse is to say we'd need to code cleaner, test more, stop pushing into red pipelines, roll back faster, perform root cause and post mortem analyses, and so on. But we've been there and done all that, chomped through our code, practices, and culture. We've streamlined and upskilled our own teams as best as we could.
The problem is that the builds fail for reasons that our teams have no control over: the Jenkins servers, the Maven Nexus, the npm registry, the code scanning services, the Cloud Foundry landscape, all of these are maintained by other teams in our company. Individually, all of the involved 15 tools and teams are nice, and suffer only sporadic outages that might block a pipeline from minutes to a handful of days max. But in combination, the failure probabilities sum up to a nearly impenetratable wall of random failure.
What are strategies to improve this situation?

A: Technical answer
The exact concept that is needed here is fault tolerance. You need a pipeline that is resilient to failure. This is an open-ended engineering problem, of course.
The most obvious brute force solution is redundancy, i.e. have redundant nodes in the pipeline so that even if something fails there is another server that can take over.
Another important but often neglected aspect to consider is the recovery mode. If there is a failure, does the pipeline pick up where it left off, or does it always start again from the beginning?  Are build tasks idempotent and capable of being run repeatedly without issue, or do you have to trigger a full rollback and clean the system every time? This can make a huge difference in any process that has continuous problems.
Business answer
The other team needs help in getting visibility to the issues that are preventing them from deliveing a high quality, stable pipeline. Help them by gathering metrics of downtime and estimating the actual cost to the business. This will help them make a case with their own management to get additional resource (staff, hardware, training, or third party services) to meet the business' needs. You can also help with measuring success by coordinating and agreeing on an internal SLA and tracking their ability to meet it.
Needless to say, do not be adversarial about it, as this is often counterproductive.

A: Abandon the flaky network services, and do stuff locally.
You can unit test stuff on your own PC, and you can do it before you check in buggy code.  You don't need a Maven repository if the third-party code is all in a repository that your team has control over.  You don't need Jenkins to build source, instead fire up your IDE, and do a Clean and Build.  If it doesn't absolutely need to be "in the cloud", do it locally within your team, and keep control over it.
Added bonus: In five years time, when a customer comes back and asks for an update to a product that you thought was long retired, you don't want to find that you have no way of building the thing anymore.  Relying on a mess of servers maintained by multiple other people is asking for trouble.  They will all have been retired, or moved on to newer versions that aren't compatible with your old project.  It's much better if everything you need is configured locally, so you can check it all out and build the whole lot from scratch according to your documented procedures.

A: I find it hard to believe that "only sporadic outages" of few dependent services would result in 99% builds failing. Maybe you need some detailed analysis on which services are worst offenders and either communicate with their owners to improve their stability or replaces them with more stable options.
Quick math. If each service has x% chance of failing and your build uses N services in sequence, then the probability of random build failure is : 1-(1-x)^N. So for failure rate of 1% and 5 services, it is 1-(1-0.01)^5 = 0.049, which is roughly 5%.
Another idea is to separate "necessary for deployment" dependencies from dependencies that provide useful information, but do not prevent deployment. Static code analysis comes to mind. You don't need it for deployment, but it is nice information. Instead of running it as part of your deployment pipeline, run it asynchronously in separate pipeline, that provides reports to developers.
Next idea that comes to mind is, that instead of single pipeline, you could have "phased" pipeline. Inspiration for this comes from book A Practical Approach to Large-Scale Agile Development, that Jez Huble likes to reference. There, they describe a build pipeline, that has multiple phases. Each able to run on it's own and which can be re-started if it fails, without need to re-start all that came before it.


text:
Q: Copy HTML from WebView and paste into EditText In Android 4.1.1 copying some content from a WebView (like paragraphs, bullets, spans, links) and pasting it into an EditText renders the HTML almost like the original (since many tags aren't supported it's not exactly the same but close enough).
But as of Android 4.1.2, the text is not pasted as HTML anymore, and when reading from the ClipboardManager the text has the MIME_TYPE text\plain. Is there a way to tell the clipboard manager to copy the selection from a WebView as HTML and not text?


text:
Q: How to host dynamic website which uses MongoDB, Node, Stripe (since Github Pages won't work?) Thus far I have enjoyed Github Pages for putting up my webpages and projects online where others can view and interact with them. This is also handy for displaying and linking to things I've worked on in my portfolio.
My newest project, a tutorial on building shopping cart with thorough functionality, involves Node.js, Express.js, MongoDB, Passport.js, Stripe.js.
Link to Shopping Cart Repository
The gh-pages version of the site: Github Pages version of the repository  gives a 404 Error. As I understand, because this involves interacting with a server (MongoDB and Node), this is a "dynamic page", whereas Github Pages can only host "static pages".
Is there a way that I can have this up and running online so that others can see and interact with it?
If not, is another solution to simply record and post a video of the website in action?
Thank you.

A: For Node you can use Heroku.com
And for MongoDB I think you can find a free hosted on internet, either you can maybe create a local MongoBD server as local with Node


text:
Q: Why won't OS X let me rename a file? I accidentally named a file testIn2Post.py rather than testIn2post.py (notice the different case for the letter "p") and have been unable to rename it, even after rm-ing the file in question. Notice that when I recreate the file with a lowercase "p" and then run ls, the file is created with a capital "p":

I expected to create a filename testIn2post.py, but I get testIn2Post.py (again, different case for the letter "p").
How can I force OS X to properly rename/create my file? It is causing issues when I try to import the module.

A: There might be simpler ways, but when I have encounterd the Mac's filesystem to behave against my (Unix) expectations I moved the files that I need to a new directory, remove the old one and renamed the new directory to the old one.
cd ..
mkdir tmptest
mv test/*.py tmptest
rm -rf test
mv tmptest test

I am not sure what causes this except that it probably has to do with the underlying filesystem not being case-sensitive as John1024 already commented. It never happened often enough to me to care about finding a more efficient solution than this workaround.


text:
Q: Mapserver can't write in /var/www/mapserver/log/ I'm executing Mapserver 5.6.4 under Apache2 in a Ubuntu 10.04 machine.
I'm having problems writing log file. In the mapfile, I have:
CONFIG  "MS_ERRORFILE" "/var/www/mapserver/log/mylogfile.log"
DEBUG   5

Any request I make gets the same answer
msSetErrorFile(): General error message. Failed to open MS_ERRORFILE
/var/www/mapserver/log/mylogfile.log
If I change the path to /tmp/mylogfile.log it works, but then I have a
similar problem with SLD:
msHTTPExecuteRequests(): HTTP request error. HTTP: request failed with
curl error code 7 (Failed connect to mymachine:80; Operation now in
progress) for http://mymachine/sld/polygon_simplepolygon.sld
msSLDApplySLDURL: WMS server error. Could not open SLD
http://mymachine/sld/polygon_simplepolygon.sld and save it in
temporary file /var/www/mapfiles/4df0f886_22dd_0.sld.xml. Please make
sure that the sld url is valid and that imagepath and imageurl are set
properly in the map file
IMAGEPATH and IMAGEURL are properly set in Mapfile (a writable
directory and a correct url). The log directory belongs to www-data,
and the SLD directory too, and www-data has write permission in both directories.  I made a test executing, with the www-data user, a python script that creates a file in those directories and it works.
Why mapserv process can't do it? Even when I change the permissions of log directory or SLD directory to 777, mapserv can't write on them, but it can it /tmp. Why?
Many thanks in advance, and best regards,

A: Just change the permission (777 is sufficient) to your logfile.
In your case:
chmod 777 /var/www/mapserver/log/mylogfile.log

A: It is a bad idea to write data to /var/www ; Check whether apparmor for apache is enabled, it may disable writing to that directory (but it is better to use a different one anyway, and chown it 1777).
sudo aa-status

(to check whether apparmor is enabled for apache)


text:
Q: Angular - Change css using ng-style I am trying to change top position of a DIV on Scroll event -
In controller i have-
    angular.element($window).on("scroll", function(e) {
        vm.scrollTop = angular.element($window).scrollTop()+'px';
        console.log(vm.scrollTop);
    });

In html -

    Hello World

On scroll event is printing scrollTop values in console but "Div" style never gets updated.
Please correct me if this is syntactically incorrect.

A: You need to call $scope.$apply(); after setting vm.scrollTop because the event handler is executing outside of angular's awareness.

A: You can use $scope.$apply or $scope.$watch.
Here's snippet using $scope.$apply.

function TodoCtrl($scope, $document, $window) {
   $scope.scrollTop = 30;
     $document.bind('scroll', function(){
        $scope.$apply(function(){
   $scope.scrollTop = $window.scrollY;
      });
   });
   $scope.getStyle = function(){
        var styles = {}
        styles['margin-top'] = $scope.scrollTop + 'px';
        return styles;
  }
}

Top

         Hello World


text:
Q: Java Replace a particular character The following regex
str = str.replace(/,/g, '');

works well in javascript to replace any particular character(comma in this case).How to achieve same in Java.

A: str = str.replaceAll(",", "");

Replaces every comma with nothing


text:
Q: Custom alphanumeric sequences in Postgresql? We have a need to make a custom id called "JobID" in our  postgresql database.  It looks like this
XXX-Y
Where xxx=company short id and y=job id.
So imagine if we had job 3 for Apple it would be
APL-3.
You could have the same job 3 for Microsoft and it would be
MSF-3.
So its essentially a combination of a 3 digit code plus a sequence.
Is this something you can do in Postgresql?  I mean I could obviously do this without a sequence but I was curious if anybody had tried this before?


text:
Q: retrieving fork with composer This has been discussed multiple times in multiple questions on SO, but all the answers given refuse to work for me accept this answer:
Contributing to open source bundles from vendor directory?
I've tested this on multiple machines, so I'm pretty sure it's not an isolated incident.
But using the type "package" is considered bad practice I read. Can someone explain to me why this is not working? It won't load the forked repository!
{
    "repositories":
    [
        {
            "type": "vcs",
            "url": "https://github.com/flyandi/lumen-doctrine.git"
        }
    ],
    "require": {
        "nordsoftware/lumen-doctrine": "dev-master@dev"
    }
}

update
So it turns out it has something todo with the stability of packages more about that here:
https://igor.io/2013/02/07/composer-stability-flags.html
I then tried this which works:
{
    "repositories":
    [
        {
            "type": "vcs",
            "url": "https://github.com/flyandi/lumen-doctrine.git"
        }
    ],
    "require": {
        "nordsoftware/lumen-doctrine": "dev-master@dev"
    },
    "prefer-stable" : true,
    "minimum-stability": "dev"
}

What I don't understand is way the @dev flag doesn't work though? Can someone elaborate?

A: Composer tries to resolve into a stable set of packages by default.
It won't resolve, because the package you are fetching (via alias)
uses development dependencies itself. The dependency doctrine/orm of the package you are fetching lumen-doctrine is required in dev mode.
And the need for this development dependency bubbles up to your package.
When you add dev-master or dev-master@dev for nordsoftware/lumen-doctrine
it works only for this package.
The @dev makes explicit, what we already know because of the dev- prefix: its a request for a dev version, but it doesn't change the stability for all packages - and it doesn't set the stability for dependencies of the package.
The installation request for nordsoftware/lumen-doctrineis satisfiable by  dev-master (and by a number of tagged versions).
The problem is that the package doctrine/orm is not satisfiable, because nordsoftware/lumen-doctrine dev-master requires doctrine/orm ~2.6@dev
Your options are:

*

*set the minimum-stability of all packages to dev (you already have that)

*or just add doctrine/orm and go lower in stability only on this package

*

*by using ~2.6@dev or 2.6.x-dev

{
    "repositories":
    [
        {
            "type": "vcs",
            "url": "https://github.com/flyandi/lumen-doctrine.git"
        }
    ],
    "require": {
        "nordsoftware/lumen-doctrine": "dev-master",
        "doctrine/orm":                "~2.6@dev"
    }
}


text:
Q: How feature communicate with eachother in wspbuilder project? Suppose i have multiple features inside my wspbuilder. That includes a list definition, and a webpart.

*

*I want to fetch the records / items inside list, into my webpart. how we can do this ?

*As i explained , i have a list definition in my WSPBuilder project. the requirement is, to set the lookup field on that list itself on ID Or Title column. Can we do this ? What i have to do.

A: *

*Use a SPQuery object. But you should develop what you want to do. There is often native components that can do the job with a small amount of work

*either use the AddLookupMethod, or do the stuff in the list definition. The later way is quite hard, because the list definition schema is not always properly handled by SharePOint code. I also have to add, that the lookups needs to be used with precaution. You have to create the target list, then the child list (can't create the lookup on a non existing field)


text:
Q: PostgreSQL 14 json Input Cannot Insert For Each Attribute To Each Column When I try to insert json input to my stored procedure it shows below error< i Googled a lot and couldn't find any solution, I am Little confused about the type conversion In Postgres
--Call
do $$
    declare d TIMESTAMP WITH TIME ZONE;
    v_json JSON;
    begin
        select now() INTO d;
        CALL sp_insert_or_update_branch('{"code":"TestCode", "name":"testName"}'::jsonb, v_json);
    end;
$$;

--SP
CREATE OR REPLACE PROCEDURE sp_insert_or_update_branch(jsnBranch JSONB, jsnSqlRes OUT JSON) AS $$
    DECLARE
        objSpOutRes TYP_SP_OUT_RES;
        objFnCheckRes TYP_FN_CHECK_RES;
    BEGIN
            INSERT INTO organization.tbl_branch
        (fk_company_id, vhr_branch_code, vhr_branch_name, ars_product_ids)
        VALUES(1, jsnBranch->>code, jsnBranch->>name, '{1}');

        --COMMIT;
        objSpOutRes.binSqlPk := 1::BIGINT;
        objSpOutRes.sinSqlCustomStatus := 1::SMALLINT;
        objSpOutRes.strSqlCustomStatusCode := 'SUCCESS';
        objSpOutRes.strSqlCustomMessage := 'Branch Saved';

        SELECT * FROM  fn_convert_type_out_object_to_out_json(objSpOutRes) INTO jsnSqlRes;
        RAISE NOTICE 'jsnSqlRes: %', jsnSqlRes;
    END;
$$ LANGUAGE plpgsql;

--Error
ERROR:  column "code" does not exist
LINE 3:      VALUES(1, jsnBranch->>code, jsnBranch->>name, '{1}')
                                   ^
QUERY:  INSERT INTO organization.tbl_branch
                    (fk_company_id, vhr_branch_code, vhr_branch_name, ars_product_ids)
                    VALUES(1, jsnBranch->>code, jsnBranch->>name, '{1}')
CONTEXT:  PL/pgSQL function sp_insert_or_update_branch(jsonb) line 6 at SQL statement
SQL statement "CALL sp_insert_or_update_branch('{"code":"TestCode", "name":"testName"}'::jsonb, v_json)"
PL/pgSQL function inline_code_block line 6 at CALL
SQL state: 42703


text:
Q: Android complex Player layout design I want to convert the following image into a layout,

If you look closely the bottom and top view behind the Play button are separated and the Play button needs to be fitted in between them.
Here's the top holder,

and the bottom holder,

Here's what I've done so far,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_blur"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

        <ImageView
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_margin="18dp"
            android:background="@drawable/btn_play" />

        <ImageView
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_margin="18dp"
            android:background="@drawable/btn_play" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="45dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="162dp"
            android:layout_height="162dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="35dp"
            android:background="@drawable/btn_play" />

        <LinearLayout
            android:id="@+id/topHolderLayout"
            android:layout_width="400dp"
            android:layout_height="30dp"
            android:layout_above="@+id/middle_separator"
            android:layout_weight="1"
            android:background="@drawable/top_holder_top_part"
            android:orientation="horizontal"></LinearLayout>

        <View
            android:id="@+id/middle_separator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"></View>

        <LinearLayout
            android:id="@+id/bottomHolderLayout"
            android:layout_width="400dp"
            android:layout_height="30dp"
            android:layout_below="@+id/middle_separator"
            android:layout_weight="1"
            android:background="@drawable/top_holder_bottom_part"
            android:orientation="horizontal"></LinearLayout>
    </RelativeLayout>
</RelativeLayout>

Since it's solely depends on the pixels so doesn't works on different screen sizes. What would be the best way to adopt this type of design? Any kind of help/suggestion will be greatly appreciated!

A: If you want your layout to scale with device screen, you may do one of the following:

*

*Create separate images for each screen density (this may be a good idea in case of your buttons):

res/drawable-mdpi/graphic.png         // bitmap for medium-density
res/drawable-hdpi/graphic.png         // bitmap for high-density
res/drawable-xhdpi/graphic.png        // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png       // bitmap for extra-extra-high-density

Source: http://developer.android.com/guide/practices/screens_support.html

*Create a drawable XML resource in res/drawable.
For example, background of your top holder might look like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#e0e0e0" />
    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:topLeftRadius="128dp"
        android:topRightRadius="128dp" />
</shape>

And bottom holder:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#e0e0e0" />
    <corners
        android:bottomLeftRadius="128dp"
        android:bottomRightRadius="128dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="0dp" />
</shape>

Your buttons may then overlay the holders (you don't need to "cut" round holes in them).

*Create a 9-patch image using draw9patch tool from Android SDK, as described here: http://developer.android.com/tools/help/draw9patch.html


text:
Q: Efficient simulation of cellular automata in Python I am implementing cellular automata (CA) to simulate tumor growth. My goal is to simulate CA in three dimensions. However, my code is very slow. I was hoping to simulate 10^6 cells in reasonable time (within 1 hour). Is there any way to speed up my code? I have hard time to find bottleneck of my code.
My code is:
   for generation in np.arange(100):
        print(len(TC.keys()))
        keys = list(TC.keys())
        keys = np.array(keys)
        for cell in np.ndenumerate(keys): # for each tumor cell
            cell_id = cell[1]
            division, migration, death = TC[cell_id].action(TC_pdivision, TC_pmigration, TC_pdeath)
            if death:
                del TC[cell_id] # remove tumor cell from dictionary
            else:
                # find free spot
                ngh = TC[cell_id].freeSpots(cells,TC[cell_id].neighbors(TC[cell_id].x,TC[cell_id].y,TC[cell_id].z))
               if np.size(ngh)>0:
                   ngh = np.reshape(ngh,[int(np.shape(ngh)[0]/3),3])
                   x,y,z = spot(ngh)
                  cell_id_new = positionToID(x,y,z)
                  if migration:
                     TC[cell_id_new] = TC.pop(cell_id)
                  elif division:
                     TC[cell_id_new] = TumorCell(x, y, z)

That is, each tumor is defined with position in three dimensions (x,y,z). Each tumor cell is one entry in dictionary. I am using function PositionToID function to convert (x,y,z):
    def positionToID(x,y,z):
           id = int(x + (y - 1) * gridSize + (z - 1) * gridSize * gridSize)
           return id
So, tumor cell is defined as follows:
TC[id] = [some_tumor_cell_properties]

Function neighbor generate (x,y,z) of all 26 adjacent cells, and freespots is:
    def freeSpots(self, cells, ngh):
    freeSpots = np.array([])
    for neighbor in ngh:
        currNeighbor = tuple(neighbor)
        if currNeighbor not in cells:
            freeSpots = np.append(freeSpots, np.array(currNeighbor))
    return freeSpots

responsible of checking for each adjacent cell if it is occupied or not. Freespots is fast so it is not an issue with this function.
I guess, the problem is with iterator. I tried to iterate over all tumor cells by extracting keys of dictionary TC (tumor cell) and converting them to numpy.array. Next, I applied ndenumare for iteration over all cells.
Is there any way to improve performance of my code? Thank you in advance for your help.


text:
Q: 'learning_logs' is not a registered namespace I have been seeing the following error. How can I solve it?
Error: 'learning_logs' is not a registered namespace
urls.py
"""Defines URL pattern for learning_logs"""
from django.conf.urls import url
from . import views
app_name = 'learning_log'
urlpatterns = [
    #Home page
    url(r'^$', views.index, name='index'),
    url(r'^topics/$', views.topics, name='topics'),
]```

#base.html

'''

  Learning Log -
  Topics

{% block content %}{%endblock content %}

A: Try this:
###base.html

    Learning Log -
    Topics

{% block content %}{%endblock content %}

This is because our book is out of date, I think.
A tip: try to use path functions instead of url functions in urls.py


text:
Q: Angular 9 mat-autocomplete not working properly with switchmap operator I am using deouncetime and switchmap operator to search in my APIs to perform autocomplete. But after subscribing to it, it returns all records from the API.
I know that switchmap cancels previous observables. So I can't understand why after subscribing to it returning all records from API.
I made sure the search request for API working well. It is returning only searched records.
Thank you in advance
.html
<mat-form-field class="example-full-width">
  <mat-label>Search for seller name</mat-label>
    <input matInput #input
    aria-label="product name"
    [matAutocomplete]="auto"
    [formControl] ="searchVendorCtrl">

    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)='Selected($event.option.value)' >

     <ng-container>
      <mat-option *ngFor="let state of vendor_list " [value]="state"  >
        <span>{{state.name}}</span>
      </mat-option>

      <mat-option *ngIf="!vendor_list || !vendor_list.length" class="text-danger">
        Such seller does not exists
      </mat-option>
     </ng-container>

    </mat-autocomplete>

</mat-form-field>

.ts
 ngOnInit() {

 this.subscribe5 = this.searchVendorCtrl.valueChanges.pipe(
      debounceTime(400),
      filter(term => term),
      switchMap((value) =>  this.vendorService.search_vendors(value))
    ).subscribe(data =>{
      if(data){
        console.log(data) // resulting all data from API
        this.vendor_list = data
      }
    })
  }

service
  search_vendors(data):Observable<any>{
    return this.http.get<any>(`${this.vendor_url}/vendor_autocomplete/${data}`)

  }

A: isLoading: boolean;
ngOnInit() {
    this.subscribe5 = this.searchVendorCtrl.valueChanges.pipe(
    debounceTime(400),
    tap(() => this.isLoading = true),
   switchMap((value) =>  this.vendorService.search_vendors(value)
   .pipe(
        finalize(() => this.isLoading = false),
      ))
 ).subscribe(data =>{
   if(data){
     console.log(data) // resulting all data from API
     this.vendor_list = data
   }
 });
}


text:
Q: JS assignment order of properties in objects Just had a quick question about why a certain order of assignment works and another doesn't.
I wanted to create a simple "inherit" / "copy" function (just for testing it) that copies properties from one object to another:
var cat = { tail:"yes", hairy:"yes, hairy" };
var dog = { sick:"extremely ill"};

function inherit(obj1, obj2) {
    for (var p in obj1)
    {
    obj2[p] = obj1[p]; // this works, but "obj1[p] = obj2[p];" doesn't. Why??
    }
}

inherit(cat, dog);

console.log(dog.tail);

A: You are looping over all the properties of obj1, so all those properties exist on obj1.
If you try to copy from obj2 then you are trying to copy properties that don't exist (on that object), so you cause an error.

A: You're reading the properties var p in obj1, so those indexes only necessarily exist in obj1. As such, trying to assign obj1[p] = obj2[p]; won't work as expected, since there is no guarantee (and in your particular example this is certainly the case) that obj[p] is defined. This assignment will simply assign undefined to indexes in obj1 that don't exist in obj2 and copy the values whose indexes do exist in obj2.
You need to loop over each object's properties separately (i.e. two loops), although this also isn't a good idea, since any values with the same index on both object will result in one being wiped out. What are you actually trying to achieve by this? It seems a very dangerous/volatile thing to do.


text:
Q: Application Specific User Role Configuration - OpenID Currently, we have 4 .NET applications which all having form based authentication. All these applications have their specific roles for users.
For example, consider applications are A, B, C, and D and each application has one user. A has user A1, B has user B1, C has user C1, D has user D1.
A1 has role of ARole1,ARole2 in application A.
B1 has role of BRole1 in application B.
C1 has role of CRole1,CRole2 in application C.
D1 has role of DRole1 in application D.
Currently these roles are mapped against users in application specific sql DB. Once users log in to the application these roles are fetched from DB.
Now we are moving all these applications to SAPCDC for authentication using OpenID connect and will be common login for all these four applications.
I am okay with the authentication part in SAPCDC.
But not sure how to manage/migrate these existing application-specific roles of the users.
Do we need to map these roles as OpenID scopes against the user ?
Or we can keep the application specific roles in the current sql DB against user? Once the user is authenticated through OpenID we can check the roles from the DB ?
Any guidance on this will be really helpful.

A: After authentication and before token issuance, it is common for the OIDC provider to look up domain specific claims (such as roles) and then include them in tokens as claims. This is typically done via a REST or database connection.
Typically the OIDC provider has its own user fields, eg:

*

*User name

*Email

*Generated subject claim (often a GUID)

In some cases roles can be included in the OIDC data, but it is common to keep them separate. Some domain specific claims - such as a customer subscription level - are best stored outside the OIDC data.
You need to design a way to map from the OIDC data to your domain specific data. A couple of common techniques are:

*

*A DB query that filters on email

*Adding the subject claim to your DB data

Here is a Curity article that discusses design patterns around customizing claims, which is an important area so that your APIs are able to authorize correctly.


text:
Q: Weibull Regression of Left Truncated Data in R I have a data set of tree diameters that do not include any measurements below a 7.5 due to the difficulty in identifying species when they are small. I want to run a Weibull regression that returns the parameters Shape & Scale that correspond to the forest stand rather than my truncated sample. For illustration purposes I have created a mock dataset in R with known parameters.
control <- rweibull(10000, shape = 1, scale = 10)
           # 10000 Random Samples From A Weibull Dist
           # W/ Shape =1 Scale =10
cutoff <- control[control > 7.5]
    # Removing All Samples Less Than 7.5 to Mimic My Data

Using the function fitdistr from the package MASS for Maximum-likelihood fitting of univariate distributions yields undesirable parameters for the truncated data.
library(MASS)
fit_control <- fitdistr(control, "weibull")
fit_cutoff <- fitdistr(cutoff, "weibull")

The regression worked well for the control data set, Shape ~ 1 and Scale ~ 10. However, things are obviously different with the truncated data set. I understand why but I am looking for a method to get similar values for the parameters from the truncated to describe the forest stand.
I attempted to create a truncated distribution of the Weibull for R to fit the data to by subtracting the cumulative distribution up to 7.5 from the density function.
Trunc_Weibull <- function(x, shape, scale, log = FALSE){
  dweibull(x, shape, scale, log)-pweibull(7.5, shape, scale,
       lower=FALSE)
}
fit_truncated <- fitdistr(cutoff, Trunc_Weibull,
         start = list(shape=0.5, scale=0.5))

This yields closer results but still not the desired output. Shown below is the cutoff and control histograms with the results from the truncated regression of the cutoff dataset.

The desired output would be: Shape ~ 1 and Scale ~ 10.

A: The likelihood for the dataset will be $\mathcal{L} \left( \alpha , \beta \right) = \left( F_{\alpha \beta} \left( 7.5 \right)\right)^{i} \prod_{j=i+1}^{n} f_{\alpha \beta}\left( x_{j} \right) $ where $i$ of your $n$ data points are left censored and $F$ is the cumulative distribution function and $f$ the probability density function.


text:
Q: About about binary files in C What I want to do in my program is to add a person ( or more ) and thereafter see the amount of bytes used, when going to (2), case 2.
My #include "header.h" is:
struct student {
    long long int personalnumber;
    char name[20];
    char gender[20];
    char program[20];
    int age;
    char email[20];
};

What I do here is start the program, click 1, write all the information the program asks for, maybe add two students (therefor the loop). when I click (n) the program should go back to the options. When Clicking 2 the amount of bytes used in the binary file should be printed out. Main function is here:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header.h"

int main()
{

    int val, age;
    long long int personalnumber, size;
    char email[20], program[20], gender[20], name[20], n;

    do
    {

        system("cls");

        printf("1:  Add\n\n");
        printf("2.  info\n\n");

        scanf("%d", &val);
        getchar();

        switch (val)
        {
        case 1:

            system("cls");
            printf("Add a new student to the database\n");

            struct student s1;

            FILE *myfile;
            myfile = fopen("students.dat", "wb");
            if (myfile == NULL)
            {
                printf("Could not open the file!\n");
                system("pause");
                exit(1);
            }
            while (1)
            {
                printf("\nEnter student personalnumber: ");
                scanf("%lld", &s1.personalnumber);
                getchar();
                printf("Enter name of student: ");
                fgets(&s1.name, 20, stdin);
                printf("Enter the gender of the student: ");
                fgets(&s1.gender, 20, stdin);
                printf("Enter the Program of the student: ");
                fgets(&s1.program, 20, stdin);
                printf("Enter the Age of the student: ");
                scanf("%d", &s1.age);
                getchar();
                printf("Enter the students Email: ");
                fgets(&s1.email, 20, stdin);

                myfile = fopen("students.dat", "wb");
                fwrite(&program, sizeof(struct student), 1, myfile);

                printf("Do you wish to add more students? Enter y or n");
                n = getchar();
                getchar();

                if (n == 'n')
                {
                    break;
                }
            }
            fclose(myfile);

            system("pause");
            break;

        case 2:

            freopen("students.dat", "rb", myfile);
            system("cls");
            printf("bytes:\n\n");

            myfile = fopen("students.dat", "rb");
            fseek(myfile, 0, SEEK_END);
            size = ftell(myfile);
            rewind(myfile);
            printf("Size of file is: %lld", size);

            system("pause");

            break;
        }

    } while (val != 3);

    system("pause");
    return 0;

}

A: With myfile = fopen("students.dat", "wb"); in the loop, you open the file again and again. Then you write to the file, overwriting anything that was in the file, so the file only contains your last write. Probably (possibly) your second call of fopen fails as the "file is already open by another process" but since you don't check the return value of the open call, you don't notice.
I suggest you read about the fopen call and especially the open modes.
As for hints (without providing a full solution): place the open call before the loop. You may have to check whether the file exists and decide whether to truncate the file or open it in read/write mode. Likewise, place the fclose call after the loop, so you only close it after you are done working with it.
You must also check the return value of open to know whether it has suceeded or not.

As to what you write: you write a string program but tell the write call it has the size of struct student. That isn't correct. Also, to pass a pointer to an array to a function, you only need to mention the name of the array; the compiler will translate this into the address of the array, so you don't need to use the address-of operator (&).

Concerning your case 2: you make the same mistake of opening the file multiple times (and of not checking whether the calls succeeded). freopen closes the file associated with the handle (that file is already closed, so this could invoke an error) and opens the new file. Then you call fopen on the file again, probably causing an error. At the end of the case you must close the file.


text:
Q: Getting method parameter names Given the following Go method:
func (t *T) TMethod(data *testData) (interface{}, *error) {
    ...
}

I want to reflect the name of the parameter (which is data here).
I tried the following, but it returns the structure name (which is testData here):
reflect.ValueOf(T).MethodByName("TMethod").Type.In(0).Elem().Name()

How can I get the name of the parameter?

A: There is no way to get the names of the parameters of a method or a function.
The reason for this is because the names are not really important for someone calling a method or a function. What matters is the types of the parameters and their order.
A Function type denotes the set of all functions with the same parameter and result types. The type of 2 functions having the same parameter and result types is identical regardless of the names of the parameters. The following code prints true:
func f1(a int) {}
func f2(b int) {}

fmt.Println(reflect.TypeOf(f1) == reflect.TypeOf(f2))

It is even possible to create a function or method where you don't even give names to the parameters (within a list of parameters or results, the names must either all be present or all be absent). This is valid code:
func NamelessParams(int, string) {
    fmt.Println("NamelessParams called")
}

For details and examples, see Is unnamed arguments a thing in Go?
If you want to create some kind of framework where you call functions passing values to "named" parameters (e.g. mapping incoming API params to Go function/method params), you may use a struct because using the reflect package you can get the named fields (e.g. Value.FieldByName() and Type.FieldByName()), or you may use a map. See this related question: Initialize function fields
Here is a relevant discussion on the golang-nuts mailing list.


text:
Q: Java local database I am creating a piece of software using Java and Eclipse. The software is to be freestanding and not require an internet connection.
The main use of the program requires access to database. I am used to developing for Android where there is an inbuilt MySQL database in every device. Is there a similar thing with Java. I have looked everywhere and have seen references to this kind of thing but have not seen any clear answers. I know there is JDBC, but this seems to be a method of controlling the database rather than creating it.
What I am trying to establish is, is there a pre installed database available to use in Eclipse without any further installation, in the same way as the MySQL Db is available when using Android??
The version of Java I am using is java.runtime.version=1.7.0_40-b43
and I am using Eclipse Kepler Service Release 2

A:
What I am trying to establish is, is there a pre installed database available to use in Eclipse without any further installation, in the same way as the MySQL Db is available when using Android??

First, Android includes SQLite (not mysql). Second, No. No there is not. You could use Derby or SQLite or H2 (or any other pure Java database). As pure Java databases they don't require external installation (but they can be installed externally) and can be run directly in Eclipse.

A: Would SQLite work for your purposes?
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
It's not pre-installed, but seems like it might be a good fit otherwise:
http://wiki.eclipse.org/Connecting_to_SQLite