text:
Q: Codelite installation unmet dependencies I would like to update the repository of my system

holger@ubuntu:~$ cat /etc/os-release
NAME="Ubuntu"
VERSION="14.04.5 LTS, Trusty Tahr"
holger@ubuntu:~$ uname -m
i686

with a newer codelite version (9.1), as the offical ubuntu repository contains an old one (2.8). I followed these instructions: How to install the latest version of codelite?
But I see this dependency error:

The following packages have unmet dependencies:
  codelite : Depends: liblldb-3.6 but it is not installable
          Recommends: lldb (>= 3.4) but it is not installable
          Recommends: nodejs but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

The installed version is:

liblldb-3.9/trusty-security,now 1:3.9.1-4ubuntu3~14.04.2 i386 [installed]

I appreciate any ideas how to fix it.
Edit:
By checking on the codelite dependencies, I see the following:

holger@ubuntu:~$ sudo apt-get build-dep codelite
The following packages have unmet dependencies:
 libgtk2.0-dev : Depends: libglib2.0-dev (>= 2.27.3) but it is not going to be installed
                 Depends: libgdk-pixbuf2.0-dev (>= 2.21.0) but it is not going to be installed
                 Depends: libpango1.0-dev (>= 1.20) but it is not going to be installed
                 Depends: libatk1.0-dev (>= 1.29.2) but it is not going to be installed
                 Depends: libcairo2-dev (>= 1.6.4-6.1) but it is not going to be installed
                 Depends: libxrandr-dev (>= 2:1.2.99) but it is not going to be installed
E: Build-dependencies for codelite could not be satisfied.

libgtk2.0-dev depends on libglib2.0-dev and other libs. When I try to install libglib2.0-dev, I get the following error:
> holger@ubuntu:~$ sudo apt-get install libglib2.0-dev Reading package
> lists... Done Building dependency tree Reading state information...
> Done Some packages could not be installed. This may mean that you have
> requested an impossible situation or if you are using the unstable
> distribution that some required packages have not yet been created or
> been moved out of Incoming. The following information may help to
> resolve the situation:
>
> The following packages have unmet dependencies:  libglib2.0-dev :
> Depends: libglib2.0-0 (= 2.40.0-2) but 2.40.2-0ubuntu1 is to $
>                   Depends: libglib2.0-bin (= 2.40.0-2) but 2.40.2-0ubuntu1 is t$
>                   Depends: libpcre3-dev (>= 1:8.31) but it is not going to be i$ E: Unable to correct problems, you have held broken
> packages.

So the dependend libs are on my system, they just differ in the minor release number. As I understand it I need version 2.40.0-2 for libglib2.0-0 but have version 2.40.2-0ubuntu1 installed.
What repo can I get these packages from? The standard repo only allows to install this version:
> holger@ubuntu:~$ apt search libglib2.0
> ...
> libglib2.0-dev/trusty
> 2.40.0-2 i386   Development files for the GLib library

Please let me know, what am I missing here?

A: What you could do is install it from its repository. From the website TipsUbuntu, it has instructions for the latest version 9.2 here.

*

*sudo sh -c 'echo "deb http://repos.codelite.org/ubuntu/ trusty universe" >> /etc/apt/sources.list.d/codelite.list' <- Add the repository.

*sudo apt-key adv --fetch-keys http://repos.codelite.org/CodeLite.asc <- Setup the key trust.

*sudo apt update && sudo apt install codelite wxcrafter <- Install!

*If it gives you any dependency issues, you can fix them with sudo apt-get install -f
Hope this helps!


text:
Q: SQL return multiple values in rows into columns I have a table with a few columns, but only two are relevant to this search:
ITEMNMBR and ALTITEM1
Right now data appears as follows
ITEMNMBR    ALTITEM1
A0001       ABCDEF
A0001       GBESJF
A0001       SDFJLK
B0001       JKHKJF
C0001       KLJSDF
C0001       MSXNCV

I would like to display the data so only one instance of each ITEMNMBR appears in the column with the corresponding ALTITEM1 values appearing in new columns.
ITEMNMBR    ALTITEM_1    ALTITEM_2    ALTITEM_3
A0001       ABCDEF       GBESJF       SDFJLK
B0001       JKHKJF
C0001       KLJSDF       MSXNCV

Each ITEMNMBR may have up to 20 ALTITEM1 values. If possible to add these columns dynamically that's great, but I figure that they need to be provisioned in the code...
SQL server 2008 R2

A:     (select itemnmber,
    case when altitem1 as altitem_1,
    null as altitem_2,
    null as altitem_3
    --repeat this until you reach 20 items
    from tablename)
    union all
    (select itemnmber,
    null as altitem_1,
    altitem1 as altitem_2,
    null as altitem_3
    --repeat this until you reach 20 items
    from tablename)
     union all
    (select itemnmber,
    null as altitem_1,
    null as altitem_2,
    altitem1 as altitem_3,
    --repeat this until you reach 20 items
    from tablename)
    ---repeat the whole process as many times with the column names

You can also use a empty string instead of null

A: You can simply use a PIVOT function for this like the following:
-- Create demo data
CREATE TABLE #temp(ITEMNMBR nvarchar(20), ALTITEM1 nvarchar(20))

INSERT INTO #temp(ITEMNMBR, ALTITEM1)
VALUES  (N'A0001',N'ABCDEF'),(N'A0001',N'GBESJF'),
        (N'A0001',N'SDFJLK'),(N'B0001',N'JKHKJF'),
        (N'C0001',N'KLJSDF'),(N'C0001',N'MSXNCV')

SELECT *
FROM (
    SELECT ITEMNMBR, ALTITEM1, ROW_NUMBER() OVER(PARTITION BY ITEMNMBR ORDER BY ALTITEM1) as rowNo
    FROM #temp
    ) as data
PIVOT(
    MAX(ALTITEM1)
    FOR rowNo IN([1],[2],[3])
) as pvt

-- Cleanup
DROP TABLE #temp

