text:
Q: Trying Decorator Design Pattern, what's wrong with this code? I have this code that explains the decorator pattern:
 public abstract class IBeverage {
    protected string description = "Unknown beverage";

    public virtual string getDescription() {
        return description;
    }
}

public abstract class CondimentDecorator : IBeverage {
    public abstract string getDescription();
}

public class Espresso : IBeverage {
    public Espresso() {
        description = "Espresso";
    }
}

public class Mocha : CondimentDecorator {
    IBeverage beverage;

    public Mocha(IBeverage beverage) {
        this.beverage = beverage;
    }

    public override string getDescription() {
        return beverage.getDescription() + ", Mocha";
    }
}

I should use it like:
static void Main(string[] args) {
    IBeverage b = new Espresso();
    Console.WriteLine(b.getDescription());
    b = new Mocha(b);
    Console.WriteLine(b.getDescription());

    Console.ReadKey();
}

When I create the beverage (Beverage b = new Espresso();) _description is updated to "Espresso", when I decorate b with Mocha (b = new Mocha(b)), then _description takes the original value "Unknown Beverage". It should be "Espresso, Mocha". What's wrong?
This code was originally written in Java (the book was written with Java), but I translated it into C#. I guess Java works a little different from C#.

A: Because GetDescription() is not virtual.
public virtual string GetDescription() { ... }

virtual is the companion keyword to override, it's what allows subclasses to override methods. This is a key difference in C# from Java. In Java all methods are implicitly virtual.

A: You've actually got a few issues here (perhaps differing designs from Java). Even after sorting all of the naming issues, you will not get what you expect.
public abstract class CondimentDecorator : IBeverage {
    public abstract string GetDescription();
}

*

*The CondimentDecorator class will actually hide the IBeverage version GetDescription() method (you technically should use public new abstract string GetDescription();.

*You are classifying the Mocha class as an IBeverage by assigning it to the b variable (which you earlier defined as an IBeverage via  IBeverage b = new Espresso(), the IBeverage version of the GetDescription() method is what actually fires (totally ignoring the Mocha override of the CondimentDecorator GetDescription() method)
You can see this if you step through the code. Try using
CondimentDecorator m = new Mocha(b);
Console.WriteLine(m.GetDescription());

and you will get what you expect.
However, this kind of defeats the purpose of using a decorator in my opinion. A better option would be to change the design a bit and get rid of the CondimentDecorator. It is not providing anything other than confusion and unexpected behaviour. Instead try this:
This is your only needed abstract Beverage class:
public abstract class Beverage
{
    // c# convention is to use properties instead of public fields.
    // In this case I've used a private readonly backing field.
    private readonly string _description = "Unknown Beverage";

    protected string Description
    {
        get { return _description; }
        set { _description = value; }
    }

    // Make this method virtual so you can override it, but if you
    // choose not to, this is the default behaviour.
    public virtual string GetDescription()
    {
        return Description;
    }
}

This is a standard beverage class (can be decorated):
public class Espresso : Beverage
{
    public Espresso()
    {
        // Setting the Beverage class Description property.
        // You can use base.Description if you prefer to be explicit
        Description = "Espresso";
    }
}

This is a Beverage class that decorates another Beverage class:
public class Mocha : Beverage
{
    // store an instance of the Beverage class to be decorated
    private readonly Beverage _beverage;

    // Beverage instance to be decorated is passed in via constructor
    public Mocha(Beverage beverage)
    {
        _beverage = beverage;
    }

    // Override Beverage.GetDescription
    public override string GetDescription()
    {
        // Calls decorated Beverage's GetDescription and appends to it.
        return _beverage.GetDescription() + ", Mocha";
    }
}

And now to get the behaviour you expect, you can run the same code as above:
static void Main(string[] args)
{
    Beverage b = new Espresso();
    Console.WriteLine(b.getDescription()); // "Espresso"
    b = new Mocha(b);
    Console.WriteLine(b.getDescription()); // "Espresso, Mocha"

    Console.ReadKey();
}

As a side note. You can avoid using Console.ReadKey(); when debugging by using Ctrl + F5 This will automatically put in "Press any key to continue..." for you.
UPDATE
Since you want to include the CondimentDecorator class (as mentioned in your comment), you can create the following class:
public abstract class CondimentDecorator : Beverage
{
    private readonly Beverage _beverage;

    protected Beverage Bevy
    {
        get { return _beverage; }
    }

    protected CondimentDecorator(Beverage beverage)
    {
        _beverage = beverage;
    }
}

Then you would change your Mocha class to the following:
// override CondimentDecorator instead of Beverage
public class Mocha : CondimentDecorator
{
    // Pass the Beverage to be decorated to the base constructor
    // (CondimentDecorator)
    public Mocha(Beverage beverage)
        : base(beverage)
    {
        // nothing needed in this constructor
    }

    public override string GetDescription()
    {
        // Now access the CondimentDecorator's Beverage property
        // (which I called Bevy to differentiate it)
        return Bevy.GetDescription() + ", Mocha";
    }
}


text:
Q: Positioning JLabel in Corner I'm pretty nooby at layouts... for my application I want to put a panel in the bottom-left corner, with padding, but I'm not sure which layout to use.
I tried using a BorderLayout coupled with horizontal alignment in order to position the panel in the corner, but it did not produce the expected result. My code is as follows:
final JLabel label = new JLabel();
label.setBorder(new EmptyBorder(20, 20, 20, 20));
label.setHorizontalAlignment(JLabel.LEFT);
label.setPreferredSize(new Dimension(100,100));
label.setBackground(Color.WHITE);
label.setOpaque(true);
add(label, BorderLayout.SOUTH);

(the outer class extends JFrame)
The image below details what I want, and what I have.

Any tips to achieve this layout? It seems rather simple, but again, I'm new to layouts

A: There are 2 ways I recommend:

*

*You can use GridBagLayout to achieve what you want. Check out the tutorial here.
It is flexible enough to give you what you need and for any further add-on components.

*Use nested panels with different layouts. For example, a topPanel and a bottomPanel. By default (FlowLayout will be used for your bottomPanel) which will position the JLabel at bottom left hand corner.

A: You can use a SpringLayout.
It's tricky, but it'll do the trick.
SpringLayout springLayout = new SpringLayout();
Container cont = getContentPane();
cont.setLayout(springLayout);

JLabel label = new JLabel("New label");
springLayout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, cont);
springLayout.putConstraint(SpringLayout.SOUTH, label, -10, SpringLayout.SOUTH, cont);
cont.add(lblNewLabel);

Spring Layout allows you to set the distance between the sides of components and the frame, and eventually set it's location in a dynamic way (the location will remain relative to the frame when you resize)
this is the output:

A: You can Use null Layout, to customise your JFrame. with
 yourFrame.setLayout(null)

you can
 setLocation(x,y);
 setsize(width,height);

redpajama_set_name: RedPajamaStackExchange


text:
Q: text wrapping in two column table I am trying to make a table in which a text can automatically adjust itself as some of my text hide out of border page. Below is code of my draft. Kindly solve the issue for me. Thank you.
\documentclass[conference]{IEEEtran}
\usepackage{graphicx}
\usepackage{bm}
\usepackage{url}  %%%%%%%%%%%%%%%%
\usepackage{epsf}
\usepackage{amsfonts,amssymb,amsmath,amsthm}
\usepackage{algorithmic,algorithm}
\usepackage[sort,compress]{cite}
\usepackage{subfigure}
%\usepackage{fixltx2e}
\usepackage{multirow}
\usepackage{tabulary}
\usepackage{color}
\usepackage{epstopdf}
\usepackage{pifont}
\usepackage{float}
\usepackage{booktabs,chemformula}
\usepackage{makecell}
\usepackage{longtable}
\usepackage{xtab}
\usepackage{lipsum}
\usepackage[utf8]{inputenc}
%\newenvironment{figurehere}

%{\def\@captype{figure}}
\addtolength{\textwidth}{-0.05in}

\begin{document}

\begin{table*}

  \centering

  \begin{tabular}{@{}ccccc@{}}

    \toprule

    Year  & Journal    & Paper & Description& Attack Type \\
    \midrule

    {1995} & Journal of Moderen optics & et al. Phoenix \cite{phoenix1995multi} & \makecell {proposed technique to allow multi-user secure key distribution \\ on optical networks} & Eavesdropping \\

  {1997} & IEEE network & et al. Medard \cite{medard1997security} & \makecell {Provide overview of physical layer security about tapping \\ and eavesdropping attacks in optical passive network} & Survey Paper \\
 \ch{2019}
    & \makecell {Optics express} & et al. Li \cite{li2019optical} & \makecell {In order to detect attacks, this paper studies the optical spectral signature analysis (OSFA) and recognition. By analyzing the spectral characteristics of optical signals, the identification and detection of unauthorized signals can be realized} & \makecell {Attack Management} \\

ch{2019}
    & \makecell {Journal of Lightwave Technology} & et al. Natalino \cite{natalino2019experimental} & \makecell {This paper proposes a machine learning (ML) framework for detecting and identifying physical layer attacks. The framework is based on experimental attack trajectories from the operator site of testers deployed with coherent receivers, and performs in-band and out-of-band interference Signal insertion attacks, and polarization scrambling attacks of different intensities} & \makecell {Attack Management} \\

ch{2019}
    & \makecell {-} & et al. Bensalem \cite{bensalem2019machine} & \makecell {This paper proposes a machine learning (ML) framework for detecting and preventing jamming attacks in optical networks, and proposes a novel resource redistribution scheme that uses statistical information on the accuracy of attack detection to reduce successful congestion The probability of the light path while minimizing the redistribution of the light path} & \makecell {Attack Management} \\

ch{2020}
    & \makecell {Journal of Lightwave Technology} & et al. Furdek \cite{furdek2020machine} & \makecell {The framework includes modules for detecting and identifying attacks. These modules can use supervised, semi-supervised, and unsupervised learning to detect attacks, and when applicable, identify the type and strength of the attack; and the connection and/or link local for the attack Modified modules have been integrated into NMS} & \makecell {Attack Detecting and Identifying} \\

    \bottomrule

  \end{tabular}

  \caption{Sample table}

\end{table*}

\end{document}


text:
Q: Link column with link to a file in static (django-tables2, Django) I generate a table with django-tables within Django.
I want to create a column with links to txt files in my static directory.
When the user clicks on the link, the txt file should be displayed.
To create a link to the txt file within an html, I simply do:
txtfile

However, I have problems finding the right way to do this using django-tables.
I tried to define the link column as follows:
logfiles = tables.LinkColumn('{static', text='txtfile', args=[A('log')], orderable=False, empty_values=())

This gives the error
"Reverse for '{static' not found. '{static' is not a valid view function or pattern name."
I also tried this:
tables.py
logfiles = tables.LinkColumn('logfile', text='bla', orderable=False, empty_values=())

urls.py:
url(r'^logfile/', views.logfile, name='logfile')

views.py:
def logfile(request):
return HttpResponse('
yeah
')

So I can find a way to open a new url, but how to open a specific static file, i.e.how to pass the info from [A('log')], which is basically the filename?
Any help is appreciated.

A: You could use a TemplateColumn to achieve this:
class LogTable(tables.Table):
    log = tables.TemplateColumn(
        template_code='{% load static %}txtfile'
    )

Note that the column name is log, so there is no need to specify the accessor. If you want the color to appear with a different name, use the verbose_name kwarg.


text:
Q: Only allow one image at the same time with File API? Only allow one image at the same time with File API?
What's the correct method to set the restriction for only one image at the same time?

<input id="browse" type="file" multiple>

A: One solution could be a promise chain like this:
function readImage(file) {
  //wrap readImage body into a promise
  return new Promise((resolve) => {
    var reader = new FileReader();
    reader.addEventListener("load", function () {

      var image = new Image();
      image.addEventListener("load", function () {
        elPic.appendChild(this);
        //resolve the promise after the child is appended so the caller would know when to start the next one
        resolve();
      });

      image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
    });

    reader.readAsDataURL(file);
  });
}

elBrowse.addEventListener("change", function () {

  var files = this.files; {
    //start the chain
    var chain = Promise.resolve();
    for (var i = 0; i < files.length; i++) {
      //use let to have properly scoped variable
      let file = files[i];
      if ((/\.(png|jpeg|jpg|gif)$/i).test(file.name)) {
        //append functions to call to the chain
        chain = chain.then(() => readImage(file));
      }
    }
  }
});

The call to the next readImage() is performed after resolve() is called in the previous one - after the image is loaded and appended.
You might want to consider using loadend event also, it is emitted even when the loading fails for some reason so it won't break your chain.
https://developer.mozilla.org/en-US/docs/Web/Events/loadend

A: I started a new approach that leads to the desired result.

<input type="file" onchange="previewFile()">


text:
Q: EF6 Map and MapToStoredProcedures equivalent in EF Core I'm in the process of rewriting of our webapis to .NET Core and using EntityFrameworkCore 5.0.  In our previous iteration we used EntityFramework 6. We are moving this app so we can host it on azure.
I'm new to EFCore and was noticing some differences that I can't seem to get around.
We have an entity that will use mapping from two tables, one is a view and the other is the actual table that the object will live in. The last part contains the stored procedures to insert, update, and delete entries in the dbo.PhoneFaxEmail table.
The Previous EF6 code is below.
Map(m =>
            {
                m.ToTable("HomeownerContactDetails_vw", "monarch");
                m.Properties(h => new { h.HomeownerId, h.Id, h.StartDate, h.EndDate });

                m.Requires("RelationTypeLUKey").HasValue(587); // Contact-PhoneFaxEmail (p-c)

                m.Property(h => h.HomeownerId).HasColumnName("ParentRelationKey");
                m.Property(h => h.Id).HasColumnName("ChildRelationKey");
            });

            #endregion

            #region PhoneFaxEmail Mapping

            Map(m =>
            {
                m.ToTable("dbo.PhoneFaxEMail");
                m.Properties(h => new { h.Type, h.Value, h.ValidDate, h.Status, h.Version });

                m.Property(h => h.Id)
                    .HasColumnName("RelationKey");

                m.Property(h => h.Type).HasColumnName("PhoneFaxEMailTypeLUKey");
                m.Property(h => h.Value).HasColumnName("Value");
                m.Property(h => h.ValidDate).HasColumnName("StatusDate");
                m.Property(h => h.Status).HasColumnName("StatusLUKey");
                m.Property(a => a.CreatedBy).HasColumnName("CreatedBy");
                m.Property(a => a.CreatedDate).HasColumnName("CreatedDate");
                m.Property(a => a.ModifiedBy).HasColumnName("ModifiedBy");
                m.Property(a => a.ModifiedDate).HasColumnName("ModifiedDate");
            });

            #endregion

            MapToStoredProcedures(s =>
            {
                s.Insert(i => i.HasName("HomeownerContactDetailCreate_sp", "monarch"));
                s.Update(u =>
                {
                    u.HasName("HomeownerContactDetailUpdate_sp", "monarch");
                    u.Parameter(p => p.Id, "RelationKey");
                    u.Parameter(p => p.Version, "Version");
                });

                s.Delete(i =>
                {
                    i.HasName("HomeownerContactDetailDelete_sp", "monarch");
                    i.Parameter(p => p.Id, "RelationKey");
                    i.Parameter(p => p.Version, "Version");
                });
            });

The issue I am having in .NET Core is that there is no Map() function and no MapToStoredProcedures() function. I'm not sure where to go from here to get the Entity mapped to the two separate tables, and how EF Core maps procs (or of it even does map procs in the same manner).
I tried to do Entity Splitting with this code, but the 'm' lamba expression results to a TableBuilder object, which only has 2 methods, m.ExcludeFromMitigations() and m.GetType().
pfeEntity.ToTable("dbo.PhoneFaxEmail");
            pfeEntity.Property(b => b.Id).HasColumnName("RelationKey");
            pfeEntity.Property(b => b.Value).HasColumnName("Value");

            pfeEntity.ToTable("HomeownerContactDetails_vw", "monarch", m =>
            {

                m.Property(b => b.BlogId).HasColumnName("Id");
                m.Property(b => b.Url);
            });

Any help would be greatly appreciated! (even if I'm totally approaching this the wrong way, like I said, totally new and want to learn all I can about EFCore!)

A: You can declare a DbSet with the properties of the stored procedure and call
context.DbSetName.FromSqlRaw("Execute yourStoredProcedure")
and it will be mapped to that declared DbSet model.
See examples in this question:
Generating and accessing stored procedures using Entity framework core


text:
Q: Opencart showing some links as https without ssl enabled I have installed the latest version (3.0.2.0) of Opencart. It is showing some links as https even when there is no SSL certificate installed and ssl url are disabled from admin dashboard.
When I looked in "C:\xampp\htdocs\opencart\catalog\controller\common\footer.php" I found that some urls have ssl enabled like below
    $data['voucher'] = $this->url->link('account/voucher', '', true);
    $data['affiliate'] = $this->url->link('affiliate/login', '', true);
    $data['special'] = $this->url->link('product/special');
    $data['account'] = $this->url->link('account/account', '', true);
    $data['order'] = $this->url->link('account/order', '', true);
    $data['wishlist'] = $this->url->link('account/wishlist', '', true);
    $data['newsletter'] = $this->url->link('account/newsletter', '', true);

What to do to run these url's without editing the code

A: Change HTTPS_SERVER in your config.php and admin/config.php file. (change https:// to http://)


text:
Q: C to MIPS - functions and arrays I am trying to translate the following C code to MIPS assembly.
The base address of array is stored in $a0. The variable index is stored in $a1. The variable x is stored in $t0.
void ld_array(char array[], int index) {
  x = array[index];
}

When index was a defined integer (eg: 5) I had done
lbu $t0, 5($a0)

However, lbu $t0, $a1($a0) is not correct syntax.

A: You can use pointer arithmetic to compute the address of the data you are trying to access.
array[index] is equivalent to *(array+index). You can do the same thing in mips using the addu instruction.
Assuming $a0 is the array pointer and $a1 is the index you can use:
addu $t0, $a0, $a1 # tmp = array+index
lbu  $t0, ($t0)    # x = *tmp

We are using addu because it is an unsigned operation since pointers are unsigned words. This means it will not trigger an overflow exception.
Assuming that your array would be an array of words you would use the same approach but first multiply the index by 4 (since words in 32bit are 4 bytes long).
sll  $t0, $a1, 2   # index << 2 = index * 4
addu $t0, $a0, $t0 # tmp = array+index
lw   $t0, ($t0)    # x = array[index]


text:
Q: What's going on inside the game when a BUD switch activates? I understand completely what a BUD switch is and what purpose it serves. But what within the game is happening when a BUD switch works? What allows it to work and what is the game thinking?

A: Here is a more detailed explanation (it is still a bit simplified though):
Block updates theory and examples
The Minecraft world changes constantly and the game needs to constantly calculate the new state of the world. This happens 20 times per second and is called a tick. In most game ticks there are quite a few entity changes - mobs movement and behavior, projectiles and dropped items movement, etc.
In the game code, each block has certain behavior associated with it - doors open or close, pistons move, water flows, etc. The game needs to execute this behavior to calculate the new state of blocks. In typical settings there are tens of millions of blocks around the player, but block changes are relatively rare. In a single tick there are hardly any block changes. That is why it doesn't make sense to execute (calculate) the behavior for all the blocks all the time, but instead it is much more reasonable to do it only for changed blocks. This means that the game needs to track which blocks are changing.
Fortunately keeping track of changes is easy - changes are typically transfered from one block to its neighbors. So if one block changes - for example when player places block or flips a lever, all six adjacent blocks are scheduled for update. When their change is calculated, they in turn schedule all their adjacent blocks for update etc. The process stops if a 'passive' block is reached, like air or most solid blocks.

For example, consider what happens if the player breaks the bottom of grown reed: the block is removed (replaced by air) and a reed item is created in its place. It then notifies all adjacent six blocks to update themselves. The middle reed 'realizes' it is not supported and deletes itself and creates a second reed item. The adjacent water 'realizes' it can flow in the free space where the bottom reed was and places flowing water there. Finally the top reed updates, scheduled by the second reed - it 'realizes' it is not supported and deletes itself and creates a third reed item. The rest of the adjacent blocks are air or ground, and they don't change, so they don't notify any more adjacent blocks to update themselves.

When a redstone lamp is scheduled for update, it checks any of the surrounding blocks are powered and lights up (or turns off if not). When the player places a redstone block next to it, the redstone block schedules updates for all adjacent blocks including the lamp. The lamp then 'realizes' it is powered and lights up.

This is also how redstone signal 'travels' - each redstone dust piece notifies adjacent blocks and adjacent dust pieces update their power level and notify the adjacent blocks etc.
How BUD works
When a piston is scheduled for update, it checks if any of the adjacent blocks are powered. However for some reason, it also checks if any of the adjacent blocks of the block above it are powered. In a picture, it checks if any of the glass blocks are powered:

This is why it is possible to build this simple non-resettable BUD:

When you place the redstone block, it notifies the grass below and the air around it to update, and they do nothing. The redstone block does not notify the piston to update, because it is not adjacent to the redstone block, so the piston stays retracted. If after that the piston receives any notification for update in some other way (for example placed block next to piston or crop growing next to piston), the piston will 'realize' it is powered (because it will check the place diagonally above where the redstone block is) and it will extend.
Droppers and dispensers have the same weird pattern of checking if they are powered, so they can be used as BUDs as well.
More block updates theory
Usually block updates are triggered by some player or mob action, but there is also another source of updates - the game schedules a special kind of update (different from normal update) for randomly chosen blocks each tick. Some blocks react to these random updates - for example crops can decide to grow on this random update. If they decide to grow, they then schedule regular updates to their adjacent blocks. Another example is water can choose to turn into ice if it is in a cold biome or high above the ground.

A: Most BUD switches work on the fact that you can power a piston with quasi-connectivity. This lets it be powered without the piston noticing. When you change a  block next to the piston, it checks to see if it is powered, and notices that it is. It then sends a signal and resets itself.


text:
Q: Getting blank records on Excel sheet when binding it using stored procedure This is my stored procedure
 CREATE OR ALTER PROCEDURE [dbo].[sp_TADashboardVoid]
        @PartnerId INT,
        @UserId BIGINT,
        @TAType INT = 0,
        @Borough INT = 0,
        @LandlordId INT = 0,
        @AllocationStartDate DATE = NULL,
        @AllocationEndDate DATE = NULL,
        @PropertyRef VARCHAR(100) = NULL,
        @PropertyType INT = 0,
        @PropertyId VARCHAR(100) = NULL,
        @PropertyAddress VARCHAR(200) = NULL,
        -- @LandlordProperty VARCHAR(100) = NULL
        @PropertyStatusId INT = NULL,
        @HouseholdId VARCHAR(10) = NULL,
        @ReferenceID VARCHAR(50) = NULL,
        @VoidStartDate DATE = NULL,
        @VoidEndDate DATE = NULL
    AS
    BEGIN

DECLARE @demotest TABLE (

      PropertyID NVARCHAR(MAX)
      ,App_id INT

      ,Rent DECIMAL(18, 2)
      ,RoomId INT
       ,CreatedDate Date
      ,StartDate Date
      ,EndDate Date
       ,VoidStartDate  DATE
      ,VoidEndDate  DATE
      --,VoidLoss NVARCHAR(MAX)
)

insert  into @demotest

select PropertyId,App_Id,Rent,RoomId,CreatedDate,StartDate,EndDate,EndDate+1 as VoidStartDate,
LEAD(StartDate) OVER (Partition BY PropertyId ORDER by Propertyid) As VoidEndDate

from tbl_AssignAppToProperty

SELECT  ROW_NUMBER() OVER (
            --ORDER BY  A.Reference_id DESC
            ORDER BY dt.PropertyId
            ) AS RowNumber

          , app.Reference_ID as ApplicationRef
          , A.Reference_ID as PropertyRefId
          , A.ID as PropertyID
      ,vtp.TypeofProperty
      ,vPN.PropertyName AS PropertyName
      ,c.title AS Landlord
      ,P.FirstName
      ,P.LastName
      ,Ho.HouseholdLoginId AS HouseholdId
      ,vrt.RentType as RentFrequency
      ,dt.Rent
      ,A.Apptype
      ,A.FormId  --added due to error
      , A.session_guid

       ,CASE
            WHEN
            app.Reference_ID  IS NULL Then  A.DateOfSubmission

            ELSE dt.VoidStartDate
            END AS VoidStartDate

      ,Case
          WHEN
          dt.VoidEndDate is NULL Then getdate()
          Else dt.VoidEndDate
          END AS VoidEndDate

      ,datediff(ww,dt.VoidStartDate,dt.VoidEndDate) * dt.Rent AS VoidLoss

      from tbl_Application A
     INNER JOIN tbl_Form F ON F.id = A.FormId

      left join @demotest dt on dt.PropertyId = A.ID

     left join tbl_Application APP on dt.App_Id = APP.ID

     Left JOIN tbl_household HO ON HO.Household_ID = APP.Household_Id

     left JOIN v_TypeOfProperty vTP ON vTP.App_Id = A.ID
     INNER JOIN v_PropertyName vPN ON A.ID = vPN.App_Id         --record dropped from 78 to 57 to display only properties with name
     --INNER JOIN tbl_ApplicationSubPortal ASS ON A.ID = ASS.AppID
     INNER JOIN v_PropertyAddress vPA ON A.Session_Guid = vPA.MapGuid

    LEFT JOIN tbl_applicationlandlord AL ON AL.AppId = A.id
    LEFT JOIN tbl_choice c ON C.id = AL.LandlordId

     --LEFT JOIN v_PropertyType vPT ON vPT.App_Id = A.ID

     LEFT JOIN v_Person P ON P.AppId = dt.App_Id
        AND P.HouseholdType = 'M'
     LEFT JOIN v_RentType VRT on VRT.APP_ID = A.ID

     where A.AppType='pro' --and A.Formid=803

     AND F.PartnerId = @PartnerId
        AND (
            (@TAType = 0)
            OR (vTP.TypeOfPropertyId = @TAType)
            )

        AND (
            @PropertyRef IS NULL
            OR A.Reference_ID LIKE '%' + @PropertyRef + '%'
            )

        AND (
            @PropertyStatusId IS NULL
            OR (A.App_status = @PropertyStatusId)
            )
        AND (
            @PropertyId IS NULL
            OR A.Reference_ID LIKE '%' + @PropertyId + '%'
            )
        AND (
            @PropertyAddress IS NULL
            OR ((isnull(vPA.FlatNo, '') + ' ' + isnull(vPA.BuildingName, '') + ' ' + isnull(vPA.StreetName, '') + ' ' + isnull(vPA.TownCity, '') + ' ' + isnull(vPA.County, '') + ' ' + isnull(vPA.PostCode, '')) LIKE '%' + @PropertyAddress + '%')
            )

        AND (
              @HouseholdId IS NULL
              OR HO.HouseholdLoginId LIKE '%' + @HouseholdId + '%'
              )

        AND (
             @ReferenceID IS NULL
             OR APP.Reference_ID LIKE '%' + @ReferenceID + '%'
            )

        AND (
            (
                CONVERT(DATE, @VoidStartDate, 103) IS NULL
                OR CONVERT(DATE, @VoidEndDate, 103) IS NULL
                )
            OR (
                (
                    CONVERT(DATE, dt.VoidStartDate, 103) BETWEEN CONVERT(DATE,@VoidStartDate, 103)
                        AND CONVERT(DATE,  @VoidEndDate, 103)
                    )
                AND (
                    CONVERT(DATE, dt.VoidEndDate, 103) BETWEEN CONVERT(DATE, @VoidStartDate, 103)
                        AND CONVERT(DATE,  @VoidEndDate, 103)
                    )
                )
            )

END

This is my BindVoidData method
public System.Data.DataSet BindVoidData(int partnerId, long userId, string taType, string Borough, string landlord, string propertyRef, string propertyType, string propertyAddress , string propertyStatus)
{
    SqlCommand sqlCommand = new SqlCommand();

    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
    DataSet dataTable = new DataSet();

    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HousingRegister"].ConnectionString);

    try
    {
        sqlCommand = new SqlCommand("sp_TADashboardVoid", connection);

        sqlCommand.Parameters.Add(new SqlParameter("@PartnerId", partnerId));
        sqlCommand.Parameters.Add(new SqlParameter("@UserId", userId));
        sqlCommand.Parameters.Add(new SqlParameter("@TAType", taType));
        sqlCommand.Parameters.Add(new SqlParameter("@Borough", Borough));
        sqlCommand.Parameters.Add(new SqlParameter("@LandlordId", landlord));
        sqlCommand.Parameters.Add(new SqlParameter("@PropertyId", propertyRef));
        sqlCommand.Parameters.Add(new SqlParameter("@PropertyType", propertyType));
        sqlCommand.Parameters.Add(new SqlParameter("@PropertyAddress", propertyAddress));
        sqlCommand.Parameters.Add(new SqlParameter("@PropertyStatusId", propertyStatus));
        sqlCommand.CommandType = CommandType.StoredProcedure;

        sqlDataAdapter.SelectCommand = sqlCommand;

        sqlDataAdapter.Fill(dataTable);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        sqlCommand.Dispose();
        connection.Close();
    }

    return dataTable;
}

The problem that I am facing is that the datatable is not returning me any rows due to which there are no records on Excel sheet, but when I tested the stored procedure using exec on SQL Server, it is returning around 200 rows.
Can anyone please help me out on this as I am not sure how to proceed.

A:
Here is the code try this out, I Just edited it into my style of code

    public DataSet BindVoidData(int partnerId, long userId, string taType, string Borough, string landlord, string propertyRef, string propertyType, string propertyAddress, string propertyStatus)
    {
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet Ds = new DataSet();
        try
        {
            var constring = System.Configuration.ConfigurationManager.ConnectionStrings["HousingRegister"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constring))
            {

                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using (SqlCommand cmd = new SqlCommand("sp_TADashboardVoid", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    //Add the DataType Based on Your StoredProcedure
                    cmd.Parameters.Add("@PartnerId", SqlDbType.Int, 20);

                    //After Adding All Data Type Define Value
                    cmd.Parameters["@PartnerId"].Value = partnerId;
                    da = new SqlDataAdapter(cmd);
                    da.Fill(Ds);

                    cmd.Dispose();
                }
                con.Close();
            }

            //Return Data Set
            return Ds;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Here is the SQL Server Data Types and Their .NET Framework Equivalents for Add DataType in SqlCommand
Link


text:
Q: 3 file string matching pattern awk in tab separated file I've got 3 file:
FILE 1
NODE_2020   Cancer
NODE_2029   Thug
NODE_0902   Snap

FILE 2
NODE_2020   Mikro
NODE_2029   Bold
NODE_0902   Mini

FILE 3
NODE_2020   Gold
NODE_2080   Damn
NODE_0900   Gueo

I need to search for the first column of file 1 into the other two: if value matches, then column 2 of file 2 and column 2 of file 3 will be printed into a single file; if not, a "NO MATCH" string will be printed in return. Output file will be made like this:
Query   File1   File2   File3

NODE_2020   Cancer  Mikro   Gold
NODE_2029   Thug    Bold    NO MATCH
NODE_0902   Snap    Mini    NO MATCH

Awk/sed/perl solutions are really appreciated. What I'm stuck on doing is to use first column of file 1 as a variable to look with just an if statement into other 2 files.
Here's what I've tried, to use column from file 1 and match into file 2:
awk 'NR==FNR{a[NR]=$1;next} { print a[FNR],"\t", $2 }' file1 file2

It actually works for 2 files. No idea on how to extend to three file, and to add the "NO MATCH" pattern.

A: With GNU awk for true multi-dimensional arrays and ARGIND:
$ cat tst.awk
BEGIN { OFS="\t" }
(NR==FNR) || ($1 in vals) {
    vals[$1][ARGIND] = $2
}
END {
    printf "%s%s", "Query", OFS
    for (fileNr=1; fileNr<=ARGIND; fileNr++) {
        printf "%s%s", ARGV[fileNr], (fileNr<ARGIND ? OFS : ORS)
    }
    for (key in vals) {
        printf "%s%s", key, OFS
        for (fileNr=1; fileNr<=ARGIND; fileNr++) {
            val = (fileNr in vals[key] ? vals[key][fileNr] : "NO MATCH")
            printf "%s%s", val, (fileNr<ARGIND ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk file1 file2 file3
Query   file1   file2   file3
NODE_2020       Cancer  Mikro   Gold
NODE_0902       Snap    Mini    NO MATCH
NODE_2029       Thug    Bold    NO MATCH

A: You may use this awk:
awk -v OFS='\t' 'function bval(p,q) {
    return ((p,q) in b ? b[p,q] : "NO MATCH")
}
FNR == NR {
   a[$1] = $2
   next
}
{
   b[FILENAME,$1] = $2
}
END {
   print "Query", ARGV[1], ARGV[2], ARGV[3]
   for (i in a)
      print i, a[i], bval(ARGV[2],i), bval(ARGV[3],i)
}' file{1,2,3}

Query   file1   file2   file3
NODE_2020   Cancer  Mikro   Gold
NODE_0902   Snap    Mini    NO MATCH
NODE_2029   Thug    Bold    NO MATCH


text:
Q: Orbeon forms - repeated section field validation I have form like this: https://demo.orbeon.com/demo/fr/orbeon/builder/edit/f34f17613d9dbce14bcdf1219b1a7a6babaeebe2
I want to add validation like this:

*

*only one field 'yes/no' in this section can have selected value 'yes' at the same time

*validation message should appear only under the fields with selected value 'yes'

Should I create some action, that iterate over all 'yes/no' fields, check their value and raise an error if detect above situation?
My main problem is how to iterate over all 'yes/no' fields and detect this situation.

A: Assuming you name your field yes-no, then the following expression will do it:
string() = 'false' or
count(//yes-no[string() = 'true']) <= 1

With this expression you're saying that an answer is valid if either:

*

*it is "No", as we don't have any limit on those, or

*there only one "Yes", or less.

And for more on that string() = 'true' business, see Testing on a Yes No Answer field.


text:
Q: XSLT from 2 XMLs i'm new to xslt advanced program. i actually have a doubt in making an xslt from 2 different xml files.
Below are the 2 xml files i have.
AHK-authors.xml
    <?xml version="1.0" encoding="UTF-8"?>
<chapters>
    <chapter no="1">
        By J. R. Weeramantry
    </chapter>
    <chapter no="2">
        By Ernest Yang<footnote id="AHK-02.1.fn0" prefix="*">
                <footnote-para>I would like to acknowledge and express my gratitude for the assistance provided by my colleagues, Mr. Kevin Hong and Ms. Sharon Leung, in the preparation of this Chapter. All errors and omissions are my own. </footnote-para>
            </footnote>

    </chapter>
    <chapter no="3">
        By David Bateson and Edmund Wan
    </chapter>
    <chapter no="4">
        By Timothy Hill and Mark Lin
    </chapter>
    <chapter no="5">
        By Christopher To<footnote id="AHK-05.1.fn0" prefix="*">
                <footnote-para>I would like to acknowledge Alan Tang Siu Lun for his assistance in compiling parts of the Chapter.</footnote-para>
            </footnote>

    </chapter>
    <chapter no="6">
        By Chiann Bao
    </chapter>
    <chapter no="7">
        By Justin D'Agostino and Ula Cartwright-Finch
    </chapter>
    <chapter no="8">
        By Kim M. Rooney
    </chapter>
    <chapter no="9">
        By Neil Kaplan QC, JP, CBE, SBS and Andrew Aglionby
        [Revised and Updated by William Stone QC, SBS]<footnote id="AHK-09.1.fn0" prefix="*">
                <footnote-para>With thanks to summer students Chadwick Wong and Cheryl Leung.</footnote-para>
            </footnote>

    </chapter>
    <chapter no="10">
        By Frances van Eupen
    </chapter>
    <chapter no="11">
        By Peter Yuen and John Choong
    </chapter>
    <chapter no="12">
        By David Bateson and Edmund Wan
    </chapter>
    <chapter no="13">
        By Teresa Cheng SC<footnote id="AHK-13.1.fn0" prefix="*">
                <footnote-para>Special thanks to Andrew Aglionby, Joy Medd and Johnson Tan, co-authors to the first edition of this chapter, as portions of their work has been retained herein.</footnote-para>
            </footnote>

    </chapter>
    <chapter no="14">
        By Paul Starr<footnote id="AHK-14.1.fn0" prefix="*">
                <footnote-para>Heartfelt thanks to Jennifer Lee-Shoy, Stefania Lucchetti, Samuel Tang and Rita Wong.</footnote-para>
            </footnote>

    </chapter>
    <chapter no="15">
        By Timothy Hill and Mark Lin
    </chapter>
    <chapter no="16">
        By Denis Brock and Shirley Wu
    </chapter>
    <chapter no="17">
        By Peter Chow
    </chapter>
    <chapter no="18">
        By Paul Starr<footnote id="AHK-18.1.fn0" prefix="*">
                <footnote-para>Heartfelt thanks to Jennifer Lee-Shoy, Samuel Tang and Rita Wong for their assistance with this chapter.</footnote-para>
            </footnote>

    </chapter>
    <chapter no="19">
        By Kathryn Sanger, Joseph Chu and Bing Yu
    </chapter>
    <chapter no="20">
        By Loke-Khoon Tan
    </chapter>
    <chapter no="21">
        By Philip Yang and Rosita Lau
    </chapter>
    <chapter no="22">
        By Marianne Chao
    </chapter>
    <chapter no="23">
        By Dr Nils Eliasson
    </chapter>
    <chapter no="24">
        Banking, International Investor-State, Insurance, Property and Employment Disputes
        By Frances van Eupen, Vincent Li, Gary Soo and Alexander Stock
    </chapter>
</chapters>

ARBHK-Chapter01.xml
    <?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="xsl" ref="Untitled28.xslt"?>
<chapter num="A">
    <title>
        <content-style font-style="bold">PART 1 GENERAL PRINCIPLES</content-style>
    </title>

        <title>
            <content-style font-style="bold">Chapter 1: THE NEW ARBITRATION ORDINANCE</content-style>
        </title>

</chapter>

and the xslt i tried is as below
Untitled28.xslt
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="html" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">

                <xsl:text disable-output-escaping="yes"><![CDATA[</meta>]]></xsl:text>
                <title>
                    <xsl:value-of select="substring-after(chapter/section/title,':')"/>
                </title>
                <link rel="stylesheet" href="er:#css" type="text/css"/><xsl:text disable-output-escaping="yes"><![CDATA[</link>]]></xsl:text>

                <xsl:call-template name="new"/>

    </xsl:template>

<xsl:template match="chapters/chapter" name="new">

<xsl:apply-templates select="document('AHK-authors.xml')/head-4">
</xsl:apply-templates>

</xsl:template>
</xsl:stylesheet>

the o/p i'm getting is as below

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </meta>
        <title> THE NEW ARBITRATION ORDINANCE</title>
        <link rel="stylesheet" href="er:#css" type="text/css"/>

but i want  to list all the authors information.
please let me know how do i do it.
Thanks

A: Check your XPath in  where you are directing looking for "/head-4", you must put it from document element or put // slash instead of one which should work


text:
Q: pyrocms: access forbidden on front-end when creating module I am trying to create a simple module to test things out and whenever I go to the module page http://mysite.com/testmodule I get a "forbidden, access denied" error.
the only thing the module does is echo out a test string:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class testmodule extends Public_Controller
{
 /**
  * Constructor method
  *
  * @author PyroCMS Dev Team
  * @access public
  * @return void
  */

 public function __construct()
 {
  parent::__construct();
  echo 'test';

}

}

Any idea why this might be happening?

A: I'm not overly familiar with PyroCMS (as in, not at all) but it is based on Codeigniter...
in which case, it seems likely that the following might help. Apologies if they are not appropriate for PyroCMS.
Try it again like this:
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');

    class Testmodule extends Public_Controller
    {
     /**
      * Constructor method
      *
      * @author PyroCMS Dev Team
      * @access public
      * @return void
      */

     public function __construct()
     {
      parent::__construct();
     }

    public function index()
    {
      echo 'Test';
    }
}

Your problems may be:
1) You were echoing in your constructor not in a default function
2) Your class name did not start with a capital letter
Hope that helps!


text:
Q: What is the difference between ASP.NET Web Pages and Razor? Is "Web Pages" just another name for "Razor"? Or has is added new features to the "Razor" which has been used since ASP.NET MVC3?
If Web Pages is a new thing besides ASP.NET WebForm and MVC, how can I create a "Web Pages" project in Visual Studio?

A: Web Pages is like Web Forms but with razor syntax.
Razor is the syntax used on the view pages (.cshtml is the razor extension).

A: Yeah, Razor is just syntax that provides a fast, approachable, and lightweight way to combine server code with HTML to create dynamic web content. If you want to create a "Web Pages" project in Visual Studio, then follow the steps that are described in the tutorial Program ASP.NET Web Pages in Visual Studio. This will give you detailed information on the step by step creation of Web pages project in visual studio including screenshots which will make your process easier.


text:
Q: i am getting permission denied after writing rules in firebase     import React, { useReducer, useState ,re} from 'react';
import uuid from 'react-uuid';
import { useDispatch } from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import database from '../firebase/firebase';
import snapshot from '../firebase/firebase';
import '../App.css';
import { auth } from 'firebase';

const AddTasks = () => {

    const dispatch = useDispatch();
    const newLocal = null;
    const [selectedDate, setSelectedDate] = useState(newLocal);
    const [task, setTask] = useState('');
    const date = new Date()

here i want to add task with user but gettin permission issue want to set users=> task but it gives me getState is not a function so i tried
eturn (dispatch, getState) but its do nothing

    const addTask = () => {
//  return (dispatch, getState) => {
//       const uid =  getState().auth.uid
         console.log(selectedDate);
        const payload = { id: uuid(), text: task, completed: false, addedAt: JSON.stringify(selectedDate)}
        console.log(payload)

i tried ref(users/${uid}/tasks) but not working

const dbtasksWrapper = database.ref().child('tasks');
            return dbtasksWrapper.child(payload.id).update(payload).then(() => {
                    dispatch({ type: "ADD_TASKS", payload })
                 })
            setTask('');
            setSelectedDate(null);
        //  }
     }

return (
    <form onSubmit={e => {
        e.preventDefault(e.target.value);
        addTask();
    } }>
        <input className="input-group-prepend" value={task} placeholder="Enter your Task" onChange={e => setTask(e.target.value)} />
        <DatePicker className="input-group-prepend" placeholderText="Enter task date " selected={selectedDate} onChange={(date) => setSelectedDate(date)} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy H:mm aa" minDate={date} /><br />
        <input className="btn btn-primary" type='submit' value='Submit' />

    </form>
);

};

export default AddTasks;

i have edit rules for my task want to set for Auth user but its not working      PERMISSION_DENIED: Permission denied
 "rules": {

      "users":{
        "$user_id":{
          ".read": "$user_id === auth.uid",
            ".write": "$user_id === auth.uid ",
          "tasks": {
            "$task_id": {

i think the issue is here in "newData.hasChildren but dont know whats wrong??
              ".validate": "newData.hasChildren(['task', 'addedAt', 'complete'])",

                "task":{
                  ".validate": "newData.isString() && newData.val().length > 0 "
                },
                "addedAt":{
                  ".validate": "newData.isString()"
                },
                "complete":{
                  ".validate": "newData.isBoolean()"
                },

                "$other": {
                ".validate": false
            }
            }
          },

        }
      }

  }
}

A: const AddTasks = () => {

    const dispatch = useDispatch();
    const newLocal = null;
    const [selectedDate, setSelectedDate] = useState(newLocal);
    const [task, setTask] = useState('');
    const date = new Date()

useSelector for uid as following

const userId = useSelector(state => state.auth.uid);

    const addTask = () => {
        console.log(userId);
        const payload = { id: uuid(), text: task, completed: false, addedAt: JSON.stringify(selectedDate)}

then add child userId and its done

const dbtasksWrapper = database.ref().child(userId).child('tasks');
            return dbtasksWrapper.child(payload.id).update(payload).then(() => {
                setTask('');
                setSelectedDate(null);
                dispatch({ type: "ADD_TASKS", payload })
            })
         }


text:
Q: How to define readable shortcuts for international keyboards? I thought I can use the string representation of a keyboard key to configure shortcuts, i.e. let somebody define a keystroke in a resource bundle and pass that value directly to javax.swing.KeyStroke.getKeyStroke(String). But this does not work for international keyboards, e.g. arabic. There the keyboard keys are only high level key typed events, but shortcuts need to be defined as low level key pressed events with their key code representation. If one knows the according key code one can use the english representation of that key to get it working, but where should one know this from? I wrote a key listener that tells that, but I need something while parsing a String programmatically. Any ideas to use the natural language dependent key representation for shortcuts?
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class InternationalKeyStroke {

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

            public void run() {
                JFrame frame = new JFrame();
                frame.setPreferredSize(new Dimension(600, 400));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel panel = new JPanel();
                final JLabel label = new JLabel("Type the key you want to know the key code of!");
                panel.add(label);
                frame.addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyPressed(KeyEvent e) {
                        String text = "Key " + e.getKeyChar() + " needs to be configured with char ='" + (char) e.getKeyCode() + "'";
                        label.setText(text);
                        System.out.println(text);
                    }

                });
                frame.getContentPane().add(panel);
                frame.pack();
                frame.setVisible(true);

                KeyStroke working = KeyStroke.getKeyStroke("control typed A");
                label.registerKeyboardAction(new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent event) {
                        System.out.println("Working action " + event);
                    }
                }, working, JComponent.WHEN_IN_FOCUSED_WINDOW);

                KeyStroke target = KeyStroke.getKeyStroke("control typed ش");
                System.out.println(target);
                label.registerKeyboardAction(new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent event) {
                        System.out.println("Not working Action " + event);
                    }
                }, target, JComponent.WHEN_IN_FOCUSED_WINDOW);
            }
        });
    }
}