If you need a more dynamic approach (which won't work in a view), you can also take a look at my other solution here, which will dynamically create the IN()-clause here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why concrete members of wdDialogEditFind are not found by reflection? I am working on a VSTO project and want to use Word Dialog Boxes in Hidden Mode, just like code below:
Code from MSDN
dynamic dialog = Application.Dialogs[Word.WdWordDialog.wdDialogFilePageSetup];
dialog.PageWidth = "3.3\"";
dialog.PageHeight = "6\"";
dialog.TopMargin = "0.71\"";
dialog.BottomMargin = "0.81\"";
dialog.LeftMargin = "0.66\"";
dialog.RightMargin = "0.66\"";
dialog.HeaderDistance = "0.28\"";
dialog.Orientation = "0";
dialog.DifferentFirstPage = "0";
dialog.FirstPage = "0";
dialog.OtherPages = "0";

// Apply these settings only to the current selection with this line of code:
dialog.ApplyPropsTo = "3";

// Apply the settings.
dialog.Execute();

I want to implement another diaglog wdDialogEditFind, but methods and properties are unknown. then use reflection to retrieve them (late binding). but no useful methods found.
Word.Dialog dlg = this.Application.Dialogs[Word.WdWordDialog.wdDialogEditFind];

System.Type t = dlg.Type.GetType();
System.Reflection.MemberInfo[] memInfo = t.GetMembers();

string str = "";
foreach (System.Reflection.MemberInfo m in memInfo)
    str += m.Name + "\n";

A: MS Word interop hides these members from you since it relies on COM RCW. Reflection cannot be used to iterate through the properties since they are not defined for the Dialog base type. If you want to know what properties are available - see this MSDN reference for built-in dialog box arguments for wdDialogEditFind.
Built-in Dialog Box Arguments for wdDialogEditFind (from MSDN)

Find, Replace, Direction, MatchCase, WholeWord, PatternMatch, SoundsLike, FindNext, ReplaceOne, ReplaceAll, Format, Wrap, FindAllWordForms, MatchByte, FuzzyFind, Destination, CorrectEnd, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl

If you are insistent upon knowing the COM methods and properties - you can dig into IDispatch and weed your way through the COM types.


text:
Q: How to make numbering navigation after break; in PHP? Hi all I have searching for method but not luck. Help me I want to make numbering navigation. Here is my code:

            <?php
            $kw = file_get_contents('keywords.txt');
            $kw = explode("\n", $kw);
            asort($kw);
            $i = 0;
            foreach($kw as $k) {
            if($i==30) { break; }
            ?>

                <a href="<?php echo $domain.'/'.clean($k);?>"><?php echo ucwords($k);?>

            <?php $i++; } ?>

The above code just displayed 30 result from 1500 keyword I have. I want to make Page Numbering navigation also shorting A-Z. So user can Short Keyword by Alphabetic above it and page numbering after it.

A: Use Datatables.
Table

            KeyWord

        <?php foreach($kw as $k) { ?>

            <a href="<?php echo $domain.'/'.clean($k);?>"><?php echo ucwords($k);?>

        <?php } ?>

Javascript
$(document).ready(function() {
    $('#example').DataTable();
} );

Do include the proper plugin files for js & css. from - Datatables


text:
Q: CGAL Intersection returns false result I m a bit confused about how the the CGAL::do_intersect works.
I thought the function returns true if there is a point in both polygons. As far as I m not mistaken in lies within out and I should see true printed out or what am I missing?
#include <CGAL/Point_2.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>

typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
typedef Kernel::Point_2 Point_2;
typedef CGAL::Polygon_2<Kernel> Polygon_2;
int main(int argc, char **argv)
{
  Polygon_2 in, out;
  in.push_back(Point_2(1,1));
  in.push_back(Point_2(1,2));
  in.push_back(Point_2(2,2));
  in.push_back(Point_2(2,1));

  out.push_back(Point_2(0,0));
  out.push_back(Point_2(3,0));
  out.push_back(Point_2(3,3));
  out.push_back(Point_2(0,3));

  std::cout << "IN intersect with OUT is " << (CGAL::do_intersect(in, out) ? "true":"false") << std::endl;
  std::cout << "OUT intersect with IN is " << (CGAL::do_intersect(out, in) ? "true":"false") << std::endl;
  std::cout.flush();
}

A: The vertices in the polygon need to be counter-clockwise. The following code produces the desired output:
IN intersect with OUT is true
OUT intersect with IN is true

#include <CGAL/Point_2.h>
#include <CGAL/Polygon_2.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Boolean_set_operations_2.h>

typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
typedef Kernel::Point_2 Point_2;
typedef CGAL::Polygon_2<Kernel> Polygon_2;
int main(int argc, char **argv)
{
  Polygon_2 in, out;
  in.push_back(Point_2(1,1));
  in.push_back(Point_2(2,1));
  in.push_back(Point_2(2,2));
  in.push_back(Point_2(1,2));

  out.push_back(Point_2(0,0));
  out.push_back(Point_2(3,0));
  out.push_back(Point_2(3,3));
  out.push_back(Point_2(0,3));

  std::cout << "IN intersect with OUT is " << (CGAL::do_intersect(in, out) ? "true":"false") << std::endl;
  std::cout << "OUT intersect with IN is " << (CGAL::do_intersect(out, in) ? "true":"false") << std::endl;
  std::cout.flush();
}


text:
Q: second fragment doesn't appear Vertical layout:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="30dp"
    android:paddingRight="16dp"
    android:orientation="vertical"
    tools:context="john.unitconverter.UnitConverter">

    <fragment
        android:id="@+id/unitConverter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="john.unitconverter.ConverterFragment"></fragment>

</RelativeLayout>

horizontal layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/unitConverter"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="john.unitconverter.ConverterFragment"></fragment>

    <fragment
        android:id="@+id/discConverter"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="john.unitconverter.DisclaimerFragment"></fragment>

</LinearLayout>

what's inside the second fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="john.unitconverter.DisclaimerFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/disclaimer"
        android:text="landscape mode is missing some features." />
</FrameLayout>

what happens is the second fragment doesn't show in landscape. why is that happening? basically, only the first fragment is showing up in the screen both horizontal and vertical layout.
thanks

A: As said in the comment you have to use the weight attribute:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
    android:id="@+id/discConverter"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:name="com.example.trist_000.teststack.ArticleFragment"></fragment>

<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="0.1"/>

<fragment
    android:id="@+id/unitConverter"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:name="com.example.trist_000.teststack.ArticleFragment"></fragment>

</LinearLayout>

My fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/disclaimer"
    android:text="landscape mode is missing some features." />
</FrameLayout>

The result:


text:
Q: Parameter Integral Sin function, Gamma function Given $$ F: A \in\Bbb{R}\rightarrow\Bbb{R}$$ such that $$F(y)=\int\limits_{0}^{\pi/2} (sinx)^y(cosx)^{1-y} \; dx$$
Prove that $F(1/2)=\frac{1}{\sqrt\pi}(\Gamma(3/4))^2$ and then find the maximum domain $A$ such that $F$ exists.
$$\Gamma(s)= \int_0^\infty e^{-t}t^{s-1}dt$$
I arrived at $F(1/2)=\frac{\sqrt2}{2}\int\limits_{0}^{\pi/2}\sqrt\sin2x\;dx$ and that is about all that I can do.

A: Define
$$
\Gamma(z)=\int_0^{+\infty} t^{z-1}e^{-t}\,dt
$$
and
$$
B(z,w)=\int_0^1 t^{w-1}(1-t)^{z-1}\,dt.
$$
Then you should be able to conclude what you want from the following two results.

It holds that
  $$
B(z,w)=\frac{\Gamma(z)\Gamma(w)}{\Gamma(z+w)}.
$$

Proof
We make a calculation, changing coordinates,
$$
\begin{align}
\Gamma(z+w)B(z,w)&=\Gamma(z+w)\int_0^1 t^{w-1}(1-t)^{z-1}\,dt\\
&=[t=u/(1+u)]\\
&=\Gamma(z+w)\int_0^{+\infty} u^{w-1}\Bigl(\frac{1}{1+u}\Bigr)^{z+w}\,du\\
&=\int_0^{+\infty}\int_0^{+\infty} u^{w-1}\Bigl(\frac{1}{1+u}\Bigr)^{z+w} e^{-v}\,dv\,du\\
&=[s=v/(1+u)]\\
&=\int_0^{+\infty}\int_0^{+\infty}u^{w-1}s^{z+w-1}e^{-s(u+1)}\,ds\,du\\
&=\int_0^{+\infty}s^ze^{-s}\int_0^{+\infty}(us)^{w-1}e^{-su}\,du\,ds\\
&=\int_0^{+\infty}s^{z-1}e^{-s}\Gamma(w)\,ds\\
&=\Gamma(z)\Gamma(w).
\end{align}
$$

The following is valid for $a>-1$ and $b>-1$
  $$
\int_0^{\pi/2}(\sin \phi)^a(\cos\phi)^b\,d\phi = \frac{1}{2}B\bigl(\tfrac{a+1}{2},\tfrac{b+1}{2}\bigr).
$$

Proof
Just let $u=(\sin\phi)^2$.


text:
Q: Django Model Relationships (foreignkey) (manytomany) I'm totally new to django, coming from a PHP perspective. I want to write a real basic application with four classes: Book, Ebook, Genre and price. Each Book and Ebook should have one genre and many prizes. In a SQL-DB I'd put a field in Book and Ebook referencing to a genre table by id and a new table called something like Book_prices which is linking Books and Ebooks to prices.
table book_prices
id | type   | price
---+--------+------
1  |  book  | 3
2  |  book  | 3
3  |  ebook | 1

table book/ebook
id | ... | genre_id
---+-----+---------
1  |     | 5
2  |     | 7
3  |     | 9

Basically I want to add a list of prices and ONE genre for each Ebook and Book. How can I do this using the django model? I know of model.ForeignKey() which could be applied to each Book/Ebook referencing to a genre. But what about my prices? If I add a ForeignKey() to a price it can only reference to a Book OR Ebook.
class Book:
    name = models.CharField(max_length=100)
    pages = models.IntegerField()

class Ebook:
    name = models.CharField(max_length=100)
    filesize = models.FloatField()

class Genre:
    name = models.CharField(max_length=100)
    info = models.TextField()

class Price:
    currency = models.CharField(max_length=4)
    amount = models.FloatField()

A: Here's one way. It uses inheritance to reduce duplication between classes.
It uses the contenttypes framework.
Also your classes need to subclass django.db.models
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Genre(models.Model):
    name = models.CharField(max_length=100)
    info = models.TextField()

class Price(models.Model):
    currency = models.CharField(max_length=4)
    amount = models.FloatField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    book = generic.GenericForeignKey('content_type', 'object_id')

class BookBase(models.Model):
    name = models.CharField(max_length=100)
    genre = models.ForeignKey(Genre)

    class Meta:
        abstract = True

class Book(BookBase):
    pages = models.IntegerField()

class Ebook(models.Model):
    filesize = models.FloatField()

A: class Genre:
    name = models.CharField(max_length=100)
    info = models.TextField()

class Price:
    currency = models.CharField(max_length=4)
    amount = models.FloatField()

class Book:
    genre = models.ForeignKey(Genre)
    name = models.CharField(max_length=100)
    pages = models.IntegerField()
    prices = models.ManyToManyField(Price)

class Ebook:
    genre = models.ForeignKey(Genre)
    name = models.CharField(max_length=100)
    filesize = models.FloatField()
    prices = models.ManyToManyField(Price)

Get all prices for a Book instance.
b1 = Book.objects.get(id=1)
prices = b1.prices.all()

ManyToManyField creates an intermediate table behind the scenes, exactly like you
would have done, if you did it manually. You can even define explicitly this table,
in case you want to add more fields to it, with the through parameter
Also consider using DecimalField for prices.


text:
Q: How to inject something into JsonConverter implementation (MVC Core, .NET 4.6.1) Note
I don't believe this is a duplicate of this question. in which the objective is to deserialise a model using a non-default constructor, whereas I need my custom deserialiser, not the model, to instantiate using its non-default constructor, injecting some dependency set up in the API statup. I tried the JsonConstructor anyway, but it still produced the same error.

Newtonsoft.Json.JsonException: No parameterless constructor defined for 'Domain.UserProjector'.

I'm working on an API that should allow the consumer to dictate resource projections based on some query string parameters. I though it'd be easiest handling it during JSON serialisation.
The model
I decorate my model with the custom serialiser.
[JsonConverter(typeof(CustomProjector))]
public class SomeDTO { /* members */ }

The converter
I implement my custom serialiser, injecting the required HttpContext.
public class CustomProjector : JsonConverter
{
    public CustomProjector(IHttpContextAccessor httpContext)
    {
        /* IHttpContextAccessor is already set up in the dependency container. Then get the requirements from the query string. */
    }

    /* JsonConverter implementation */
}

The API method
And all I have to do is return the result.
public IActionResult GetSomething(int id)
{
    SomeDTO something = domain.GetSomething(id);

    return this.Ok(somthing);
}

Unfortunately this doesn't work because JsonConverter implementations need default constructors, and an error is thrown due to the paramaterised constructor in CustomProjector, producing an error:

Newtonsoft.Json.JsonException: No parameterless constructor defined for 'Domain.UserProjector'.

A possible solution is to simply provide CustomProjector with the query string and do the convertion manually.
The model
No decoration required.
public class SomeDTO { /* members */ }

The converter
HttpContext is replaced by the query string, since I'm going to instantiate it manually.
public class CustomProjector : JsonConverter
{
    public CustomProjector(string queryString)
    {
        /* Get requirements from query string. */
    }

    /* JsonConverter implementation */
}

The API method
Instantiate the converter, and use it convert, before returning the result.
public IActionResult GetSomething(int id)
{
    SomeDTO something = domain.GetSomething(id);

    CustomProjector projector = new CustomProjector(this.Request.QueryString.Value);
    string somethingSerialised = JsonConvert.SerializeObject(something, projector);

    return this.Ok(somethingSerialised);
}

or
Pass the individual query string parameters to the constructor, but this is essentially the same as the option above.
The model
public class CustomProjector : JsonConverter
{
    public CustomProjector(string reqParam1, string reqParam2)
    {
        /* Use requirements provided. */
    }

    /* JsonConverter implementation */
}

The API method
public IActionResult GetSomething(int id, string reqParam1, string reqParam2)
{
    SomeDTO something = domain.GetSomething(id);

    CustomProjector projector = new CustomProjector(reqParam1, reqParam2);
    string somethingSerialised = JsonConvert.SerializeObject(something, projector);

    return this.Ok(somethingSerialised);
}

I would like to avoid these solutions as it requires API methods to include the parameters and requires that each method converts the results manually, or the returned data will be incorrect.

Is there something I can change to make it work the way I want? Perhaps something to do with DI? Perhaps a different serialiser?
Much appreciated!


text:
Q: How to install Excel OLE DB to Windows Server 2008? We have a web server running Windows 2008 32-bit.
When we deploy a website that reads from Excel using OLE DB, we got this error

The 'Microsoft.ACE.OLEDB.12.0'
  provider is not registered on the
  local machine.

We don't want to install Microsoft Office on the server. Is there anything else we can do to solve this?
Thanks in advance.

A: Install Data Connectivity Components on the server
http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en


text:
Q: Creating a matrix of future values for a time series I have a time series in R.  I want to construct a matrix, where each row is the current observation, and each column represent the future values of that series, starting from that point.  eg:
x <- ts(1:25,start=2000, frequency=12)
maxHorizon <- 12

freq <- frequency(x)
st <- tsp(x)[1]-(1/freq)

actuals <- matrix(NA,length(x)-1,maxHorizon)
for(i in seq(1, (length(x)-1))) {
    xnext <- window(x, start=st+(i+1)/freq, end=st+(i+maxHorizon)/freq)
    actuals[i,1:length(xnext)] <- xnext
}
actuals

In this case, we've got a time series with 25 observations, so our final matrix has 24 rows.  Starting with row 1, the next 12 ovbservations are 2-13.  Row 2 is 3-13, etc.  At the end of the matrix we fill it in with NA values.
> x
     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2000   1   2   3   4   5   6   7   8   9  10  11  12
2001  13  14  15  16  17  18  19  20  21  22  23  24
2002  25

> actuals
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    2    3    4    5    6    7    8    9   10    11    12    13
 [2,]    3    4    5    6    7    8    9   10   11    12    13    14
 [3,]    4    5    6    7    8    9   10   11   12    13    14    15
 [4,]    5    6    7    8    9   10   11   12   13    14    15    16
 [5,]    6    7    8    9   10   11   12   13   14    15    16    17
 [6,]    7    8    9   10   11   12   13   14   15    16    17    18
 [7,]    8    9   10   11   12   13   14   15   16    17    18    19
 [8,]    9   10   11   12   13   14   15   16   17    18    19    20
 [9,]   10   11   12   13   14   15   16   17   18    19    20    21
[10,]   11   12   13   14   15   16   17   18   19    20    21    22
[11,]   12   13   14   15   16   17   18   19   20    21    22    23
[12,]   13   14   15   16   17   18   19   20   21    22    23    24
[13,]   14   15   16   17   18   19   20   21   22    23    24    25
[14,]   15   16   17   18   19   20   21   22   23    24    25    NA
[15,]   16   17   18   19   20   21   22   23   24    25    NA    NA
[16,]   17   18   19   20   21   22   23   24   25    NA    NA    NA
[17,]   18   19   20   21   22   23   24   25   NA    NA    NA    NA
[18,]   19   20   21   22   23   24   25   NA   NA    NA    NA    NA
[19,]   20   21   22   23   24   25   NA   NA   NA    NA    NA    NA
[20,]   21   22   23   24   25   NA   NA   NA   NA    NA    NA    NA
[21,]   22   23   24   25   NA   NA   NA   NA   NA    NA    NA    NA
[22,]   23   24   25   NA   NA   NA   NA   NA   NA    NA    NA    NA
[23,]   24   25   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA
[24,]   25   NA   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA

How can I do this without using the ugly for loop?
edit: it would be ok if the data were returned in another format, such as a data.frame or even a list of rows.
edit: here's some code to compare the 3 functions we have so far:
rm(list = ls(all = TRUE))

zach1 <- function(x,maxHorizon) {
    freq <- frequency(x)
    st <- tsp(x)[1]-(1/freq)

    actuals <- matrix(NA,length(x)-1,maxHorizon)

    for(i in seq(1, (length(x)-1))) {
        xnext <- window(x, start=st+(i+1)/freq, end=st+(i+maxHorizon)/freq)
        actuals[i,1:length(xnext)] <- xnext
    }

    actuals
}

zach2 <- function(x,maxHorizon) {
    t(apply(embed(c(x,rep(NA,maxHorizon)),maxHorizon),1,rev))[2:length(x),]
}

josh1 <- function(x,maxHorizon) {
    actuals <- outer(seq_along(x), seq_len(maxHorizon), FUN="+")
    actuals[actuals > length(x)] <- NA
    actuals <- actuals[1:(length(x)-1),]
    actuals <- apply(actuals,2,function(a) x[a])
    actuals
}

x <- ts(rnorm(10000),start=2000, frequency=12)

> system.time(actuals1 <- zach1(x, 6))
   user  system elapsed
  11.81    0.00   11.93

> system.time(actuals2 <- zach2(x, 6))
   user  system elapsed
   0.15    0.00    0.16

> system.time(actuals3 <- josh1(x, 6))
   user  system elapsed
      0       0       0

> all.equal(actuals1,actuals2)
[1] TRUE
> all.equal(actuals1,actuals3)
[1] TRUE

A: EDIT:  To fill the matrix with the elements of x (rather than their indices), you can pass outer() an 'anonymous function' of your own devising.  This should do the trick:
# Trying it out
x <- ts(rnorm(25),start=2000, frequency=12)
maxHorizon <- 12

actuals <- outer(seq_along(x), seq_len(maxHorizon),
                 FUN = function(X,Y) {x[X+Y]}
)

tail(actuals)
#             [,1]       [,2]       [,3]       [,4]      [,5] [,6] [,7] [,8] [,9]
# [20,] -1.2729640 -0.4983060  0.6199497 -2.0999648 0.1673402   NA   NA   NA   NA
# [21,] -0.4983060  0.6199497 -2.0999648  0.1673402        NA   NA   NA   NA   NA
# [22,]  0.6199497 -2.0999648  0.1673402         NA        NA   NA   NA   NA   NA
# [23,] -2.0999648  0.1673402         NA         NA        NA   NA   NA   NA   NA
# [24,]  0.1673402         NA         NA         NA        NA   NA   NA   NA   NA
# [25,]         NA         NA         NA         NA        NA   NA   NA   NA   NA
#       [,10] [,11] [,12]
# [20,]    NA    NA    NA
# [21,]    NA    NA    NA
# [22,]    NA    NA    NA
# [23,]    NA    NA    NA
# [24,]    NA    NA    NA
# [25,]    NA    NA    NA

A: This gets rid of the for loop, but I'm not sure if it's any more elegant:
t(apply(embed(c(x,rep(NA,maxHorizon)),maxHorizon),1,rev))[2:length(x),]
edit: it's a lot faster though.


text:
Q: Refactoring - Just code SqlParameterCollection.Add Method is obsolete I'm currently refactoring the code using the tool "Just code" which displayed one of the warnings as:

System.Data.SqlClient.SqlParameterCollection.Add(string,object) is obsolete.

Also from MSDN I found that:

SqlParameterCollection.Add Method (String, Object).
Note: This API is now obsolete.

I was wondering whether I should refactor this code :
SqlCommand cmdGetIds= oConn.CreateCommand();
cmdGetIds.CommandType = CommandType.StoredProcedure;
cmdGetIds.CommandText = "GetEmployeeId_sp";
cmdGetIds.Connection = oConn;

cmdGetIds.Parameters.Add("@User", "ADMIN");

A:
System.Data.SqlClient.SqlParameterCollection.Add(string,object) is
  obsolete.
  Warning   1   'System.Data.SqlClient.SqlParameterCollection.Add(string,
  object)' is obsolete: 'Add(String parameterName, Object value) has
  been deprecated.  Use AddWithValue(String parameterName, Object
  value).  http://go.microsoft.com/fwlink/?linkid=14202'