A: This seems not to be possible. I checked Microsoft Office and Eclipse and they all don't use the real unicode letter of the current locale, but the letter of the according virtual key code...


text:
Q: Telegram API: how to get username from id (Python telepot)? I save ids of all users of my bot in a database but how can I get their current username if I know id? I'm using Python 3 and Telepot framework.

A: Information about a user from user_id can be obtained by the getChat method in telepot.
bot = telepot.Bot(TOKEN)
info = bot.getChat(user_id)
print(info)

A: you can get the inforamtion of an account by checking the entity.
You can try to get the entity with this method:
entity = client.get_entity(chat_id)

then Print the entity and try to get the name from there with something like name = entity.chat.name


text:
Q: Counterexample for $\lim_{n\to\infty} (a_{n-1}-a_n) = 0 \Rightarrow a_n$ converges I think the equation above is false, but I cannot find a counterexample.
Also, I think that the implication is true when $a_n^2 \to 1$ is also required.
Suppose we have $a_n\in\mathbb{C}\ \forall n\in\mathbb{N}$.
Can you help me?

A: Hint: What happens if $a_n=1+\frac12+\frac13+\cdots+\frac1n$?

A: If $a_n=\log n,$ $\lim_{n\rightarrow \infty}(a_n-a_{n-1})=\lim_{n\rightarrow \infty}\log (1+\frac1{n-1})=0$.
However, $a_n\rightarrow \infty (n\rightarrow\infty).$


text:
Q: How can I change the terminal in VS Code to the VS Live Share Space rather than my local drive? I have connected to my team's VS Code Live Share workspace from my VS Code App. However it doesn't let me access the terminal for that space, instead being a proxy of my local terminal and the files contained under it on my personal machine.
VSCode Pic


text:
Q: Número de elementos no corresponde con tamaño de paginación El código en mi controlador es:
@Autowired
private INewsService newsService;

@RequestMapping(path = "/news", method = RequestMethod.GET)
public Page<NewsItem> listNews(@RequestParam(name="page", defaultValue = "0") int page ){
    Pageable pageRequest = new PageRequest(page, 4);

    Page<NewsItem> newsItemsList = newsService.getLastNewsItems(pageRequest);

    return newsItemsList;
}

Por lo que espero recibir 4 registros de los 12 que tengo en la base de datos. Pero cuando levanto el servidor, y me voy a http://localhost:8080/news
Recibo los siguientes elementos:
{
"content":
[{
"idNewsItem":1,"title":"noticia 1","content":"cuerpo 1","createDate":1623196800000
},
{
"idNewsItem":2,"title":"noticia 2","content":"cuerpo 2","createDate":1623283200000
},
{
"idNewsItem":3,"title":"noticia 3","content":"cuerpo 3","createDate":1623369600000
},
{
"idNewsItem":4,"title":"noticia 4","content":"cuerpo 4","createDate":1623456000000
},
{
"idNewsItem":5,"title":"noticia 5","content":"cuerpo 5","createDate":1623542400000
},
{
"idNewsItem":6,"title":"noticia 6","content":"cuerpo 6","createDate":1623628800000
}],
"totalPages":4,"totalElements":14,"last":false,"number":0,"size":4,"sort":null,"first":true,"numberOfElements":6}