If you see this problem, you can solve it like this:
SqlCommand cmdGetIds= oConn.CreateCommand();
cmdGetIds.CommandType = CommandType.StoredProcedure;
cmdGetIds.CommandText = "GetEmployeeId_sp";
cmdGetIds.Connection = oConn;
cmdGetIds.Parameters.AddWithValue("@User", "ADMIN");


text:
Q: How to access private or protected methods from superclass with reflection? It is do possible to access private or protected methods with getDeclaredMethod(). Resulting method instance can be made accessible with setAccessible() and invoked.
But this technique allows to access "downmost" classe's method. Is it possible to access methods from superclass similarly?
I am doing service class which is used similar to PropertyChangeSupport class and which requires to access firePropertyChange method, which is protected in most implementations.
UPDATE
Suppose we don't want to hack overriding. I mean, we wish to find downmost protected method.


text:
Q: iText 5.0.0 where did RTF and HTML go? This question may seem stupid, but, so be it! I have a stupid problem then :-). Well, my problem is this : using this code
//PDF generation

PdfWriter.getInstance(document,
new FileOutputStream("PDFFile.pdf"));

//RTF generation

RtfWriter2.getInstance(document,
new FileOutputStream("RTFFile.rtf"));

//HTM generation

HtmlWriter.getInstance(document,
new FileOutputStream("HTMLFile.htm"));

(and some other lines) with iText version 2.1.7, every computer geek is able to produce files in PDF, RTF or HTM file formats from his Java code. Now, i've upgraded iText to latest version (5.0.0) and i am unable to locate RtfWriter2 (or old RtfWriter) or HtmlWriter. To be concise, i was wondering if anyone has any idea if the support for those file types was even maintained, since every search on web-search engines obviously pointed me to previous versions of iText, where, apparently, one was able to do everything. Any hints on the matter?

A: iText's rtf capabilities are still around.  I would just like to add more information because the prior answers did not completely state what you have to do.
First, visit http://mirrors.ibiblio.org/pub/mirrors/maven2/com/lowagie/itext-rtf/2.1.7/itext-rtf-2.1.7.jar to get itext-rtf.jar.  This has the entire rtf package, however it is not sufficient to work with RTF documents.  One class needed quite commonly when using the rtf package is com.lowagie.text.Document which is not included in the itext-rtf.jar distribution.
Secondly, visit http://grepcode.com/snapshot/repo1.maven.org/maven2/com.lowagie/itext/2.1.7.  Here you want to download itext-2.1.7.jar.  This is the itext jar file you will need in order to work with the iText-rtf library.  This is different than the current iText which now manages only pdf documents.  At 5.0.0, rtf broke off and pdf kept the current numbering system.  The rtf version number restarted and the rtf package now requires a different iText which will have the same version number as the rtf version number.
With these two downloads, you should be golden.
EDIT
Other resources I know of:

*

*IText Rtf API

*Some Examples - Take with a grain of salt because it really is not Java and it is older, but some of the code snippets work anyway when you cut/paste

I generally just answer the question/comment asked, however one can see the precarious position one might be in when doing new coding in itext-rtf.  Proceed with caution.