Es decir, 2 elementos más cuando deberían ser 4.. esto no lo entiendo. Alguien sabe por qué pasa esto?


text:
Q: How to read a char* string by fread function? We called a library to read text, this library API only accepts a FILE* pointer. It actually reads file text by fread() call internally.
But we also need to use this library to read text from a char* string rather than a FILE*.
Of course we can write the char* string into a temp file but we're not allowed to do this for some reasons...
How to do ? Thanks !!

A: Check out fmemopen
The fmemopen() function shall associate the buffer given by the buf argument with a stream.
#include <stdio.h>

static char buffer[] = "foobar";

int main (void)
{
  FILE *stream;

  stream = fmemopen (buffer, strlen (buffer), "r");

  /* You got a FILE* pointer, you can call your function here :-) */
}

A: It can be done, but it's not easy and quite complicated.
You can create a shared-memory file handle with shm_open, this file handle can the be used by mmap to make it point to the memory area of the string, then use fdopen to create a FILE pointer from the file descriptor.
Note: This will only work on POSIX (e.g. Linux or Mac OSX) systems. Windows systems should have similar functionality, but it still won't be easy.
Edit It's probably something similar to this that happens behind the scenes in the fmemopen call referenced in the answer by Massimo Fazzolari.

A: Hmm, short of writing your own device driver to communicate back with the process somehow, this is a tricky one. By that, I mean you could create a character device which would, when read from, communicate via some sort of IPC (shared memory, named pipes, or other things) back to the process.
But this is (1) nasty, (2) UNIX-specific (non-portable) and (3) a very bad idea :-)
Without such low-level tricks (or with non-portable extensions that can treat memory like file handles), this cannot be done - fread expects a FILE* and will read from a file handle, that's it, really.

A: On various unix systems, you can create a pipe/socket or similar file descriptors, and use fdopen() to open the file descriptor and get a FILE* pointer. Then feed the string into the pipe/socket.
I suggest you check you program/library design when you run into strange problems like this. Strange problems/requirements are strong indications of bad designs.

A: I don't think this can be done. fread can read only from a file stream i.e either FILE * or stdout.


text:
Q: Force HTML table to exceed div width: CSS This question is asking the opposite of what usually is desired: a fixed-width table that exceeds the width of its parent div(s).
In fact, the following implementation works as expected in Chrome/Chromium based browsers:

#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
  width: 1040px;
  /* Full-width */
  table-layout: fixed;
}

/* This is intended to be in a media query for screens less than 768 px */

#myTable {
  width: 745px;
  /* Full-width + 225px */
}

td:nth-child(1),
th:nth-child(1) {
  width: 51.9px;
}

td:nth-child(2),
th:nth-child(2) {
  width: 158.783px;
}

td:nth-child(3),
th:nth-child(3) {
  width: 225px;
}

td:nth-child(4),
th:nth-child(4) {
  width: 78.2667px;
}

td:nth-child(5),
th:nth-child(5) {
  width: 116.15px;
}

td:nth-child(6),
th:nth-child(6) {
  width: 100.833px;
}

        col1
        col2
        col3
        col4
        col5
        col6

        col1
        col2
        col3
        col4
        col5
        col6

        col1
        col2
        col3
        col4
        col5
        col6

        col1
        col2
        col3
        col4
        col5
        col6

However, when checking in Firefox and Microsoft Edge, the specified table/column widths are not honored, instead conforming to the parent div.
Most suggested solutions I've found appear to recommend applying table-layout: fixed; rule to the table, however, it's already applied in this example to no effect.
Anyone have any ideas?

A: Typically I use a class/ID wrapper and based on the max-width of the wrapper assign the table's width:100% which will then create the scrollbar effect with the overflow:scroll hidden property which is what I think you're looking for? If you  want vertical scroll.
I never use the table-layout fixed attribute which would seem to be the problem., but then again I don't use it.
Just assign the table CSS at width:100% and use the @media with the table's wrapper based on screen size. This will work great for the column's adaptations too. You will just have to adjust accordingly.
By assigning the parent div's width inline you are creating somewhat of a roadblock for your responsive css capabilities as you cannot override inline styles. I'd change that approach.
#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
  width: 100%;
  overflow: scroll hidden;
}

 .tbl_wrapper{max-width: 540px;}

@media screen and (max-width: 768px){

.tbl_wrapper{max-width: 540px;}
}

@media screen and (max-width: 1040px){

.tbl_wrapper{max-width: 640px;}
}


text:
Q: Why does this Nokogiri command strip out HTML tags? This is a continuation of a previous question. I'm having problems with this Nokogiri snippet:
>> require 'nokogiri'
>> html = 'bad
markup
with'
>> Nokogiri::HTML(html).at_css('body').children.map {|x| '
' + x.text + '
'}.join('')
=> "
bad

markup

with

"

What happened to my image tag? It seems that Nokogiri might be stripping ALL the HTML tags present (including my original
 around the word "markup"), and replacing them. How do I prevent this from happening? All I want to do is ensure that entirely untagged text is wrapped in a
 tag...

A: Only wrap the element in a p tag if it is a text node, otherwise call to_html on it:
require 'nokogiri'

html = 'bad
markup
with'

Nokogiri::HTML(html).at_css('body').
children.map do |x|
  if x.text?
    '
' + x.text + '
'
  else
    x.to_html
  end
end.join('')
#=> "
bad
\n
markup

with
"


text:
Q: Py-StackExchange raise a valueError I try to use the StackExchange API and I found the Py-StackExchange library for Python. I installed it through easy_install in Windows.
Here is the code:
from stackexchange import Site, StackOverflow

so = Site(StackOverflow)
my_favourite_guy = so.user(2309097)
print my_favourite_guy.reputation.format()
print len(my_favourite_guy.answers), 'answers'

And here is the error:
Traceback (most recent call last):
  File "C:\Users\Tasos\Desktop\test - Copy.py", line 8, in <module>
    my_favourite_guy = so.user(2309097)
  File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 626, in user
    u, = self.users((nid,), **kw)
  File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 631, in users
    return self._get(User, ids, 'users', kw)
  File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 621, in _get
    return self.build(root, typ, coll, kw)
  File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 598, in build
    json = self._request(url, kw)
  File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 570, in _request
    json, info = request_mgr.json_request(url, new_params)
  File "build\bdist.win-amd64\egg\stackexchange\web.py", line 120, in json_request
    return (json.loads(req.data), req.info)
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

I saw in Wiki the following but I don't use any proxy and the code version is the latest through easy_install:

This is probably the result of some proxy/router mangling with request
  headers. It could be that your router/proxy adds headers requesting
  gzip data, but doesn't decompress it, and that you are running a
  slightly old version of the code which does not deal with gzip
  compression. In this case, just update to the latest version of the
  library.

A: The version on PyPI is well out of date (released 2011) and still uses API version 1.1, which has been shut down.
The Github codebase has been updated to use API v2.2, install that directly:
pip install git+https://github.com/lucjon/Py-StackExchange

or using easy_install, download the current master zip:
easy_install https://github.com/lucjon/Py-StackExchange/archive/640eac1525baaf57474ddbc3be2b580f00e4f1e8.zip

To get answers listed you need to call .fetch():
print len(my_favourite_guy.answers.fetch()), 'answers'

This only fetches the first page of answers:
>>> from stackexchange import Site, StackOverflow
>>> so = Site(StackOverflow)
>>> my_favourite_guy = so.user(2309097)
>>> print my_favourite_guy.reputation.format()
563
>>> print len(my_favourite_guy.answers.fetch()), 'answers'
19 answers
>>> my_favourite_guy = so.user(100297)
>>> print my_favourite_guy.reputation.format()
251.2k
>>> print len(my_favourite_guy.answers.fetch()), 'answers'
30 answers

I have a few more than 30 answers, last time I checked. Use .extend_next() calls to fetch the next query set, until you run out.


text:
Q: How can I freeze the first column and the first row with a scrollable table on R markdown? I would like to block the first row AND the first column in a Kable or flextable table on a Rmardown file  for html. The subject has already been discussed on SO but there is no answer. I don't want to use the DT package.
Maybe there would be a way to adapt the scroll_box function (kableExtra package)? Or to modify the concerned cells? I don't have HTML skills to do this.
Thank you in advance for your help!

A: The creator of the flextable package added this option for html reports.
This does not exist on the kableEtra package or any other package as far as I know.
library(flextable)
dat <- lapply(1:30, function(x) rnorm(n = 50)) %>%
  setNames(paste0("colname", 1:30)) %>%
  as.data.frame()

ft_1 <- flextable(dat)
ft_1 <- set_table_properties(ft_1,
                             opts_html = list(
                               extra_css = ".tabwid tbody tr > :first-child {position: sticky;z-index: 1;left: 0;background: #ddd;}",
                               scroll = list(height="500px")))
ft_1

https://github.com/davidgohel/flextable/issues/461


text:
Q: How do I call a file.js into a file.html What I am trying to do is run the script in file.js to onload prompt username. But for some reason every time the script is on the html file it works but when I move it to the file.js it doesn't work. Any Idea why this is happening?
My main goal is to separate my scripts from my html.
file.html

file.js

A: file.js is a JavaScript file - it can't have  tags in it since those are HTML script element tags. Remove those and it works.
Keep in mind:

*

*Your  tag wasn't closed.

*Your  tag wasn't closed.

*Your function isn't closed properly, you're missing a }.

*You were missing an element with the ID "Name".

*JS files are best put at the end of your  so the browser can render the page without having to wait for the JS files to load. The code will still work because the onload event is fired at the end of the document loading process.

Working code:

function myFunction() {
  var person = prompt("Please enter your name", "Your Name here");
  if (person != null) {
    document.getElementById("Name").innerHTML = "Hello " + person + "! How are you today?";
  }
}


text:
Q: jquery ajax complete function firing immediately I have a strange situation I have never seen before. I have a jquery ajax that calls a method that does a sql query, builds the json response and write its back out to the response stream.
As soon as the ajax call is  executed the complete function fires as a success with a null response text.... I can debug the method and see that is it is building the response and returning it. Just not sure here any ideas? ASP .net if that helps.
        jQuery.ajax({
            url: 'Data/ServiceCalls.aspx?SelectRequestsWithDate=1&start_date=' + escape(jQuery("#request_start_date").val()) + '&end_date=' + escape(jQuery("#request_end_date").val()) + "'",
            type: "POST",
            dataType: "json",
            success: function (jsonresponse, stat) {

                if (stat === "success") {
                    var thegrid = jQuery("#grid_requests")[0];
                    var jsonObject = eval('(' + jsonresponse.responseText + ')');
                    thegrid.addJSONData(jsonObject);
                    jsonresponse = null;
                    thegrid = null;
                }
            }

        });