A: According to the iText website, in v5.0.0 they deliberately removed the RTF and HTML writers. On their history page (http://itextpdf.com/content/changelogs), they say:

"The toolbox and RTF support have been removed: they are now in a separate project at SourceForge."

I believe this is the link to the new separate iText RTF project: http://sourceforge.net/projects/itextrtf
And according to this thread: http://itext-general.2136553.n4.nabble.com/HTML-to-RTF-td2161984.html, the HTML support is taken over by the xhtmlrenderer project at https://xhtmlrenderer.dev.java.net (update: dead link. The project appears to have been renamed "Flying Saucer": new home at http://code.google.com/p/flying-saucer/, source at https://github.com/flyingsaucerproject/flyingsaucer).

A: according to the maven repository, the last version of itext to support rtf is 2.0.8
the itextrtf link on sourceforge in the previous answer seems to be vaporware, as there are no files available for download.

A: search.maven.org is a good resource for finding the jars you want. See http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.lowagie%22 for all of the com.lowagie jars available - currently includes itext, itext-rups, itext-rtf
Side note, this site also show what the latest versions are and when they were published - very handy!


text:
Q: Vue: how to define the if condition in my case I am currently working on a project facing below problem,

I would like to get the correct url from database if the thumbnail.url exist. Below is my json get from API for blog.thumbnail.url and also source code inspection.
I can see all the blog runs the :src='backendurl+blog.thumbnail.url' and the v-if is not working?
How to fix it if I want only run this code with vaild thumbnail.url?
Thanks
Stan
Json from API
Source code Inspection

A:

{{ blog.title }}

If that doesn't work, just write {{ blog }} and see what it displays, then write {{ blog.thumbnail }} to see what you get there. This way you can get to the right syntax step by step.
You don't need the backend url if it's on the same server, else backendurl + blog.thumbnail[0].url should work.


text:
Q: Social login on registration page for Stormpath I really hope this is my last question on the Stormpath API for a while. Making the switch from C# and PHP to node has been somewhat challenging.
I am trying to implement social login on the registration page. The pre-built option places it on the Login page only.
Rendering the page and adding elements to the Jade view is simple enough, but I need to get an oauthStateToken. Now I looked at how the login.js code does this:
        var oauth = require('../oauth');
        var oauthStateToken = oauth.common.resolveStateToken(req, res);
        var formActionUri = (config.web.login.uri + (nextUri ? ('?next=' + nextUri) : ''));

        var hasSocialProviders = _.some(config.web.social, function (socialProvider) {
          return socialProvider.enabled;
        });

        extend(options, {
          form: form,
          formActionUri: formActionUri,
          oauthStateToken: oauthStateToken,
          hasSocialProviders: hasSocialProviders
        });

So essentially it calls the oath files and goes through the code, theoretically, I could do something similar on register.js - essentially (just sample code):
    var oauth = require('../oauth');
    var _ = require('lodash');
    var hasSocialProviders = _.some(config.web.social, function (socialProvider) {
          return socialProvider.enabled;
    });
    var oauthStateToken = '';
    if (hasSocialProviders) {
          oauthStateToken = oauth.common.resolveStateToken(req, res);
    }

    helpers.render(req, res, view, {
        form: helpers.sanitizeFormData(req.body),
        formModel: viewModel.form
        oauthStateToken : oauthStateToken,
        hasSocialProviders: hasSocialProviders
    });

But of course I wouldn't want to meddle with the core files, and was thinking about creating a middleware function, something like app.use('/register', callFunction, router); but I am having some difficulty in conceptualizing how that would work. I seem to understand how stormpath lets me generate an oauth token which I store as a cookie using JWT but I'm having a hard time putting it together into working code without replicating a lot of code already existent in the library.
I can even kinda of get it working by using the REST API but I would like to use it within the express-stormpath library. So some explanation in the context of express-stormpath library would also be enlightening. OR am I overthinking this, should I just fork the library, make the changes to register.js and try for a push upstream?
Thanks again folks,

A: thanks for the question!
I've found a way to work around this in your application, without modifying the express-stormpath library.  You'll need to add a route handler for your registration route, and in that route handler you'll have to manually do the work to get the oAuthStateToken setup, then call next() to let express-stormpath continue handling the request for the registration page.  Here's what that looks like:
var cookieParser = require('cookie-parser');
var oauth = require('express-stormpath/lib/oauth');

// create your express server, 'app'

app.use('/register', cookieParser(), function (req, res, next) {
  var oauthStateToken = oauth.common.resolveStateToken(req, res);
  req.app.get('stormpathConfig').templateContext = {
    oauthStateToken: oauthStateToken
  };
  next();
});

app.use(stormpath.init(app, {
  // .. other config options
  web: {
    register: {
      view: 'views/register.jade'  // path to your custom registration file
    }
  }
}));

I hope this helps!  This certainly could be easier, this is a good feature request for the library.


text:
Q: NS_OPTIONS Bitmask Autogeneration I have a large enum (for the sake of transparency 63 values), and I am now creating a NS_Options bitflag based on that enum. Is there a way that I can write this so that it will be flexible?
The main concerns I have with hardcoding it are:

*

*If I add/remove an enum, I will have to manually add/remove it in my bitflag.

*There is a lot of typing to generate these.

*My .h file is getting intensely long (because I like to use whitespace and adequate comments)

The only solution I've come up with thus far is:
#define FlagForEnum(enum) 1 << enum

typedef NS_ENUM(NSInteger, ExampleEnum)
{
    Value1,
    Value2,
    ...
    ValueN
}

typedef NS_OPTIONS(NSNumber, ExampleEnumFlags)
{
    Value1Flag = FlagForEnum(Value1),
    Value2Flag = FlagForEnum(Value2),
    ...
    ValueNFlag = FlagForEnum(ValueN)
}

This is a barely adequate solution when I remove an enum (at least I get a compile error), and if the enum ordering gets changed, the flags' bitshifted position changes too (not that it truly matters, but it seems comforting). But it doesn't solve the 'this-is-a-lot-of-typing' problem, or the 'what-if-I-forget-to-add-a-flag' problem.

A: You can use a technique called X Macro
#define VALUES \
  VALUE_LINE(Value1) \
  VALUE_LINE(Value2) \
  VALUE_LINE(Value3)

typedef NS_ENUM(NSUInteger, ExampleEnum)
{
#define VALUE_LINE(x) x,
VALUES
#undef VALUE_LINE
}

typedef NS_OPTIONS(NSUInteger, ExampleEnumFlags)
{
#define VALUE_LINE(x) x##Flag = 1 << x,
VALUES
#undef VALUE_LINE
}

A: Here is a slightly better (in terms of less typing) preprocessor #define solution. Although this still isn't as elegant as I'd like.
#define BitShift(ENUM_ATTRIBUTE)            (1 << ENUM_ATTRIBUTE)
#define CreateEnumFlag(ENUM_ATTRIBUTE)      ENUM_ATTRIBUTE##Flag = BitShift(ENUM_ATTRIBUTE)

typedef NS_ENUM(NSUInteger, ExampleEnum)
{
    Value1,
    Value2,
    ...
    ValueN
}

typedef NS_Options(NSUInteger, ExampleEnumFlags)
{
    CreateEnumFlag(Value1),
    CreateEnumFlag(Value2),
    ...
    CreateEnumFlag(ValueN)
}

This will create flags of the form Value1Flag, Value2Flag, ..., ValueNFlag.


text:
Q: Laravel Editing post doesn't work There are routes
Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show')->name('posts.show');
Route::get('get-random-post', 'PostsController@getRandomPost');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('unpublish', 'PostsController@unpublish');
Route::post('delete', 'PostsController@delete');
Route::post('restore', 'PostsController@restore');
Route::post('change-rating', 'PostsController@changeRating');

Route::get('dashboard/posts/{id}/edit', 'PostsController@edit');
Route::put('dashboard/posts/{id}', 'PostsController@update');

Route::get('dashboard', 'DashboardController@index');
Route::get('dashboard/posts/{id}', 'DashboardController@show')->name('dashboard.show');
Route::get('dashboard/published', 'DashboardController@published');
Route::get('dashboard/deleted', 'DashboardController@deleted');

methods in PostsController
public function edit($id)
{
    $post = Post::findOrFail($id);
    return view('dashboard.edit', compact('post'));
}

public function update($id, PostRequest $request)
{
    $post = Post::findOrFail($id);
    $post->update($request->all());
    return redirect()->route('dashboard.show', ["id" => $post->id]);
}

but when I change post and click submit button, I get an error

MethodNotAllowedHttpException in RouteCollection.php line 233:

What's wrong? How to fix it?
upd
opening of the form from the view
{!! Form::model($post, ['method'=> 'PATCH', 'action' => ['PostsController@update', $post->id], 'id' => 'edit-post']) !!}

and as result I get
<form method="POST" action="http://mytestsite/dashboard/posts?6" accept-charset="UTF-8" id="edit-post"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="aiDh4YNQfLwB20KknKb0R9LpDFNmArhka0X3kIrb">

but why this action http://mytestsite/dashboard/posts?6 ???

A: Try to use patch instead of put in your route for updating.

Just a small tip you can save energy and a bit of time by declaring the Model in your parameters like this:

public function update(Post $id, PostRequest $request)

and get rid of this
 $post = Post::findOrFail($id);

EDIT

You can use url in your form instead of action :
'url'=> '/mytestsite/dashboard/posts/{{$post->id}}'

A: Based on the error message, the most probable reason is the mismatch between action and route. Maybe route requires POST method, but the action is GET. Check it.

A: Try to send post id in hidden input, don't use smt like that 'action' => ['PostsController@update', $post->id]
It contribute to result action url.


text:
Q: MongoDB (PHPLib) ObjectID changes after upsert I am having a problem with MongoDB ID changing after I upsert a document.
public function upsert(User $user) {
    $userMongo = new UserMongo($user);

    if(!$userMongo->getUuid()) {
      $userMongo->setUuid(new ObjectID);
      $this->collection->insertOne($userMongo);

    } else {
      $userMongo->setUuid(new ObjectID($userMongo->getUuid()));
      $this->collection->updateOne(["_id" => $userMongo->getUuid()], ["\$set" => $userMongo]);
    }

    $userMongo->setUuid($userMongo->getUuid()->__toString());
    return $userMongo;
  }

This should create a new document from php object with newly created objectID, and return the php object with created ObjectID. However this returns ObjectID A(ie. "5986c0c8e13823329a682c81") and stores it as ObjectID B(ie. "5986c0c8e13823329a682c82"). The stored ObjectID and returned ObjectID are slightly different (last digit).
Why am I getting different ObjectIDs and how can I retrieve the ObjectID of newly created document from upsert?


text:
Q: Jenkins: How to access parameters in a parameterized job I have a parameterized build like below:

then i've create a groovy script to create a variable URL_TOMCAT where its value depends on the TARGET_TOMCAT parameter:
Even after this update i got the same error
import hudson.model.*
def target = build.buildVariableResolver.resolve("TARGET_TOMCAT")
def URL_TOMCAT = ""
switch(target ) {
  case "tomcat1": URL_TOMCAT= "http://localhost:8080/manager/text"
   break
  case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
   break
}

Then i want to get The URL_TOMCAT value and adjust the maven build step as shown:

But i got this error :

Has any on an idea how to fix this error?

A: In your groovy script you need to make an API call to get the value of the parameter from Jenkins into your workspace.
Import hudson.model

def targetTomcat = build.buildVariableResolver.resolve("TARGET_TOMCAT")

def URL_TOMCAT = ""
switch(targetTomcat) {
  case "tomcat1": URL_TOMCAT = "http://localhost:8080/manager/text"
    break
  case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
    break
}

I want to point out that the URL_TOMCAT variable won't be available to any other buildsteps, it's scoped to just the groovy build step. If you want to expose your URL_TOMCAT variable to the rest of the build you'll need to expose it to the build environment somehow.  I normally do this by writing the value to a file as a key value pair and using the EnvInject Plugin
You can write it to a file in groovy like so:
def workspace = build.buildVariableResolver.resolve("WORKSPACE")
new File("${workspace}\\Environment.Variables").write("URL_TOMCAT=${URL_TOMCAT}")

If you don't want to write it to the jobs workspace you can skip grabbing that value and just code a specific path.
After your groovy build step add an Envinject build step and enter the path to the file containing the key value pair in the Properties File Path field. You should be able to reference URL_TOMCAT like any other environment variable in the rest of the build.  Continuing with the about path I would use ${WORKSPACE}\Environment.Variables as the path.


text:
Q: check current category of layered navigation in magento get current category in layer navigation,im using this code but it is not working please help
<?php $_helper = $this->helper('catalog/output') ?>
          <?php $_category = $this->getCurrentCategory(); >

A: please use the below code
if(Mage::registry('current_category'))
    {
    $cat=Mage::registry('current_category')->getId();
    /* used for category level*/
    }
    else{
    $cat=2; // 2 is root category id
    /* used for serch level*/
    }

hope it will be working

A: If you want to get Current Category id on navigation, you can do like this.
 <?php $layer = Mage::getSingleton('catalog/layer');
$_category = $layer->getCurrentCategory();
$currentCategoryId= $_category->getId();?>

Hopes this will solve your problem.


text:
Q: React Hooks useState promptly Update How can I promptly update the number state and watch console.log(number) updated value?
    const [number,setNumber] = useState(0);
    const minus = () => {
      setNumber(number-1);
      console.log(number);
    }
    return (
     <>

{number}

      <button onClick={minus}>-</button>
     </>
    )

A: Try this
 setNumber((number)=> {number-1 ; console.log(number)});

A: const [number,setNumber] = useState(0);
    const minus = () => {
      // setNumber(number-1);
      // It is also work well but it is working with async.
      // So you can't see the below console.log().
      // console.log(number);
      setNumber((prevNumber) => {
        newNumber = prevNumber - 1;
        console.log(newNumber);
        return newNumber;
      });
    }

    return (
     <>

{number}

      <button onClick={minus}>-</button>
     </>

)

A: What you are trying to do is a side-effect: print something onto the console.
This is what useEffect hook is for - it lets you perform side effects.
So here is a possible implementation:
function App() {
  const [number, setNumber] = useState(0);
  const minus = () => {
    setNumber(number - 1);
  };
  useEffect(() => {
    console.log(number);
  }, [number]);
  return (
    <>

{number}

      <button onClick={minus}>-</button>
    </>
  );
}

Of course, it may be an overkill solution if you are just using console.log for debugging purpose. If that's the case, @zynkn and @deepak-k's answers work just fine.


text:
Q: How to delete SPO sites by URL web address not site name in PS I have several SharePoint online sites (hundreds) every about 4 of them are created with the same name/title but they differ in the url web address. Now I need to delete specific one of each 4 which I have the URL address in a spreadsheet, so is it possible to delete them with specifying the url in the Powershell script instead of the name/title? I hope it's possible because it will take forever to check each site individual and delete the correct one.
For example the sites look like this:
AAA - .../siteaaa1
AAA - .../siteaaa2
AAA - .../siteaaa3
AAA - .../siteaaa4
ABB - .../siteabb1
ABB - .../siteabb2
and so on..
Will be great help if someone know how.
Many thanks

A: To delete an individual subsite using urls, you can use the below code in powershell:
$SiteURL = "https://tenant.sharepoint.com/sites/site/siteAA1"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$User = "admin@tenant.onmicrosoft.com"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

$Context.Credentials = $Creds

$web = $Context.Web

$Context.Load($web)
$Context.ExecuteQuery()

$web.DeleteObject()
$Context.ExecuteQuery()
Write-Host $web.Title "Site Deleted"

Or if you know the urls, you can specify them in an array and then delete them via server relative url as below:
#enter the site collection url
$SiteURL = "https://tenant.sharepoint.com/sites/site/"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$User = "admin@tenant.onmicrosoft.com"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Context.Credentials = $Creds

#enter server relative path of the subsite in the array
#for first level subsite, it will be "siteaa1" - url would be ""https://tenant.sharepoint.com/sites/site/siteaa1"
#for second level subsite, it will be "subsite/siteaa1" - url would be ""https://tenant.sharepoint.com/sites/site/subsite/siteaa1"

$array = @("siteaaa1", "siteaaa2", "siteaaa3")
for ($i=0; $i -lt $array.length; $i++)
{

    $web = $Context.Site.OpenWeb($array[$i]);

    $Context.Load($web)
    $Context.ExecuteQuery()

    $web.DeleteObject()
    $Context.ExecuteQuery()
    Write-Host $web.Title "Site Deleted"

}

Download & install the SharePoint client component SDK  which will give you the CSOM dlls.
Also download the SP online management shell to run the above code.
SharePoint 2013 Client component SDK
SharePoint online management shell


text:
Q: Query is taking too much time to execute so how can I reduce time using datepart select
    datepart(mm, dbo.axfnGetOrgDate()) As orgmonth,
    datepart(mm, rtlposslip.salesdate) as orgmonth2
from
    rtlposslip (nolock)
where
    rtlposslip.employeeusercode = 'DB@gmail.com'
    and datepart(mm, rtlposslip.salesdate) = datepart(mm, dbo.axfnGetOrgDate())

A: If you really want to fetch the same month from each year, it's not so simple and most likely will not improve the performance because it's unlikely that index can be used if you'll add a lot of 1 month date ranges with or.
But if you're returning a lot of rows, the problem you have might actually be dbo.axfnGetOrgDate(), because it is being called separately for every single row the select returns.


text:
Q: upgrade Flutter SDK to the last version and get and Error with If upgrade Flutter SDK to the last version and get and Error with If  in the column of widget while using if to show one of widget after setstate and variable be true as shown in the image enter image description here

A: Here they talk about other flutter update. They said you should upgrade your min Dart version at pubspec.yaml
Not sure if it will work but it's a similar issue than yours.
Maybe as a temp fix you could try the sintax:
Condition ? True : False
Ups, I forgot the link :)
flutter --flow-control-collections are needed, but are they?

A: You can fix this by replacing the if else statement with Ternary operators.
Ternary Operators are shorter ways of if-else statement. Syntax is :
testCondition ? trueValue : falseValue
Check the code below: it works fine.
 _isLoading
          ? CircularProgressIndicator()
          : RaisedButton(
              onPressed: () {},
              child: Text('Sign up'),
            ),

I hope this helps.

A: i change the SDK environment to sdk: '>=2.8.0 <3.0.0' and then flutter clean


text:
Q: Cookie token doesn't match database I have a token in my MySQL database on every user. When I login this token will be stored as a cookie, but when I look at the cookie value it doesn't match the one I have in the database.
An example
In the database: $6$8J/S65L0$1bQJrlRBYTg6UTvLBKwFwRYzob2kMkv1eFuX693fVWFOiHLo6f7FXLwlo/b6WzDupUW9VrDvpqWk1F/RAncaA.
In the cookie:
%246%248J%2FS65L0%241bQJrlRBYTg6UTvLBKwFwRYzob2kMkv1eFuX693fVWFOiHLo6f7FXLwlo%2Fb6WzDupUW9VrDvpqWk1F%2FRAncaA.
Why is that? I use setcookie("token", $r['token'], $expire); to store the token as a cookie.

A: Looks like you need to use this function: http://www.php.net/manual/en/function.htmlspecialchars-decode.php.
Edit: The values looks to be the same, just that the value in the cookie is URL encoded


text:
Q: How do I open a binary file using a string? Using C I was under the impression that to open binary files using strings, you could simply create the string, and then implement it as the name of the file where it will read the string. This is what my lecture notes state. However I'm obveously missing something. I've used &name, name, &name[SIZE] within the fopen and each time i've gotten inBinFile == NULL unless I use the commented line. My string is correct. What's wrong? Help is much appreciated. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 25

int frstmenu(void);
int sndmenu(void);