A: As you are using POST, you could try sending data as POST values instead of as GET appending it to your url, like:
jQuery.ajax({
   url: 'Data/ServiceCalls.aspx",
   type: "POST",
   dataType: "json",
   data : {"SelectRequestsWithDate" : 1"...},
   ......

Or try using GET as your type

A: If you want to debug, jus move the sucess callback function to a separate one:
jQuery.ajax({
            url: 'Data/ServiceCalls.aspx?SelectRequestsWithDate=1&start_date=' + escape(jQuery("#request_start_date").val()) + '&end_date=' + escape(jQuery("#request_end_date").val()) + "'",
            type: "GET",
            dataType: "json",
            success: callback
        });

function callback (jsonresponse, stat) {

                if (stat === "success") {
                    var thegrid = jQuery("#grid_requests")[0];
                    var jsonObject = eval('(' + jsonresponse.responseText + ')');
                    thegrid.addJSONData(jsonObject);
                    jsonresponse = null;
                    thegrid = null;
                }
            }

A: I thankyou for all your suggestions. Issue seems to be that I had the ajax call inside of jqgrid. For whatever reason it was making the success function fire immediately. I moved it outside the grid and everything started working.
Not the best answer but maybe it will help someone else.
Blake


text:
Q: Javascript in ajax loaded modal popup I'm working on a module that needs to open modal window and show some content inside of it + some js logic.
So I load template with ajax request which works just fine: (simplified template):
<input type="checkbox" id="show_date" name="show_date" class="control-checkbox admin__control-text"/>
<input name="date" id="date" title="<?php echo __('Date') ?>" value=""
           class="date input-text admin__control-text" type="text"/>

require([
    "jquery",
    "mage/calendar"
], function ($) {
    $('#show_date').on('change', function () {
        console.log('Changed');
    });

    $("#date").calendar({
        buttonText: 'Select date',
        showTime: false,
        beforeShowDay: $.datepicker.noWeekends
    });
});

Afterwards modal window is opened with the template content:
        var modal = $('<div/>').html(content);
        modal.modal({
            title: $.mage.__('Modal'),
            innerScroll: true,
            modalClass: '_image-box',
            buttons: [{
                text: $.mage.__('Save'),
                attr: {
                    'data-action': 'save'
                },
                'class': 'action-primary',
                click: function () {
                }
            }]
        }).trigger('openModal');

When this happens for the first time everything works as expected. The checkbox does its thing and the calendar works as well.
The problem is that when the modal window is opened for second time without page reload(load tempalte with ajax -> open the modal), it breaks. None of the javascript works.
When the js is changed to use .live instead of .on, the checkbox works every time.
I also tried to move calendar initialization out of the template. In this case the calendar is initialized, however after clicking on specific date it does not change value of the text input.
Any ideas how to fix this issue?
Any help would be greatly appreciated.

A: Main problem with Modal, that Magento remove DOM elements after modal was closed and store template for next call somewhere. After that call was make it's completely new DOM and jQuery recognize is as new too, because of it not previuosly made bindings works.
You can use modal option "opened":
modal.modal({
    ...
    opened: function () {
        $('#show_date').on('change', function () {
            console.log('Changed');
        });

        $("#date").calendar({
            buttonText: 'Select date',
            showTime: false,
            beforeShowDay: $.datepicker.noWeekends
        });
    },
    ...
});


text:
Q: Wordpress 4.1 - Changed Site Language & now 500 Internal Error when trying to login I changed the 'Site Language' in the backend of a site from US English to CA English and now I am getting a 500 Internal server error when trying to login through the backend. Because of this, I cannot change the language back.
How can I regain access to my WP dashboard?
Just wondering if there is something I could revert to within the database (site_Language) as a default? Hoping there is an answer out there - don't want to re-install..
Cheers!

A: MAGIC!!
FIXED - Added define( 'WP_MEMORY_LIMIT', '96M' ); within wp-config in increase the memory limit. Have never run into this issue in 30+ sites.. SimplePie include was throwing a fatal error.

A: Try to change the global variable in the wp-config.php:
define ('WPLANG', 'en_CA');

A: FIXED - Added define( 'WP_MEMORY_LIMIT', '96M' ); within wp-config in increase the memory limit. Have never run into this issue in 30+ sites.. SimplePie include was throwing a fatal error.


text:
Q: How to update value of input values with useRef in a map function? I have decided to use refs to hook into the inputs,
In fact I created a custom hook to consume the fetched data and then make the refs!
 function useCreateRefFromProfileDataFromApi(profileDataFromApi) {
    const [profileData, setProfileData] = useState([]);
    const newArray = profileDataFromApi.map((data) => React.createRef())

    useEffect(() => {
      setProfileData(newArray)
    }, [profileDataFromApi.length])

    return profileData
  }

  const profileData = useCreateRefFromProfileDataFromApi(profileDataFromApi);

Which I use in the map function:

      {profileDataFromApi.map((data, index) => {
        const { id, name, value } = data
        return (

 handleClick(index)}>{name}{' '}
            <input
              ref={profileData[index]}
              type="text"
              value={value}
              className=" mt-1 mb-2 bg-transparent border-0 px-3 py-3 text-textColor   rounded focus:outline-none focus:ring w-full"
              onChange={(e) => {
                handleChange(index, e.target.value)
              }}
            />

        )
      })}

However I can't get the onChange function to update the value.
The onClick work as expected:
  function handleClick(index) {
    profileData[index].current.focus();
  }

But not the onChange:
  function handleChange(index, value) {
    profileData[index].current.value = value
  }

So how do I get the handleChange to update, i.e. DOM and profileDataFromApi????
Also this the whole component:
import React, { useEffect, useState, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';

import getProfile from '../../clientApi/GetProfile'
import { useUser } from '../../lib/hooks'

export default function ProfilePage({ }) {

  const interestedActivitiesRef = useRef();
  const { user } = useUser();

  const [profileDataFromApi, setProfileDataFromApi] = useState([]);
  const [interestedActivities, setInterestedActivities] = useState([])
  const [profileLoaded, setProfileLoaded] = useState(true);
  const [input, setInput] = useState('')

  function useCreateRefFromProfileDataFromApi(profileDataFromApi) {
    const [profileData, setProfileData] = useState([]);
    const newArray = profileDataFromApi.map((data) => React.createRef())

    useEffect(() => {
      setProfileData(newArray)
    }, [profileDataFromApi.length])

    return profileData
  }

  const profileData = useCreateRefFromProfileDataFromApi(profileDataFromApi);

  useEffect(async () => {
    if (user !== undefined && profileLoaded) {
      setProfileLoaded(false);

      const fetchProfile = async () => {
        const { data } = await getProfile();

        const { email } = data[0]._user
        const obj = data[0];
        const { __v, _user, _id, ...profile } = obj;

        profile.email = email;

        for (const profileProp in profile) {

          if (profileProp === 'interested-activities') {
            setInterestedActivities(oldArray => [...oldArray, { id: uuidv4(), 'name': profileProp, 'value': profile[profileProp] }]);
          } else {
            setProfileDataFromApi(oldArray => [...oldArray, { id: uuidv4(), 'name': profileProp, 'value': profile[profileProp] }]);
          }
        }

      }
      fetchProfile()
    }
    return () => { setProfileLoaded(true) }
  }, [])

  function handleClick(index) {
    profileData[index].current.focus();
  }

  function handleChange(index, value) {
    profileData[index].current.value = input
  }

  function handleInterestedActivitiesRefClick(ind) {
    interestedActivitiesRef.current[ind].focus();
  }

  return (

Click on text e.g. "Interested Activities" to upate values.

          {profileDataFromApi.map((data, index) => {
            const { id, name, value } = data
            return (

 handleClick(index)}>{name}{' '}
                <input
                  ref={profileData[index]}
                  type="text"
                  value={value}
                  className=" mt-1 mb-2 bg-transparent border-0 px-3 py-3 text-textColor   rounded focus:outline-none focus:ring w-full"
                  onChange={(e) => {
                    handleChange(index, e.target.value)
                  }}
                />

            )
          })}

)

}

A: The problem is that you need to differentiate what is the correct way to handle input change when you use controlled-components or uncontrolled-components in this case you are using the onChange event as if you had a controlled-component, in "uncontrolled-components" the value is accessed from input.current.value but you should not update it in every onChange event
Basically these are the differences:
controlled-components: A state is used to store the value of the input every time it changes, also the ideal thing would be to tell the input that its value is the state value, in this way the value will be uniform and always the same.
Ref: https://reactjs.org/docs/forms.html#controlled-components
uncontrolled-components: The value of this input is obtained by binding a reference, so when you want to access the value you just have to do input.current.value
Ref: https://reactjs.org/docs/uncontrolled-components.html


text:
Q: Credential filling in cross-origin iFrame The same origin policy prohibits that a top-level domain can access cross-origin iFrames. A browser extension's content script runs in the context of the top-level page (https://developer.chrome.com/extensions/content_scripts) and thus cannot access an iFrame if it is cross-origin. Is it impossible that a password manager extension can fill in credentials into a cross-origin iFrame? How do password manager vendors handle this?
I guess this is only possible for password managers that are built in to the browser itself, but not for browser extensions.

A: From your link (https://developer.chrome.com/extensions/content_scripts):
all_frames

Optional. Defaults to false, meaning that only the top frame is
  matched.
If specified true, it will inject into all frames, even if the frame
  is not the topmost frame in the tab. Each frame is checked
  independently for URL requirements, it will not inject into child
  frames if the URL requirements are not met.


text:
Q: How to calculate the released energy in a fusion reaction knowing the mass of the reactants? this the reaction formula:$H^2_1 + H^3_1 ->He^4_2 + n^1_0$ (idk how to put the numbers in the left)
and I have the released energy of one reaction $E_r=2,8.10^{-12}J$, How to calculate the released energy if the mass of $H_1^2$ is $1g$ and the mass of $H^3_1$ is $2g$?
$N_A=6,02 . 10^{23}$
so I have to calculate the number of nuclei, but is it because it's fusion the number of nuclei is the half of the sum of the number of nuclei of both reactants? what about fission too?
thanks
and I'm sorry for bad english

A: A tritium nucleus has approximately 3/2 times the weight of a deuterium nucleus.  So, if you have 1 gram of deuterium and 2 grams of tritium, you don't have enough deuterium for all of the tritium to fuse.  You would need 1.33 grams of deuterium.  So the energy released from 1 gram of deuterium and 2 grams of tritium would be very nearly the same as that from 1 gram of deuterium and 1.5 grams of tritium.


text:
Q: Created DirectShape is not extracted through forge I generated (in debug mode an addin) DirectShape as a Volume of a Room as in:
https://github.com/jeremytammik/RoomVolumeDirectShape
Rooms are generated and REVIT file is saved correctly, then I send it to FORGE for processing and I extract Model View Metadata Properties (mvmp) and the OBJ.
The issue is that MVMP does not contain any information of recently generated room volumes, the object is:
DirectShape ds = DirectShape.CreateElement(doc, _id_category_for_direct_shape);
                ds.ApplicationId = id_addin;
                ds.ApplicationDataId = r.UniqueId;
                ds.SetShape(geo.ToList<GeometryObject>());
                ds.get_Parameter(_bip_properties).Set(json);
                ds.Name = "Room_Max_is_an_okayish_dev_" + r.Name;

The question here is: how should I modify it so it will be included in the extraction mvmp.json?
I suspect I need to tag it somehow or add it to some sort of collection.
Please help.
Thank you in advance.

A: In Revit, you can define which views are to be included in the Forge translation process.
Ensure that you see your direct shapes in at least one of your Revit views, and that this view is earmarked for translation to Forge.


text:
Q: Understanding a Simple Proof with Integrals In this machine learning paper, the following lemma is stated (and proven in the Appendix A, cf. page 11):

Lemma A.1 For random variables $X$, $Y$ and function $f(x, y)$ under suitable regularity conditions:
$$\mathbb E_{x\sim X, y\sim Y \mid x}[f(x, y)] = \mathbb E_{x\sim X, y\sim Y \mid x, x'\sim X\mid y}[f(x', y)].$$

In their proof, I don't understand the following transition:
\begin{align}
\mathbb E_{x\sim X, y\sim Y\mid x}\left[f(x, y)\right] = \dots &= \int_{x}\int_{y}P(x, y)f(x, y)\int_{x'}P(x'\vert y)dx'dydx
\\[6pt] &= \int_{x}P(x)\int_{y}P(y\vert x)\int_{x'}P(x'\vert y)f(x', y)dx'dydx
\end{align}
In particular, I'd like to understand why $f(x, y)$, which is integrated over $x$ in the first line, can be integrated over $x'$ in the second line? Thanks a lot!

A: My interpretation: they meant to write
\begin{align}
\mathbb E_{x\sim X, y\sim Y\mid x}\left[f(x, y)\right] = \dots &= \int_{x}\int_{y} \int_{x'} P(x, y)f(x, y) P(x'\vert y)dx'dydx
\\[6pt] &= \int_{y}\int_{x} \int_{x'}P(y) P(x\vert y)P(x'\vert y)f(x, y)dx'dydx \\[6pt]
&= \int_{y}\int_{x}\int_{x'}P(y) P(x\vert y)P(x'\vert y)f(x', y)dx'dydx
\end{align}
The order of integration doesn't matter by Fubini. The final equality holds because of symmetry: Simply swap the variables $x$ and $x'$.


text:
Q: Method may only be called on a Type for which Type.IsGenericParameter is true and The type initializer for 'XYZ' threw an exception I have a set up similar to this:
Program.cs
{
     public static void Main(string[] args)
     {
          XYZ.SomeMethod(); //--> XYZ is accessed for the firsttime here
     }

     private void OnDBInstall(object sender, EventArgs e)
     {
          //after Db install is complete
          if(success)
          {
               InvokeMethod(SomeEvent) //-->this is the second time XYZ is accessed
          }
     }
}

public static class Utility
{
     public static void InvokeSomeMEthods(EventHandler<T> h)
     {
          if(h!=null)
          {
               foreach(EventHandler<T> eh in h.GetInvocationList())
               {
                   eh.Invoke(null, EventArgs.Empty);
               }
          }
     }
}

public static class XYZ
{
     private static XYZCache _cache = new XYZCache();

     static XYZ()
     {
          SomeEvent += OnSomeEvent;
          _cache.Initialize();
     }

     static void OnSomeEvent(object sender, EventArgs e)
     {
          _cache.Initialize();
     }

     static void SomeMethod()
     {
          //some db call
     }
}

internal class XYZCache
{
     internal void Initialize()
     {
          //some db call
     }
}

I get multiple exceptions at different stages. When XYZ.SomeMethod() is called the first time, I get, "Cannot open database ".." requested by the login. The login failed". OK this is good because the database doesn't exist at that point.  I should have checked if the DB exist first before making any Db calls. And this exception is left unhandled.
Then the other exceptions I get at eh.Invoke (DB is created and available at this point): "The type initializer for 'XYZ' threw an exception", "Method may only be called on a Type for which Type.IsGenericParameter is true.", and I also get "Cannot open database ".." requested by the login. The login failed". When I get these exception, OnSomeEvent in XYZ class is not even invoked so _cache is not accessed.
"The type initializer for 'XYZ' threw an exception" is very misleading since this is not the first time XYZ is accessed.
if XYZ.SomeMethod() is wrapped by a try catch, then everything is good. Is there a way to handle this situation without try catch? I also cannot check for the DB existence because of some weird reason.
Note: I already read this post this is very useful: Method may only be called on a Type for which Type.IsGenericParameter is true


text:
Q: How do you make a calculator? I'm making a roman calculator: An input asks for a ROMAN calculation (Like I + IV) and the output is the answer in roman numerals. If the output if more than 1000, the output is "error." Here's my code:
def toRoman (x):
    roman= ""
    hundreds = x//100
    remainder = x%100    # xx=532,  d=532//100=5, x=532%100=32
    if hundreds == 1:
        roman+="C"
    elif hundreds == 2:
        roman+="CC"
    elif hundreds == 3:
        roman+="CCC"
    elif hundreds == 4:
        roman+="CD"
    elif hundreds == 5:
        roman+="D"
    elif hundreds == 6:
        roman+="DC"
    elif hundreds == 7:
        roman+="DCC"
    elif hundreds == 8:
        roman+="DCCC"
    elif hundreds == 9:
        roman+="CM"
    tens = remainder//10#  d=32//10=3,   x= 32%10=2
    ones = remainder % 10
    if tens == 1:
        roman+="X"
    elif tens == 2:
        roman+="XX"
    elif tens == 3:
        roman+="XXX"
    elif tens == 4:
        roman+="XL"
    elif tens == 5:
        roman+="L"
    elif tens == 6:
        roman+="LX"
    elif tens == 7:
        roman+="LXX"
    elif tens == 8:
        roman+="LXXX"
    elif tens == 9:
        roman+="XC"
    if ones == 1:
        roman+="I"
    elif ones == 2:
        roman+="II"
    elif ones == 3:
        roman+="III"
    elif ones == 4:
        roman+="IV"
    elif ones == 5:
        roman+="V"
    elif ones == 6:
        roman+="VI"
    elif ones == 7:
        roman+="VII"
    elif ones == 8:
        roman+="VIII"
    elif ones == 9:
        roman+="IX"
    return roman

def toDecimal (s):
    old= 100000
    t = 0
    v=0
    for i in range(0, len(s)):
        if s[i] == "I":
            v = 1
        elif s[i] == "V":
            v = 5
        elif s[i] == "X":
            v = 10
        elif s[i] == "L":
            v = 50
        elif s[i] == "C":
            v = 100
        elif s[i] == "D":
            v = 500
        elif s[i] == "M":
            v = 1000
        if v > old:
            t = v-t
        else:
            t = t + v
        old = v
    return t

I'm kind of stuck on how to combine the functions and make the calculator. Can anyone help? Thanks.

A: Here is a possible way to shorten your functions and make them more readable:
H = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
T = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
O = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
V = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 100}

def to_roman(x):
    return H[x // 100] + T[(x % 100) // 10] + O[(x % 100) % 10]

def to_decimal(x):
    result = 0
    i = 0
    while i < len(x):
        s1 = V[x[i]]
        if i + 1 < len(x):
            s2 = V[x[i+1]]
            if s1 >= s2:
                result += s1
                i += 1
            else:
                result += s2 - s1
                i += 2
        else:
            result += s1
            i += 1
    return result

Here is how you can implement your calculator:
number1 = to_decimal(input()) # input a Roman number
operator = input() # input +, -, * or /
number2 = to_decimal(input()) # input a Roman number

if operator == '+':
    result = number1 + number2
elif operator == '-':
    result = number1 - number2
elif operator == '*':
    result = number1 * number2
else:
    result = number1 // number2

print(f'Result: {to_roman(result)}')

You should still do some work to handle special cases (divisions whose result is not an integer, negative numbers, numbers higher than 1000 etc).


text:
Q: Oracle database special characters saving as ascii When I try to save Özyeğin University to an oracle database, it saves as Özyeğin University =>  ğ = ğ
This happens in my clients database and not in mine, checked and both are using same charactersets => NLS_CHARACTERSET = AL32UTF8
Any Ideas

A: Not sure how this looks on your screen; on mine (with default U.S. settings) the character is exactly the same. With that said: often the problem is not the database character set (on the server), but the front-end character set (client) - either at input time or at retrieval time (or both). To see the exact characters stored in the database, use DUMP like so:
select 'Özyeğin' as str, dump('Özyeğin') as codes from dual;

That will tell you for sure what is stored in the DB, so you can at least narrow down the problem - is it with what is stored, or just with what is displayed when you select from the DB? (Actually, don't use DUMP() EXACTLY as I showed; rather, select dump(col_name) from table_name where id = ... where the id is some id value for the row containing the university name; you want to see what is IN A TABLE in the database, not something made up on the fly like in my example. col_name is the name of the column containing the name of the university.)
To illustrate the problem, here is a short session in SQL*Plus. Note how with my standard character set (see comments below - MY default is cp 1252 because I MADE IT TO BE) (code page 1252, Microsoft name for the Western European character set) the ğ becomes g (even in the database - it is translated by the front-end before it is even sent to the database), but if I change the character set to 1254 (for Turkish) the letter is preserved, and DUMP shows the correct code for ğ in code page 1254.
SQL> select 'Özyeğin' as str, dump('Özyeğin') as codes from dual;

STR     CODES
------- -----------------------------------------
Özyegin Typ=96 Len=7: 214,122,121,101,103,105,110

SQL> host chcp 1254
Active code page: 1254

SQL> select 'Özyeğin' as str, dump('Özyeğin') as codes from dual;

STR     CODES
------- -----------------------------------------
Özyeğin Typ=96 Len=7: 214,122,121,101,240,105,110

So: if I used the Western European character set to input data into the database, then ğ was changed to g (it doesn't matter what the DATABASE character set is, because it never received the ğ, it received g). However, if everything was fine going in, you may still see g in the output if the front-end used to look at results from the database does not use the Turkish character set. (However, in the latter case you may not get "g" - you will get whatever code 240 is in the client character set; in cp 1252 it is ð, not g...)


text:
Q: Recursion equation - problem with one same root i have problem with Recursion equation. It look like this:
$x(k+2) + 2x(k+1) + x(k) = 0 $ , $x(0) = 3$,  $x(1) = 6$
then i' m gettin:
$x^2 + 2x + 1 = 0$
zero value are:
$\Delta = 0$ , $x_{0} = -1$
$x(k) = C_{1}x_{1}^{k} + C_{2}x_{2}^{k}$
for $x(0) = 3$ i get
$C_{1} + C_{2} = 3$
The question is: Am i doing it right? In formula above $x_{1} , x_{2}$ are not the same. The question is how should i do it for $x(1)$ because it by putt for both $x_{1} , x_{2}$  $-1$ i will got $0=0$. What am i doing wrong?
//------------SECOND CASE-------------------------
$x(k+2) + 3x(k+1) + x(k) = 0, x(0) = 1, x(1) = 3$
$x^{2} + 3x + 1 = 0$
$\Delta = 1$
$r_{1} = -2$
$r_{2} = -1$
In this case i'm using this:
$x(k) = C_{1}r_{1}^{k} + C_{2}r_{2}^{k}$
right??

A: When you have a double root $r$, the general form is
$$
x_k = C_1 r^k + C_2 kr^k
$$
In this case, we have $r = -1$, so
$$
3 = x_0 = C_1
$$
$$
6 = x_1 = -C_1 - C_2
$$
which yields $C_1 = 3, C_2 = -9$, and
$$
x_k = 3(-1)^k-9k(-1)^k
$$
Substitution yields $\{x_k\}_{k=0}^\infty = 3, 6, -15, 24, -33, \ldots$ which satisfies the recurrence.
Further multiplicities yield terms of the form $k^2 r^k, k^3 r^k, \ldots$  You may see a resemblance to differential equations (if you're familiar with those), in which a double root in the characteristic equation yields a solution of the form $f(x) = C_1 e^{rx} + C_2 xe^{rx}$ (and further multiplicities yield similar terms).


text:
Q: End of the month and grouping by third month I have a question regarding the following SQL code:
DECLARE @Date1 datetime
SET @Date1 = DATEADD(DAY, -90, GETDATE());

SELECT
    A.ACCOUNTNUMBER,
    N.FIRST,
    N.MIDDLE,
    N.LAST,
    FORMAT(A.OPENDATE,'MM/dd/yyyy') AS "OPENDATE",
    FORMAT(A.RECORDCHANGEDATE,'MM/dd/yyyy') AS "LASTMEMBERACTIVITY",
    L.CHARGEOFFDATE,
    A.CLOSEDATE,
    L.CHARGEOFFTYPE,
    N.EMAIL,
    N.DEATHDATE
FROM
    ACCOUNT AS A
INNER JOIN LOAN AS L ON A.ACCOUNTNUMBER = L.PARENTACCOUNT
INNER JOIN SAVINGS AS S ON A.ACCOUNTNUMBER = S.PARENTACCOUNT
INNER JOIN NAME AS N ON A.ACCOUNTNUMBER = N.PARENTACCOUNT
WHERE (L.CHARGEOFFDATE IS NULL)
  AND (A.CLOSEDATE IS NULL)
  AND (N.DEATHDATE IS NULL)
  AND not(N.LAST Like '%Trust%')
  AND N.EMAIL <> ''
  AND a.RECORDCHANGEDATE > DATEADD(DAY, 1, EOMONTH(@Date1, -1))
group by
    A.ACCOUNTNUMBER,
    N.FIRST,
    N.MIDDLE,
    N.LAST,
    FORMAT(A.OPENDATE,'MM/dd/yyyy'),
    A.RECORDCHANGEDATE,
    L.CHARGEOFFDATE,
    A.CLOSEDATE,
    L.CHARGEOFFTYPE,
    N.EMAIL,
    N.DEATHDATE
ORDER BY
    a.RECORDCHANGEDATE desc, DATEADD(DAY, -90, GETDATE());

The desired outcome is to show only the month of 05/01/2021 right now it shows August, July, June and May, starting from the first rather than (05/02/2021) that is currently showing.
I have tried the following code and still do not seem to work:
SET @startofmonth = DATEADD(dd,1,EOMONTH(@mydate,-1))
SET @startofmonth = DATEADD(dd,1,EOMONTH(Getdate(),-2))

A: Looks like the error is in your where clause statement where you are comparing
a.RECORDCHANGEDATE  > DATEADD(DAY, 1, EOMONTH(@Date1, -1))

you are basically getting all records where a.RECORDCHANGEDATE is greater than (>) 05/01/2021
if you want all records from MAY month only use one more AND clause
AND a.RECORDCHANGEDATE <= EOMONTH(DATEADD(DAY, 1, EOMONTH(@Date1, -1)))


text:
Q: Play 2.5 type mismatch Session type Using deadbolt2 I have the following controller function implementation:
def restricted: Action = deadbolt.Restrict(List(Array(USER_ROLE)))() { request =>
  Future {
    val localUser = userProvider.getUser(request.session) // <<< expects a play.mvc.Http.Session
    Ok(views.html.restricted(userProvider, localUser))
  }
}

but it results in the following compiler error:
[error] /home/bravegag/code/play-authenticate-usage-scala/app/controllers/Application.scala:26: type mismatch;
[error]  found   : play.api.mvc.Session
[error]  required: play.mvc.Http.Session
[error]       val localUser = userProvider.getUser(request.session)
[error]                                                    ^

Basically the current request is giving me a play.api.mvc.Session but the library I depend on (play-authenticate) is expecting a play.mvc.Http.Session. Is there a way to convert between the two? or another way to get hold of the needed Http one?

A: I found how to convert from play.api.mvc.Session to play.mvc.Http.Session:
import scala.collection.JavaConversions

val session : Http.Session =
    new Http.Session(JavaConversions.mapAsJavaMap(request.session.data))

thouhg I will have to keep redoing this everywhere ... or write an implicit conversion Helper object.
UPDATE Defined my own implicit conversion helper:
package utils

import scala.collection.JavaConversions

object PlayConversions {
  /**
    * Returns the result conversion from a play.api.mvc.Session to a play.mvc.Http.Session
    * @param session play.api.mvc.Session instance
    * @return the result conversion from a play.api.mvc.Session to a play.mvc.Http.Session
    */
  implicit def toHttpSession(session: play.api.mvc.Session) = new play.mvc.Http.Session(JavaConversions.mapAsJavaMap(session.data))
}

UPDATE Actually this is the Play institutional/preferred way to do it:
import play.core.j.JavaHelpers

val context = JavaHelpers.createJavaContext(request)
// and now access the Java Http.Session
context.session


text:
Q: How to include jQuery for use with Rally SDK 2.0 I have been using jQuery while developing an app with the Rally 2.0 SDK. Everything works fine when I'm using the debug version of the page but when I upload the HTML from the dev version I'm getting a bunch of syntax errors on the jQuery include. What I've done is download the jQuery 1.7.2 min distro and saved it as jquery.js in the working folder. Then I changed my config.json to:
{
    "name": "overview_v2",
    "className": "CustomApp",
    "sdk": "2.0p2",
    "javascript": [
        "App.js",
        "jquery.js"
    ],
    "css": [
        "app.css"
    ]
}

When I compile with the Rakefile it includes the jQuery into the HTML correctly but I'm getting a few different errors:
Uncaught SyntaxError: Unexpected identifier

and
unmatched ) in regular expression

The first error comes when loading the page in Google Chrome and the second comes when loading in Firefox. Am I including jQuery the correct way or is there a better alternative?
Thanks!

A: Try upgrading to the latest version of the app sdk rakefile. There were issues with parsing regular expressions in an earlier version of the rakefile.

A: Is there a reason you're using jquery?  The SDK is build using Ext 4, which should provide most if not all the functionality contained in jquery...


text:
Q: scheduler for a database I would like to write a program in visual studio 2010 which will run a function once every 10pm. The function is to basically an insertion to the database. What would be the most easiest way of writing this? I am pretty sure I don't need ASP.NET as it is an overkill for such problem...
I am just confused on what project should I start

A: The easiest way to do this is to create a Console Application project and use the Windows Task Scheduler to schedule it to run according to whatever schedule you'd like.

A: SQL Server has the SQL Server Agent built in. You can use it to schedule such a command to run whenever you like.


text:
Q: Why does this gae example use a class method? query_book In this example is defined as @classmethod, and date is an attribute.
What does cls.date mean?
If it refers to an instance attribute, then why is it in a @classmethod?
If it doesn't refer to an instance, then whose date is it referring to?
EDIT
date doesn't seem to be a class attribute, because the following code prints out two different dates for the two instances. If it was a class attribute it would print the same value.
g1 = Greeting()
g2 = Greeting()
g1.put()
g2.put()
self.response.out.write(g1.date)
self.response.out.write("<br>")
self.response.out.write(g2.date)

A: cls.date is not an instance attribute, but a class attribute.
You can also use Greeting.date. But, if the class name is changed to Goodbye, it should be changed to Goodbye.date while cls version does not.

A: Because accessing the attribute date at class level allows to access the definition of the ndb.DateTimeProperty attribute, while accessing at instance level allows to access the value assigned to the instance.
type(g1.date).__name__ == "datetime"
type(Greeting.date).__name__ == "DateTimeProperty"