int main()
{

    int fmenu, smenu;
    char name[SIZE];
    FILE *inBinFile;
    unsigned char numRead;

  fmenu = frstmenu();
  if ( fmenu !=1 && fmenu !=2 )
  {
        printf("\nIncorrect option\n");
        fmenu = frstmenu();
  }

  if (fmenu == 1)
  {
       printf("\nEnter the file name: \n");
       scanf("%s", &name[SIZE]);
       /* printf("filename: %s", &name[SIZE]); */

       smenu = sndmenu();

       if (smenu !=1 && smenu !=2 )
       {
           printf("\nIncorrect option\n");
           smenu = sndmenu();
       }
       if (smenu == 1)
       {

           inBinFile = fopen( name, "rb");
        /* inBinFile = fopen( "stream.grc", "rb"); */

        if (inBinFile == NULL)
        {
          fprintf(stderr, "Error opening %s", &name[SIZE]);
          return(-1);

        fclose(inBinFile);
       }
  }
  return(0);
}

int frstmenu()
{

  float selection;

  printf("----Menu----\n");
  printf("1 Open a file ( supported format: .grc )\n");
  printf("2 Exit the program\n");
  printf("  Please select an option (1 or 2): ");
  scanf("%f", &selection);

  return(selection);

}

int sndmenu()

{

int selection;

 printf("---Menu---\n");
 printf("1 Decode the sequence\n");
 printf("2 Exit the program\n");
 printf("  Please select an option (1 or 2):\n");
 scanf("%i", &selection);

 return(selection);
}

A: You probably want to say
scanf("%s", &name[0]);

or even just:
scanf("%s", name);

Your &name[SIZE] points to name + SIZE, which is beyond the allocated memory.


text:
Q: Remove rows based on mode Data:
 df <- data.frame("y"= c(rep(100,10), rep(103,10)), "x" = c(rep(1,8),2,2,rep(4,5),7,7, rep(4,3)) )

For each value of y, we expect a unique value of x. But in data, we have a couple of unwanted values. Based on mode, we can find the corresponding value of x for each value of y.
Can we identify the row numbers where there is unwanted pairing ?
Expected output:
9, 10, 16, 17

A: We can use ave to group by 'y', get the logical index of elements in 'x' that are not the 'Mode', from there get the row index with which.
with(df, which(as.logical(ave(x, y, FUN= function(x) x!=Mode(x)))))
#[1]  9 10 16 17

Or as @thelatemail mentioned in the comments, the above can be made compact
which(with(df, x != ave(x, y, FUN=Mode) ))

where Mode is (taken from here)
Mode <- function(x) {
  ux <- unique(x)
 ux[which.max(tabulate(match(x, ux)))]
}


text:
Q: Firebase Java API with push utf8 string I'm using java to push string to firebase, the code is very simple:
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("title", "Khao khát cuộc sống bình thường sau Masters 2016");
firebase.post("posts", dataMap);

But the result on firebase is:
title: "khao kh�t cu?c s?ng b�nh th??ng sau Masters 2016"

I don't want to convert the string to byte array before push to Firebase.
What is problem and how can I solve that?
Thank you.

A: The Firebase Java SDK doesn't have a method called post(), so I assume you're using some other library to write to the database. How are you writing to Firebase?
I just added the same text with the Java client:
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/36776859");
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("title", "Khao khát cuộc sống bình thường sau Masters 2016");
ref.updateChildren(dataMap);

and it shows up perfectly:
{
  "title": "Khao khát cuộc sống bình thường sau Masters 2016"
}

So most likely the client you are using is either breaking the text already or fails in how it transfer it to Firebase.

A: I found out the reason. It's because I'm using Java client firebase4j by Brandon Gresham. In that client, they are using StringEntity without set Charset. To fix it, just add StandardCharsets.UTF_8
In net/thegreshams/firebase4j/service/Firebase.java, line 422, modify:
result = new StringEntity(jsonData);

To
result = new StringEntity(jsonData, StandardCharsets.UTF_8);


text:
Q: Bash script runs manually, but fails on crontab I'm a newbie to shell scripting. I have written a shell script to do incremental backup of MySQL database.The script is in executable format and runs successfully when executed manually but fails when executed through crontab.
Crontab entry is like this :
*/1 * * * * /home/db-backup/mysqlbackup.sh

Below is the shell script code -
#!/bin/sh
MyUSER="root"       # USERNAME
MyPASS="password"         # PASSWORD
MyHOST="localhost"  # Hostname
Password="" #Linux Password

MYSQL="$(which mysql)"
if [ -z "$MYSQL" ]; then
echo "Error: MYSQL not found"
exit 1
fi
MYSQLADMIN="$(which mysqladmin)"
if [ -z "$MYSQLADMIN" ]; then
    echo "Error: MYSQLADMIN not found"
    exit 1
fi
CHOWN="$(which chown)"
if [ -z "$CHOWN" ]; then
    echo "Error: CHOWN not found"
    exit 1
fi
CHMOD="$(which chmod)"
if [ -z "$CHMOD" ]; then
    echo "Error: CHMOD not found"
    exit 1
fi

GZIP="$(which gzip)"
if [ -z "$GZIP" ]; then
    echo "Error: GZIP not found"
    exit 1
fi
CP="$(which cp)"
if [ -z "$CP" ]; then
    echo "Error: CP not found"
    exit 1
fi
MV="$(which mv)"
if [ -z "$MV" ]; then
    echo "Error: MV not found"
    exit 1
fi
RM="$(which rm)"
if [ -z "$RM" ]; then
    echo "Error: RM not found"
    exit 1
fi
RSYNC="$(which rsync)"
if [ -z "$RSYNC" ]; then
    echo "Error: RSYNC not found"
    exit 1
fi

MYSQLBINLOG="$(which mysqlbinlog)"
if [ -z "$MYSQLBINLOG" ]; then
    echo "Error: MYSQLBINLOG not found"
    exit 1
fi
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y-%T")"

DEST="/home/db-backup"
mkdir $DEST/Increment_backup.$NOW
LATEST=$DEST/Increment_backup.$NOW
$MYSQLADMIN -u$MyUSER -p$MyPASS flush-logs
newestlog=`ls -d /usr/local/mysql/data/mysql-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1`
echo $newestlog
for file in `ls /usr/local/mysql/data/mysql-bin.??????`
do
        if [ "/usr/local/mysql/data/mysql-bin.$newestlog" != "$file" ]; then
     echo $file
     $CP "$file" $LATEST
        fi
done
for file1 in `ls $LATEST/mysql-bin.??????`
do
 $MYSQLBINLOG $file1>$file1.$NOW.sql
 $GZIP -9 "$file1.$NOW.sql"
 $RM "$file1"
done
$RSYNC -avz $LATEST /home/rsync-back

*

*First of all, when scheduled on crontab it is not showing any errors. How can I get to know whether the script is running or not?

*Secondly, what is the correct way to execute the shell script in a crontab.
Some blogs suggest for change in environment variables. What would be the best solution

When I did $echo PATH, I got this
/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin

A: My Issue was that I set the cron job in /etc/cron.d (Centos 7). It seems that when doing so I need to specify the user who executes the script, unlike when a cronjob is entered at a user level.
All I had to do was
*/1 * * * * root perl /path/to/my/script.sh
*/5 * * * * root php /path/to/my/script.php

Where "root" states that I am running the script as root.
Also need to make sure the following are defined at the top of the file. Your paths might be different. If you are not sure try the command "which perl", "which php".
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin

A: The problem is probably that your $PATH is different in the manual environment from that under which crontab runs. Hence, which can't find your executables. To fix this, first print your path in the manual environment (echo $PATH), and then manually set up PATH at the top of the script you run in crontab. Or just refer to the programs by their full path.
Edit: Add this near the top of your script, before all the which calls:
export PATH="/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin"

A: Another more generic way is to have cron run the user's bash logon process.  In addition to the PATH, this will also pick up any LD_LIBRARY_PATH, LANG settings, other environment variables, etc.  To do this, code your crontab entry like:
34  12  * * *   bash -l /home/db-backup/mysqlbackup.sh

A: Just import your user profile in the beginning of the script.
i.e.:
. /home/user/.profile

A: *

*In your crontab file your script entry can have
* * * * * /bin/bash /path/to/your/script

*Make sure to use full paths in your script. I have had a look through it and I have not seen any but just in case I missed it.

A: first run command env > env.tmp then run cat env.tmp copy PATH=.................. Full line and paste into crontab -e, line before your cronjobs. as like below
++=============================================================++
(# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
PATH=/root/.nvm/versions/node/v18.12.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/sna>

# m h  dom mon dow   command
0 3 * * * bash /home/ubuntu/test.sh
* * * * * bash /home/ubuntu/test2.sh >> /home/ubuntu/cronlog.log
* 3 * * * bash /home/ubuntu/logscron.sh)
++=====================================================================++


text:
Q: How to rename multiple files in bash? Files are -
new_file.dat01,
new_file.dat02 and so on

i want to rename it as new_file_01.dat, new_file_02.dat and so on.
Any ideas on how to do it?

A: What about:
for f in *file.dat*; do mv "$f" "$(echo "$f" | sed -E 's/.dat(.*)/_\1.dat/')";done


text:
Q: Java, Spring : Finding objects within a given time-frame not working after adding time-zone to java.sql.Timestamp I am working on a Spring-MVC project in which I have a GroupNotes object which I am trying to search for within a given time-frame to inform user. The time was originally saved in Postgresql Timestamp object without timezone. Later we added timezone to it. But since we have done that, we couldn't find any objects, the DAO code is not working. We modified the PostgreSQL column as well as model definition for migrating to with time zone.
DAO code :
@Override
    public List<GroupNotes> findGroupNotesWithExpiryInTwelveHours() {
        Session session = this.sessionFactory.getCurrentSession();
        long currentTime = System.currentTimeMillis();
        long plus47Hours = currentTime + (11 * 60 * 60 * 1000);
        Timestamp plus47HoursTS = new Timestamp(plus47Hours);

        long plus48Hours = currentTime + (12 * 60 * 60 * 1000);
        Timestamp plus48HoursTS = new Timestamp(plus48Hours);

        Query query = session.createQuery("from GroupNotes as gn where gn.zugwisenPersonId!=:val and gn.noteTarget > :from and gn.noteTarget < :to");
        query.setParameter("val", 0);
        query.setParameter("from", plus47HoursTS);
        query.setParameter("to", plus48HoursTS);
        return query.list();
    }

GroupNotes object :
@Entity
@Table(name = "groupnotes")
public class GroupNotes implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "notetarget",columnDefinition = "timestamp with time zone")
    private java.sql.Timestamp noteTarget;

// Other columns
}

Service layer method calling the code :
// Also, can someone tell me if below script will execute every 2 hours?
  @Override
    @Scheduled(cron = "0 0 0/2 * * *")
    public void checkForZugweisedNotesAndSendEmail() {

  List<GroupNotes> twelveHourList = this.groupNotesService.findGroupNotesWithExpiryInTwelveHours();
            for (GroupNotes groupNotes : twelveHourList) {
// Perform operations
}

A: I don't understand why you want to use hard way.I believe you already changed data type in your postgre side to timestamp.So you just need to change you entity like this
@Column(name = "notetarget",columnDefinition = "timestamp with time zone")
@Temporal(TemporalType.TIMESTAMP)//declare timestamp
private Date noteTarget;//no need to use java.sql.Timestamp

In your method just use date and set particular times accordingly likes
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,11);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date plus47Hours  = cal.getTime();

And then you can change your query simply
from GroupNotes as gn where gn.zugwisenPersonId!=:val and gn.noteTarget between :from and :to


text:
Q: Is this a valid use case for Euclidean distance? I have a set of points which is a count of links that users have clicked on :
         link1,link2,link3,link4
user1,   0    ,2    ,3    ,2
user2,   1    ,4    ,0    ,5

I am not sure which distance function I should use to calculate the distance between users. I think Euclidean distance is a good fit (reading http://en.wikipedia.org/wiki/Euclidean_distance) ?

A: Mahalonobis distance could be better, because it takes into account the variability of number of clicks on the links. Say you have an unpopular link, then when someone clicks on it often, the weight of this link in the distance will be much higher, so you'll separate this user from others.

A: I think cosine distance will be better in this situation and it gives you direction and is more robust than the usual distanc measures like euclidean/mahalonobis. You can also try manhattan distance
and check how's the result.


text:
Q: Flutter provider assistance please I am trying to pass my _myUnit.unit value from this custom widget to my screen that calls the widget to confirm what units a user has selected. Currently I am able to print the correct values when the Icons.loop is pressed but don't have access when I press calculate on my implementation screen. Any advice? I think I have to get rid of my ValueListenableBuilder and change to provider?
Piece of widget to change units
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';

import 'my_unit.dart';

enum Units { unitImperial, unitMetric }
typedef OnSaved(value);

class TextFieldEntry extends StatefulWidget {
  TextFieldEntry(
      {required this.name, required this.onSaved, this.formCallBackFunction});

  final String name;
  final OnSaved onSaved;
  final Function? formCallBackFunction;

  final myDecorationField = InputDecoration(
    labelText: 'textFieldName',
    labelStyle: TextStyle(fontSize: 20, color: Colors.pink),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.only(
        topRight: Radius.circular(0),
        bottomRight: Radius.circular(0),
      ),
      borderSide: BorderSide(
        width: 1,
        color: Colors.pink,
      ),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.only(
        topRight: Radius.circular(0),
        bottomRight: Radius.circular(0),
      ),
      borderSide: BorderSide(
        color: Colors.pink,
        width: 1,
      ),
    ),
  );

  @override
  State<TextFieldEntry> createState() => _TextFieldEntryState();
}

class _TextFieldEntryState extends State<TextFieldEntry> {
  var _validator;
  var _keyboard;
  var _myUnit;

  String unitSelected = 'unit Error';

  Widget build(BuildContext context) {
    if (widget.name == 'height') {
      final heightValidate = FormBuilderValidators.compose([
        FormBuilderValidators.required(context),
        FormBuilderValidators.numeric(context),
        FormBuilderValidators.max(context, 200),
        FormBuilderValidators.min(context, 30)
      ]);

      _validator = heightValidate;
      _keyboard = TextInputType.number;
      _myUnit = MyUnit();
    } else if (widget.name == 'weight') {
      final weightValidate = FormBuilderValidators.compose([
        FormBuilderValidators.required(context),
        FormBuilderValidators.numeric(context),
        FormBuilderValidators.max(context, 450),
        FormBuilderValidators.min(context, 30)
      ]);

      _validator = weightValidate;
      _keyboard = TextInputType.number;
      _myUnit = MyUnit(imperial: 'lbs', metric: 'kg');

} else {
      _validator = null;
      _myUnit = null;
    }

    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: Column(
        children: [
          Container(
            constraints: BoxConstraints(
                maxWidth: 375,
                maxHeight: widget.name == 'Description' ? 100 : 50),

//- Textformfield code

            child: Row(
              children: [
                Expanded(
                  child: FormBuilderTextField(
                    name: widget.name,
                    maxLines: widget.name == 'Description' ? 5 : 1,
                    decoration: widget.myDecorationField.copyWith(
                        labelText: widget.name,
                        labelStyle: TextStyle(
                            color: Theme.of(context).colorScheme.primary),
                        focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                color: Theme.of(context).colorScheme.primary)),
                        enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                                color: Theme.of(context).colorScheme.primary))),
                    onSaved: widget.onSaved,
                    validator: _validator,
                    keyboardType: _keyboard,
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                      border: Border.all(
                          color: Theme.of(context).colorScheme.primary,
                          width: _myUnit != null ? 2 : 0)),

//- Text for the unit changing button (i.e. inches)
                  child: Row(
                    children: [
                      if (_myUnit != null)
                        Container(
                          padding: EdgeInsets.all(5),
                          child: Center(
                            child: ValueListenableBuilder<Units>(
                                valueListenable: _myUnit,
                                builder: (context, unit, _) => AutoSizeText(
                                      _myUnit.unitType,
                                      style: TextStyle(
                                          color: Theme.of(context)
                                              .colorScheme
                                              .onPrimary,
                                          fontSize: 20,
                                          fontWeight: FontWeight.w500),
                                    )),
                          ),
                        ),
                     Builder(
                        builder: (context) {
                          void changeUnit() {
                            Units unit = _myUnit.unit;
                            _myUnit.unit != null
                                ? _myUnit.unit = unit == Units.unitImperial
                                    ? Units.unitMetric
                                    : Units.unitImperial
                                 : '';
                          }
                          void updateSelectedUnit() {
                            widget.selectedUnit = '${_myUnit.unitType}';
                            print(widget.selectedUnit);
                          }

                          if (widget.name == 'height' ||
                              widget.name == 'weight'
                              ) {
                            return Container(
                              constraints:
                                  BoxConstraints(maxHeight: 50, maxWidth: 60),
                              child: TextButton(
                                onPressed: () {
                                  changeUnit();
                                  updateSelectedUnit();
                                },
                                child: Center(
                                  child: Icon(Icons.loop,
                                      size: 30,
                                      color: Theme.of(context)
                                          .colorScheme
                                          .onPrimary),
                                ),
                              ),
                            );
                          } else {
                            return Container();
                          }
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 12,
          )
        ],
      ),
    );
  }
}

MyUnit widget
class MyUnit extends ValueNotifier<Units> {
  //You want to check when the enum Units change, so that will be your ValueNotifier
  final String _imperial;
  final String _metric;

  MyUnit(
      {Units unit = Units.unitImperial,
      String imperial = 'inches',
      String metric = 'cm'})
      : _imperial = imperial,
        _metric = metric,
        super(unit);

  String get unitType => value == Units.unitImperial
      ? _imperial
      : _metric; //The labels you define, just like unit1 and unit2 in TextFieldEntry
  Units get unit => value; //the enum value
  set unit(Units newUnit) =>
      value = newUnit; //when this change, it will rebuild the listeners
}

Example implementation
class Input {
  var title;
  var unit;

  Input({
    this.title,
    this.unit,
  });
}

class BMIDosing extends StatefulWidget {

  @override
  State<BMIDosing> createState() => _BMIDosingState();
}

class _BMIDosingState extends State<BMIDosing> {
  final _formKey = GlobalKey<FormState>();

List<Input> _traditionalList = [
    Input(
      title: 'height',
    ),
    Input(
      title: 'weight',
    ),
    Input(title: 'age'),];

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(title: 'Traditional'),
      drawer: MainDrawer(),
      body: SingleChildScrollView(
          child: Form(
        key: _formKey,
        child: Center(
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Container(
                constraints:
                    BoxConstraints(maxHeight: 475, maxWidth: 375), //Needed
                child: ListView.builder(
                    itemCount: _traditionalList.length,
                    itemBuilder: (BuildContext inp, index) {
                      return _traditionalList[index].title ==
                                                      'height' ||
                                                  _traditionalList[index]
                                                          .title ==
                                                      'weight' ||
                                                  _traditionalList[index]
                                                          .title ==
                                                      'age'
                                              ? TextFieldEntry(
                                                  name: _traditionalList[index]
                                                      .title,
                                                  onSaved: (value) {
                                                    _traditionalList[index]
                                                        .title = value;
                                                  },
                                                );

 }),
              ),
              ElevatedButton(
                child: Text('Calculate'),
                onPressed: () {
                  // if (_formKey.currentState!.validate()) {
                  _formKey.currentState?.save();
                  }

A: Pass ValueNotifier from "screen" to "widget". "screen" has access to value, while "widget" sets new value.
Screen
class Screen extends StatelessWidget {
  final ValueNotifier<int> _counter = ValueNotifier<int>(0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Child(_counter),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.calculate),
        onPressed: () => print(_counter.value),
      ),
    );
  }
}

Widget
class Child extends StatelessWidget {
  final ValueNotifier<int> _counter;

  const Child(this._counter);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => _counter.value += 1,
      child: const Icon(Icons.plus_one),
    );
  }
}


text:
Q: Library for Additional touch events While on an iOS device, we get events like touchstart, touchmove,... end, gesturestart, ...move and ..end out of the box..
I wanted to know which free library can be used to get/listen to additional events e.g. Swipe, scrolling related, etc
I know Sencha touch is the best..But before you say that, I wanted to tell that I am looking for a free library..
Also, can we get to know the code for the default implementation.. e.g. When we do the 1-finger slide, the page scrolls automatically.. But there must be some code to do that.. Can we know the code which does that ?

A: Some quick googling found these:

*

*http://www.queness.com/post/6706/9-mobile-framework-to-kick-start-your-mobile-development-career

*http://woorkup.com/2010/08/25/10-useful-frameworks-to-develop-html-based-webapps-for-touch-devices/
(and even faster skimming led me to believe that the second one is better)
However it should be noted thatall those 'touch' events are actually other events in disguise: http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html


text:
Q: What requirements am I missing on App Engine for those Google libraries? I have had all my websites on App Engine working great for years and I recently got an email saying everything I used was deprecated. I'm migrating webapp to flask, etc etc.
My new server works locally (finally there were just a few code changes) however the deployed version does NOT work.
Locally I have the cloud SDK installed and /usr/local/google_appengine/lib/:/usr/local/google_appengine in my PYTHONPATH.
I import
from google.appengine.api import urlfetch
from google.appengine.api import datastore
from google.appengine.api import memcache
from google.appengine.ext import db

What requirements.txt am I missing? I tried to add the following
google-api-python-client==1.7.10
google-cloud-storage==1.6.0
googleapis-common-protos==1.6.0
google-cloud-datastore==1.8.0

but I'm still getting errors in the deployed app: ModuleNotFound google.appengine. Also is there a generic way to go from google doc code example/import -> requirement? Thanks

A: This is not a complete answer but a good start:
I had to migrate db to ndb
https://cloud.google.com/appengine/docs/standard/python/ndb/db_to_ndb
this seems to necessitate to set up iam permissions
https://console.cloud.google.com/iam-admin/iam?project=yourproject
The migration is not so hard, mostly replacing db with ndb, changing repeated fields (a find and replace in the code, no datastore change).
You also need to change the syntax of a few queries, this is a bit more laborious.
Regarding the "deprecated apis":
from google.appengine.api import datastore became from google.cloud import datastore
And I had to use in requirements.txt:
google-api-python-client==1.7.10
google-cloud-ndb==0.0.1
google-cloud-storage==1.17.0
grpcio-gcp==1.17.1

There are a few things that I didn't bother migrating (especially since my website is not using them that much): google oauth and memcache.
I just removed my admin page (that was using oauth), and I replaced memcache with cachetools.LRUCache (I used memcache to rate limit the calls on a page). Not as glamorous as a distributed cache but I didn't want to set up redis etc
End of the story: it is working locally but still not working when I deploy. After removing everything to just have a minimal website, it is still not working (while another project works) so I opened
 https://issuetracker.google.com/issues/138887166


text:
Q: Only one event fired in RxJava even if multiple observables are subscribed I am trying to understand RxJava. I have written a small piece of code which will upload a list files to firebase server. I have written two observables:
1. ImageUploaderService.java: Upload single file and inform status
2. AllImageUploaderService.java: Create new single file uploader and feed it with one file path to be uploaded.Collect results of all uploaders and inform the caller with links of uploaded files.
My problem is even if each instance of ImageUploaderService is subscribed in AllImageUploaderService, only one event of OnNext is fired. How can I fix it?
AllImageUploaderService.java
    public class AllImageUploaderService extends Subscriber<String>{
    private BehaviorSubject<String[]> uploadService;
    private ArrayList<String> uploadedFiles;
    private int expectedCount;
    private int actualCount;

    public Observable<String[]> uploadImages(final String[] fileNames, final StorageReference imagesRef,
        final String[] chosenImage) {
        expectedCount = fileNames.length;
        uploadedFiles = new ArrayList<>(fileNames.length);

        uploadService = BehaviorSubject.create();

        Observable<String[]> observable = Observable.create(new Observable.OnSubscribe<String[]>(){
            @Override
            public void call(Subscriber<? super String[]> subscriber) {
                for (int i = 0; i < fileNames.length; i++) {
                    ImageUploaderService imageUploaderService=new ImageUploaderService();
                    Observable<String> observable= imageUploaderService.uploadImage(fileNames[i],imagesRef,chosenImage[i]);
                    observable.subscribe(AllImageUploaderService.this);
                }
            }
        });
        observable.subscribe(uploadService);
        return uploadService;
    }

    @Override
    public void onCompleted() {
        actualCount++;
        if(expectedCount==actualCount) {
            String[] retValue = new String[uploadedFiles.size()];
            uploadedFiles.toArray(retValue);
            uploadService.onNext(retValue);
            uploadService.onCompleted();
        }
    }

    @Override
    public void onError(Throwable e) {
        Utils.logE(this,"Error",e);
    }

    @Override
    public void onNext(String s) {
        uploadedFiles.add(s);
    }
}

ImageUploaderService.java
public class ImageUploaderService implements OnFailureListener, OnSuccessListener<UploadTask.TaskSnapshot> {

    private BehaviorSubject<String> uploadSubject;

    public Observable<String> uploadImage(final String fileNames, final StorageReference imagesRef,
        final String chosenImage) {

        uploadSubject = BehaviorSubject.create();
        Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                StorageReference spaceRef = imagesRef.child(fileNames);
                UploadTask uploadTask = spaceRef.putFile(UriUtil.generatorUri(chosenImage, UriUtil.LOCAL_FILE_SCHEME));
                uploadTask.addOnFailureListener(ImageUploaderService.this);
                uploadTask.addOnSuccessListener(ImageUploaderService.this);
            }
        });
        observable.subscribe(uploadSubject);
        return uploadSubject;
    }

    @Override
    public void onFailure(@NonNull Exception exception) {
        uploadSubject.onError(exception);
        uploadSubject.onCompleted();
    }

    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
        uploadSubject.onNext(downloadUrl.toString());
        uploadSubject.onCompleted();
    }
}

It would be great if you could let me know better approaches to the same.

A: No need to overcomplicate things:
public Observable<String> uploadImages(final String[] fileNames, final StorageReference imagesRef,
    final String[] chosenImage) {

    return Observable
        .range(0, fileNames.length)
        .flatMap(i -> new ImageUploaderService()
             .uploadImage(fileNames[i],imagesRef,chosenImage[i]))
}

You need it as a collection when everything finishes? .toList().
Also, I'd think that you don't need a subject in the ImageUploaderService:
public class ImageUploader implements OnFailureListener, OnSuccessListener<UploadTask.TaskSnapshot> {

  public static Observable<String> uploadImage(final String fileNames, final StorageReference imagesRef,
    final String chosenImage) {

    Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            ImageUploader uploader = new ImageUploader(subscriber);
            StorageReference spaceRef = imagesRef.child(fileNames);
            UploadTask uploadTask = spaceRef.putFile(UriUtil.generatorUri(chosenImage, UriUtil.LOCAL_FILE_SCHEME));
            uploadTask.addOnFailureListener(uploader);
            uploadTask.addOnSuccessListener(uploader);
        }
    });
    return observable;
  }

  /////////

  private final Subscriber<String> subscriber;

  private ImageUploader(final Subscriber<String> subscriber) {
    this.subscriber = subscriber;
  }

  @Override
  public void onFailure(@NonNull Exception exception) {
    if(subscriber.isUnsubscribed()) return;
    subscriber.onError(exception);
  }

  @Override
  public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    if(subscriber.isUnsubscribed()) return;
    Uri downloadUrl = taskSnapshot.getDownloadUrl();
    uploadSubject.onNext(downloadUrl.toString());
    uploadSubject.onCompleted();
  }
}

Note, don't emit onComplete() after onError(), either of those is a terminal state for Observables, and either should be last..


text:
Q: WireGuard: Limiting download & upload bandwidth I'm trying to limit download and upload speed of each wireguard peer to 512kbit.
The problem is that my following commands, only limits download bandwidth of peer and doesn't limit upload bandwidth. Any help would be appreciated.
tc rules for example peer with ip 10.7.0.2 and iptables mark 12:
tc qdisc add dev eth0 root handle 1: htb
tc qdisc add dev wg0 root handle 1: htb

tc class add dev eth0 parent 1:1 classid 1:12 htb rate 512kbit ceil 512kbit
tc qdisc add dev eth0 parent 1:12 sfq perturb 10
tc filter add dev eth0 protocol ip parent 1: prio 1 handle 12 fw flowid 1:12

tc class add dev wg0 parent 1:1 classid 1:12 htb rate 512kbit ceil 512kbit
tc qdisc add dev wg0 parent 1:12 sfq perturb 10
tc filter add dev wg0 protocol ip parent 1: prio 1 handle 12 fw flowid 1:12

And with iptables, I mark peer with number 12, so tc does limit it:
iptables -I FORWARD -s 10.7.0.2 -j MARK --set-mark 12
iptables -I FORWARD -d 10.7.0.2 -j MARK --set-mark 12

Thanks!

A: Fixed the problem using this code, from: https://stackoverflow.com/a/65248666/3411911
export IF_INET=eth0
export LIMIT=300kbit

tc qdisc add dev ${IF_INET} ingress

tc filter add dev ${IF_INET} protocol ip ingress prio 2 u32 match ip dst 0.0.0.0/0 action police rate ${LIMIT} burst ${LIMIT}
tc filter add dev ${IF_INET} protocol ip ingress prio 2 u32 match ip src 0.0.0.0/0 action police rate ${LIMIT} burst ${LIMIT}


text:
Q: Android emulator not working after Studio upgrade Just upgraded from Android Studio 4.1 to ArcticFox 2020.3.1.
Emulator was working fine in 4.1 but now nothing shows. Sometimes the status line says 'waiting for emulator to start...' for a few seconds, but otherwise nothing, no error messages.
As part of the upgrade, it recommended to use the HAXM accelerator which I installed.
I have checked this thread but it hasn't helped (it refers to a much older version of Studio).
The app runs OK on a  real device.
I have tried adding a new (different) virtual device; same problem. I also have the same problem on two upgraded PCs (Windows 10)

A: Found the answer in these two threads:
emulator process terminated
cannot find vulkan-1
But puzzled why these weren't offered as solutions when I added my question.


text:
Q: Assigning a value for a property inside the set method The code below causes StackOverflow error (As expected). However, I want to be able to set the value of this variable inside the set method. Is there a way to do this ?
public bool IsAvailable
{
    get
    {
        return IsAvailable;
    }

    set
    {
        if (value == true)
        {
            this.Shape.BrushColor = ColorAvailable;
            IsAvailable = true;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
            IsAvailable = false;
        }
    }
}

A: You need to use a backing field:
private bool _isAvailable;

public bool IsAvailable
{
    get
    {
        return _isAvailable;
    }

    set
    {
        if (value == true)
        {
            this.Shape.BrushColor = ColorAvailable;
            _isAvailable = true;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
            _isAvailable = false;
        }
    }
}

BTW: The code can be shortened considerably:
private bool _isAvailable;

public bool IsAvailable
{
    get
    {
        return _isAvailable;
    }

    set
    {
        this.Shape.BrushColor = value ? ColorAvailable : ColorNotAvailable;
        _isAvailable = value;
    }
}

A: Your property should encapsulate a private field and that should be set in the Setter, not the property.
private bool _IsAvailable; //private field
public bool IsAvailable
{
    get
    {
        return _IsAvailable;
    }

    set
    {
        if (value)
        {
            this.Shape.BrushColor = ColorAvailable;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
        }
        _IsAvailable = value;
    }
}

A: You can use a backing field:
private bool _IsAvailable;
public bool IsAvailable
{
    get
    {
        return _IsAvailable;
    }

    set
    {
        this.Shape.BrushColor = value ? ColorAvailable : ColorNotAvailable;
        _IsAvailable = value;
    }
}

Automatic vs Explicit Properties

A: you can create a private member private bool _isAvailable and store your flag there.
public bool IsAvailable
{
get
{
    return _isAvailable;
}

set
{
    if (value)
    {
        this.Shape.BrushColor = ColorAvailable;
    }
    else
    {
        this.Shape.BrushColor = ColorNotAvailable;
    }
    _isAvailable = value;
}

}

A: You should use a backing field. But if you do not want to use backing field and sure that this.Shape.BrushColor will not be not set anywhere else you can do something (ugly) like:
public bool IsAvailable
{
    get
    {
        return this.Shape.BrushColor == ColorAvailable;
    }
    set
    {
        this.Shape.BrushColor = value  ? ColorAvailable : ColorNotAvailable;
    }
}

A: Essentially IsAvailable is the property not, as @Cemre correctly says, an underlying, (backing), field such as;
private bool _isAvailable;

I would also look at reducing the verbosity where, for instance, '(value == true)' is the same as 'if (value)', and setting value of the underlying field outside of the if...else and only on one line. In this way the above could be reduced to;
set
{
    this.Shape.BrushColor = value?ColorAvailable:ColorNotAvailable;
    _isAvailable = false;
}