text:
Q: Where is program's path for PowerShell command? Command 'git' is available from PowerShell, I want to know where is git installed on my PC, so I tried to execute such 'script'
PS> where git

but after execution I see nothing, only prompt for new command.
Question: How can I find path for command in Windows 10?

A: The existing answers are helpful, but I think a more systematic discussion is helpful too.
tl;dr
where is PowerShell's built-in alias for the Where-Object cmdlet; to invoke the external where.exe program, use .exe explicitly:[1]
# Note the use of '.exe' to disambiguate the external 'where.exe' program
# from PowerShell's built-in 'where' alias (for 'Where-Object').
PS> where.exe git
C:\Program Files\Git\cmd\git.exe

where.exe, whose purpose is return the full path of an executable in the system's path (in one of the directories listed in the $env:PATH environment variable), is unrelated to cmd (the legacy command processor): it is an external executable that comes with Windows, and it can be invoked from any shell, and therefore also from PowerShell.
By contrast, cmd does have so-called internal commands that indeed can only be called from cmd, such as mklink; in fact, in cmd you can use where <name> to infer whether a given (functioning) command <name> is internal or not: if there's no output, the command is internal (or doesn't exist at all).
Alternatively, use the equivalent and more flexible PowerShell counterpart to where.exe, the Get-Command cmdlet; it returns System.Management.Automation.CommandInfo instances (or instances of derived classes), whose .Source property contains the full path for a command-info object representing an external executable:
PS> (Get-Command git).Source
C:\Program Files\Git\cmd\git.exe

Note:

*

*where.exe finds only executable files, whereas Get-Command by default looks for all command types (aliases, functions, cmdlets, ...) - see next section.

*Unlike Get-Command, where.exe also finds executables located in the current directory. Get-Command doesn't do that, because PowerShell by design, for security reasons, doesn't allow calling executables located in the current directory by name only - a path is required (e.g., .\foo).

PowerShell has different types of commands, which - in the case of name conflicts - have a predefined order of precedence to determine what type should be the effective command.
That is, if a given command name matches two or more commands, it is their type that determines which command is actually invoked.
This precedence is documented in the conceptual about_Command_Precedence help topic; in short, here is the command precedence by type in descending order (highest precedence first):

*

*aliases

*function

*cmdlets (loosely speaking: functions implemented as compiled binaries)

*external executables, including *.ps1 script files - see bottom section

An easy way to see what command types exist for a given name is to add the -All switch when calling the Get-Command cmdlet, which lists the matching commands in descending order of precedence; that is, the command that will actually be executed via the given name is listed first.
PS> Get-Command -All where

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           where -> Where-Object
Application     where.exe                                          10.0.18... C:\WINDOWS\system32\where.exe

The result shows that the built-in where alias for the Where-Object cmdlet (whose purpose is to filter pipeline input) is the effective command when you submit where, and not the desired where.exe executable.
Given that the where.exe executable file name has the .exe extension that can distinguish it from the where alias, it is simplest to invoke where.exe with the filename extension, as shown at the top.
In cases where this is not possible (e.g., on Unix-like platforms, where executables typically do not have a filename extension or if an alias shadows a function), you can use the -Type parameter to get the command of interest, and invoke it with &, the call operator:
# Invokes where.exe, as only it is of type 'Application' (external executable)
& (Get-Command -Type Application where) git

Should there be multiple external executables whose base file name is where, it is the one from the directory listed earliest in $env:PATH that will be executed - see next section.

Precedence among external executables and *.ps1 scripts:
Note:

*

*One important difference between cmd and PowerShell is that PowerShell - by design, for security reasons - does not allow you to invoke an external executable or .ps1 script located in the current directory by name only; to do so, you must use a path, in the simplest case by prepending .\ (or ./); e.g., to invoke an executable foo located in the current directory, you must use ./foo ...

*The precedence between *.ps1 scripts and other executables in effect differs by platform (Windows vs. Unix-like platforms), as detailed below.

*The following discussion assumes that a given command name isn't shadowed by higher-precedence command types, such as aliases, and resolves to an external executable or *.ps1 script.
Precedence rules:

*

*When a command name resolves to potentially multiple external executables or *.ps1 scripts via the directories listed in the $env:PATH environment variable, the executable / script located in the directory that is listed earliest is invoked.

*If, in that earliest directory:

*

*the given name exactly matches an executable file name (e.g., where.exe) or script (e.g., foo.ps1), there is no ambiguity, and that executable / script is invoked.

*the given name doesn't include a filename extension (e.g., foo), multiple executables can match (via implied filename extensions), and the one to actually invoke is determined as follows:

*

*On Windows:

*

*PowerShell gives precedence to its own scripts, so if a .ps1 script is present, it is the effective command; note that .ps1 scripts are executed in-process, unlike external executables, which invariably run in a child process.

*Otherwise, it is the executable file whose filename extension is listed earliest among the executable extensions in the $env:PATHEXT environment variable; e.g., foo.bat takes precedence over foo.vbs, because, .BAT is listed before .VBS.

*On Unix-like platforms (Linux, macOS):

*

*Unix-like platforms determine executability solely via permissions, not via filename extensions, and executables in the vast majority of cases have no filename extension (e.g., just git, not git.exe as on Windows).

*From PowerShell's perspective, the only filename extension that matters with respect to executability on Unix is .ps1, because it is PowerShell itself that considers such files executable - irrespective of whether they are from the system's perspective.

*Therefore, in PowerShell on Unix, .ps1 is the only implied filename extension that can be omitted on invocation; e.g., you can invoke a script file foo.ps1 as just foo (assuming it is in the system's path).

*If you have an external executable whose file name doesn't have a filename extension - as is typical - and a .ps1 file with the same base name in the same directory, it is the external executable that takes precedence - the reason is that the extension-less name is an exact match for the extension-less executable file name.

*

*E.g., if external executable foo and foo.ps1 are located in the same (earliest) directory, submitting foo invokes the external executable, not foo.ps1 - unlike on Windows.
Note:

*

*The precedence rules among multiple executables in a given directory also apply when using an explicit path (without a filename extension); e.g., invoking ./foo decides the precedence among multiple executables in the current directory whose base name is foo as described above.

*Placing .ps1 scripts in a directory listed in $env:PATH and invoking them by (base) name only isn't all that common, although it is worth considering as an alternative to putting potentially many functions in one's $PROFILE file.

*

*Unfortunately, the UX is poor on Linux, where, due to its case-sensitive file system, you must specify the (base) file name case-exactly on invocation, whereas PowerShell command invocation is otherwise case-insensitive; e.g., if the actual file name is Get-Foo.ps1, only Get-Foo works for invocation, not get-foo.

[1] As for why a call such as where git - i.e. mistaken use of Where-Object - doesn't produce output: The call is equivalent to Where-Object git, which is in turn equivalent to Where-Object { $_.git }, which, in the absence of pipeline input to the cmdlet by definition never produces output.

A: In Powershell, where is an alias for where-object, which is used to filter collections.
Get-Alias -Name where
CommandType     Name                          Version    Source
-----------     ----                          -------    ------
Alias           where -> Where-Object

In Cmd, where displays location of files.
The Powershell version of Cmd's where is Get-Command
Get-Command -Name git
CommandType     Name                        Version    Source
-----------     ----                        -------    ------
Application     git.exe                     2.20.1.1   C:\Program Files\Git\cmd\git.exe

A: Use:
$(get-command <command name>).path

or
$(get-command <command name>).source

or in your case
$(get-command git).path

or
$(get-command git).source

get-command gets cmdlet info and there is a source parameter so if you use get-command as a variable, you can access the path of the cmdlet.
You can also use the cmd version in powershell with
cmd /c "where git"


text:
Q: Multiple substitution with SymPy in Julia I am using SymPy in Julia. I have the following code:
using SymPy

# Define variables and function

alpha_m, alpha_r, cm, cr phi = Sym("alpha_m", "alpha_r", "cm", "cr", "phi");

X = 1+(alpha_r/alpha_m)^(1/(1-phi))*(cr/cm)^(phi/(1-phi));

Now, I want to replace several expressions by other variables:
# New definitions

m, r = Sym("m","r");

I try three methods, but only the last one works, which is writing the sub for each individual redefinition:
# Multiple replacement

toin = (alpha_m, alpha_r);
toout = (m/(m+r),r/(m+r));

X = subs(X,zip(toin,toout)) # NOT WORKING

X = subs(X,[alpha_m,m/(m+r),alpha_r,r/(m+r)]); # NOT WORKING

X = subs(X,alpha_m,m/(m+r))
X = subs(X,alpha_r,r/(m+r)) # WORKING

Is there any way to do multiple substitutions at once, like I try in the first two methods?

A: You can use the first construct with splatting:

X = subs(X,zip(toin,toout)...)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deleting multiple rows from Kendo grid makes the page become unresponsive I have a grid with checkbox for every row, I tried grid.removeRow, dataSource.remove(item), splice() everything does not work for me.
The grid just consists of 4 columns included checkbox, and the records are just around 1.6k. The page just become unresponsive when I click the delete button to delete based of the checkbox of each row.
Here is my code:
var raw = $scope.DataSource.data();
var length = raw.length;
var item, i;
for (i = length - 1; i >= 0; i--) {
     item = raw[i];
     if(!item.IsSelect) //IsSelect here is the boolean variable
        $scope.DataSource.remove(item);
}

Any idea?

A: Try to remove the items outside a for loop. There is probably some redrawing after each removal, thus freezing the browser

A: Well, i also have done same thing, and i must say the Kendo Grid for Angular 2 is really poor performance wise.
Also, i did that with angular 2 grid, cant say that it will help you with Angular1.
Edit: i am using splice to remove selected row data from Grid:
this.array1.push(this.checkedArrayData[i]);
this.array2.splice(this.checkedArrayData[i], 1);

//reassigns the array datasource to grid
this.array2 = this.array2.slice();


text:
Q: segue from two different viewControllers osx swift I'm writing an app that uses tab view controller (each tab has own view controller) and I want to display results of calculations in two tables in the same table view. I connected that table view to both viewControllers with sagues. The problem I have is every time I open table view declaration of arrays makes both of them empty and only one table displays like I want it to. Is there a way to resolve that?
Code from my Table View Controller
import Cocoa

class TableView: NSViewController, NSTableViewDataSource, NSTableViewDelegate {

    @IBOutlet var ResultsTable: NSTableView!

    @IBOutlet var ResultTableInvers: NSTableView!

    var rekord : [(fi1: String, lambda1: String, fi2: String, lambda2: String, A12: String, A21: String, s: String)] = []
    var rekordInverse : [(fi1: String, lambda1: String, fi2: String, lambda2: String, A12: String, A21: String, s: String)] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        println(rekord)
        self.ResultsTable.reloadData()
        self.ResultTableInvers.reloadData()
        // Do view setup here.
    }

    @IBAction func powrot(sender: NSButton) {

        dismissViewController(self)
    }

    func numberOfRowsInTableView(tableView: NSTableView) -> Int {
        if(tableView == self.ResultsTable){
            return self.rekord.count
        } else { return self.rekordInverse.count}

    }

    func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
         var newString = ""
          var myArray : [(fi1: String, lambda1: String, fi2: String, lambda2: String, A12: String, A21: String, s: String)] = []
        if(tableView == self.ResultsTable){
        myArray = rekord
        } else { myArray = rekordInverse}

        switch (tableColumn!.identifier) {

        case "fi1":
            newString = myArray[row].fi1

        case "lambda1":
            newString = myArray[row].lambda1

        default: newString = "12"

        }

            return newString
    }

}


text:
Q: Pandas Latitude-Longitude: Calculate the distance between two points and select the nearest one I have a dataframe with 15k rows with coordinates and the names of the locations (mainly businesses)

spot
lat1
l1
place
lat2
lon2

1
41,1808128356934
-8,53291034698486
A
41.146749
-8.613889

1
41,1808128356934
-8,53291034698486
B
41.146105
-8.609868

2
41,1491432189941
-8,61034202575684
A
41.146749
-8.613889

2
41,1491432189941
-8,61034202575684
B
41.146105
-8.609868

I've been trying to perform a subtraction between both coordinates to find the distance (in meters) and then select only the the spot and place with less distance between them.
This is the code I was trying to use:
df['X_diff'] = df['lon1'] - df['lon2']
df['Y_diff'] = df['lat1'] - df['lat2']
df['dist'] = np.linalg.norm(df[['X_diff', 'Y_diff']], axis=1)

I also realized that the type of coordinates were different.
spot     object
lat1     object
lon1     object
place    object
lat2     float64
lon2     float64
dtype: object

How do I find the distance and select only the nearest one?

A: Your lat1 and lon1 are strings. Maybe you want to replace , with . and convert to float before you calculate the norm:
df[['lat1', 'lon1']] = df[['lat1','lon1']].apply(lambda x: pd.to_numeric(x.str.replace(',','.')) )


text:
Q: How can I change DateTime to am and pm instead of AM/PM for C# Here is the code I am using below
    string Time = DateTime.Now.ToString("MM/dd/yy h:mm tt");

The above tt will give me AM or PM but I need am or pm. Is there a different way to write this to get am or pm in C#? I have tried TT,t leaving it out completely but all end in failure.

A: DateTime.Now.ToString("MM/dd/yy h:mm tt").ToLower();


text:
Q: EF Core - insert record sequentially in DB without identity on PK Disclaimer: This question is regarding "modernization" of almost 17 years old system. ORM that was used 17 years ago required that PK's don't use Identity.
I know how bad it is, and I can't change anything regarding this.
So I have (simplified) following table in database:
CREATE TABLE [dbo].[KlantDocument](
    [OID] [bigint] NOT NULL,
    [Datum] [datetime] NOT NULL,
    [Naam] [varchar](150) NOT NULL,
    [Uniek] [varchar](50) NOT NULL,
    [DocumentSoort] [varchar](50) NULL,
 CONSTRAINT [PK_KlantDocument] PRIMARY KEY CLUSTERED
(
    [OID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[KlantDocument] CHECK CONSTRAINT [FK_KlantDocument_Klant]
GO

As you can see, table doesn't have Identity set on PK, so it has to be inserted manually.
Project is being rebuilt in Web Api .Net Core 5, that is going to do all of the CRUD operations.
It is using EF Core as ORM, and it is agreed that Unit of Work pattern is going to be used here (please do keep reading, UoW is not issue here).
For those curious or for what it's worth, you can take a look at it here (https://pastebin.com/58bSDkUZ) ( this is by no means full UoW, just partially and without comments).
UPDATE: Caller Controller Action:
[HttpPost]
        [Route("UploadClientDocuments")]
        public async Task<IActionResult> UploadClientDocuments([FromForm] ClientDocumentViewModel model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelStateExtensions.GetErrorMessage(ModelState));

            var dto = new ClientDocumentUploadDto
            {
                DocumentTypeId = model.DocumentTypeId,
                ClientId = model.ClientId,
                FileData = await model.File.GetBytes(),
                FileName = model.File.FileName, // I need this property as well, since I have only byte array in my "services" project
            };

            var result = await _documentsService.AddClientDocument(dto);
            return result ? Ok() : StatusCode(500);
        }

When I am inserting record I am doing it like so:
// Called by POST method multiple times at once
public async Task<bool> AddClientDocument(ClientDocumentUploadDto dto)
{
    try
    {
        var doc = new KlantDocument
        {
        /* All of the logic below to fetch next id will be executed before any of the saves happen, thus we get "Duplicate key" exception. */
            // 1st try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderByDescending(s => s.Oid).First().Oid + 1,
            // 2nd try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderBy(s => s.Oid).Last().Oid + 1,
            // 3rd try to fetch next id
            // Oid = await _uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Select(s => s.Oid).LastAsync() + 1,
            // 4th try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Select(s => s.Oid).Last() + 1,
            // 5th try to fetch next id
            // Oid = (_uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Max(s => s.Oid) + 1),
            Naam = dto.FileName,
            DocumentSoort = dto.DocumentTypeId,
            Datum = DateTime.Now,
            Uniek = Guid.NewGuid() + "." + dto.FileName.GetExtension()
        };

        _uow.Context.Set<KlantDocument>().Add(doc); // Does not work
        _uow.Commit();
    }
    catch (Exception e)
    {
        _logger.Error(e);
        return false;
    }
}

I get "Duplicate key" exception because 2 of the records are overlapping when inserting.
I have tried to wrap it into the transaction like so:
_uow.ExecuteInTransaction(() => {
        var doc = new KlantDocument
        {
        /* All of the logic below to fetch next id will be executed before any of the saves happen, thus we get "Duplicate key" exception. */
            // 1st try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderByDescending(s => s.Oid).First().Oid + 1,
            // 2nd try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderBy(s => s.Oid).Last().Oid + 1,
            // 3rd try to fetch next id
            // Oid = await _uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Select(s => s.Oid).LastAsync() + 1,
            // 4th try to fetch next id
            // Oid = _uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Select(s => s.Oid).Last() + 1,
            // 5th try to fetch next id
            // Oid = (_uow.Query<KlantDocument>().OrderBy(s => s.Oid).AsNoTracking().Max(s => s.Oid) + 1),
            Naam = dto.FileName,
            DocumentSoort = dto.DocumentTypeId,
            Datum = DateTime.Now,
            Uniek = Guid.NewGuid() + "." + dto.FileName.GetExtension()
        };

        _uow.Context.Set<KlantDocument>().Add(doc); // Does not work
        _uow.Commit();
});

and it does not work. I still get "Duplicate key" exception.
From what I know, shouldn't EF by default lock database until transaction is complete?
I tried to manually write insert SQL like so:
using (var context = _uow.Context)
{
    using (var dbContextTransaction = context.Database.BeginTransaction())
    {
        try
        {
            // VALUES ((SELECT MAX(OID) + 1 FROM KlantDocument), -- tried this also, but was not yielding results
            var commandText = @"INSERT INTO KlantDocument
            (
             OID
            ,Datum
            ,Naam
            ,Uniek
            ,DocumentSoort
            )
            VALUES (
                    (SELECT TOP(1) (OID + 1) FROM KlantDocument ORDER BY OID DESC),
                    @Datum,
                    @Naam,
                    @Uniek,
                    @DocumentSoort
            )";
            var datum = new SqlParameter("@Datum", DateTime.Now);
            var naam = new SqlParameter("@Naam", dto.FileName);
            var uniek = new SqlParameter("@Uniek", Guid.NewGuid() + "." + dto.FileName.GetExtension());
            var documentSoort = new SqlParameter("@DocumentSoort", dto.DocumentTypeId ?? "OrderContents");

            context.Database.ExecuteSqlRaw(commandText, datum, naam, uniek, documentSoort);
            dbContextTransaction.Commit();
        }
        catch (Exception e)
        {
            dbContextTransaction.Rollback();
            return false;
        }
    }
}

Same thing.
I did a lot research to try to tackle this issue:

*

*.NET Core - ExecuteSqlRaw - last inserted id? - solutions either don't work, or work only with identity columns

*I got idea to use SQL OUTPUT variable, but issue is that it's really hard or even impossible to achieve, feels hacky and overall if managed, there is no guarantee that it will work. As seen here: SQL Server Output Clause into a scalar variable and here How can I assign inserted output value to a variable in sql server?
As noted above, ORM at the time did some magic where it did sequentially insert records in database and I would like to keep it that way.
Is there any way that I can achieve sequential insert when dealing with given scenario?

A: Ok, I have figured this out finally.
What I tried that did not work:
1.) IsolationLevel as proposed by @bluedot:
  public enum IsolationLevel
  {
    Unspecified = -1, // 0xFFFFFFFF
    Chaos = 16, // 0x00000010
    ReadUncommitted = 256, // 0x00000100
    ReadCommitted = 4096, // 0x00001000
    RepeatableRead = 65536, // 0x00010000
    Serializable = 1048576, // 0x00100000
    Snapshot = 16777216, // 0x01000000
  }

*

*Unspecified // Failed half of them
Violation of PRIMARY KEY constraint 'PK_KlantDocument'. Cannot insert duplicate key in object 'dbo.KlantDocument'. The duplicate key value is (1652).

*Chaos // Failed all of them
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Private.CoreLib.dll

*ReadUncommitted // Failed half of them
Violation of PRIMARY KEY constraint 'PK_KlantDocument'. Cannot insert duplicate key in object 'dbo.KlantDocument'. The duplicate key value is (1659).

*ReadCommitted // Failed half of them
Violation of PRIMARY KEY constraint 'PK_KlantDocument'. Cannot insert duplicate key in object 'dbo.KlantDocument'. The duplicate key value is (1664).

*RepeatableRead // Failed half of them
Violation of PRIMARY KEY constraint 'PK_KlantDocument'. Cannot insert duplicate key in object 'dbo.KlantDocument'. The duplicate key value is (1626).

*Serializable // Failed 3 of them
Transaction (Process ID 66) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

*Snapshot // Failed all of them
Snapshot isolation transaction failed accessing database 'Test' because snapshot isolation is not allowed in this database. Use ALTER DATABASE to allow snapshot isolation.
2.) Sequence in DbContext:
Thanks to a really awesome human being from EF Core team, Roji. I asked this on GitHub as well (https://github.com/dotnet/efcore/issues/26480) and he actually pushed me in right direction.
I followed this documentation: https://learn.microsoft.com/en-us/ef/core/modeling/sequences, I was ecstatic to find this could actually be "automated" (read, I could just add them to context and commit changes using my UoW) and I won't be having the need to write the SQL queries when inserting data all the time.
Thus I created following code to setup the sequence in DbContext and to run it using migrations.
My OnModelCreating method changes looked like so:
        modelBuilder.HasSequence<long>("KlantDocumentSeq")
            .StartsAt(2000)
            .IncrementsBy(1)
            .HasMin(2000);

        modelBuilder.Entity<KlantDocument>()
            .Property(o => o.Oid)
            .HasDefaultValueSql("NEXT VALUE FOR KlantDocumentSeq");

But since my Oid (PK) is not nullable, whenever I tried to insert my document like so:
            var doc = new KlantDocument
            {
                Naam = dto.FileName,
                DocumentSoort = dto.DocumentTypeId,
                Datum = DateTime.Now,
                Uniek = Guid.NewGuid() + "." + dto.FileName.GetExtension()
            };
            _uow.Context.Set<KlantDocument>().Add(doc);
            _uow.Commit();

It produced this SQL (beautified for visibility purposes):
SET NOCOUNT ON;
INSERT INTO [KlantDocument] ([OID], [Datum], [DocumentSoort], [Naam], [Uniek])
VALUES (0, '2021-10-29 14:34:06.603', NULL, 'sample 1 - Copy (19).pdf', '56311d00-4d7c-497c-a53e-92330f9f78d4.pdf');

And naturally I got exception:
InnerException = {"Violation of PRIMARY KEY constraint 'PK_KlantDocument'. Cannot insert duplicate key in object 'dbo.KlantDocument'. The duplicate key value is (0).\r\nThe statement has been terminated."}

Since it is default value of long (non-nullable) OID value to 0, when creating doc variable, as it is not nullable.
NOTE: Be very very cautios if you are using this approach even if you can. It will alter all of your Stored procedures where this OID is used.
In my case it created all of these:
 SELECT * FROM sys.default_constraints
 WHERE
    name like '%DF__ArtikelDocu__OID__34E9A0B9%' OR
    name like '%DF__KlantDocume__OID__33F57C80%' OR
    name like '%DF__OrderDocume__OID__33015847%'

and I had to manually ALTER each table to drop these constrains.
What worked:
Again, thanks to a really awesome human being from EF Core team, Roji, I managed to implement this to work.
Same as above, I created change in DbContext, OnModelCreating method:
        modelBuilder.HasSequence<long>("KlantDocumentSeq")
            .StartsAt(2000)
            .IncrementsBy(1)
            .HasMin(2000);

Added migration that produced this code:
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateSequence(
            name: "KlantDocumentSeq",
            startValue: 2000L,
            minValue: 2000L);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropSequence(
            name: "KlantDocumentSeq");
    }

Updated database, and for DB work that was it.
Final change came into my method where I had to replace notorious code block
((SELECT MAX(OID) + 1 FROM KlantDocument) or (SELECT TOP(1) (OID + 1) FROM KlantDocument ORDER BY OID DESC)
with
NEXT VALUE FOR KlantDocumentSeq

and it worked.
Full code of my method is here:
using (var context = _uow.Context)
{
    using (var dbContextTransaction = context.Database.BeginTransaction())
    {
        try
        {
            var commandText = @"INSERT INTO KlantDocument
            (
             OID
            ,Datum
            ,Naam
            ,Uniek
            ,DocumentSoort
            )
            VALUES (
                    NEXT VALUE FOR KlantDocumentSeq,
                    @Datum,
                    @Naam,
                    @Uniek,
                    @DocumentSoort
            )";
            var datum = new SqlParameter("@Datum", DateTime.Now);
            var naam = new SqlParameter("@Naam", dto.FileName);
            var uniek = new SqlParameter("@Uniek", Guid.NewGuid() + "." + dto.FileName.GetExtension());
            var documentSoort = new SqlParameter("@DocumentSoort", dto.DocumentTypeId ?? "OrderContents");

            context.Database.ExecuteSqlRaw(commandText, datum, naam, uniek, documentSoort);
            dbContextTransaction.Commit();
        }
        catch (Exception e)
        {
            dbContextTransaction.Rollback();
            return false;
        }
    }
}

and SQL it generates is:
INSERT INTO KlantDocument
(
 OID
,Datum
,Naam
,Uniek
,DocumentSoort
)
VALUES (
        NEXT VALUE FOR KlantDocumentSeq,
        '2021-10-29 15:34:43.943',
        'sample 1 - Copy (13).pdf',
        'd4419c6c-dff9-431c-a7ed-6db54407051d.pdf',
        'OrderContents'
)


text:
Q: Heroku Scheduled Task that uses Net::HTTP library to make HTTP GET request - Ruby on Rails I'm trying to use a Heroku Scheduled Task that makes an HTTP GET to a particular controller's action. Here's what the task looks like:
require 'net/http'

desc "This task is called by the Heroku scheduler add-on"
task :send_notifications => :environment do
    Net::HTTP.get("http://testapp.com", "/test/send_notifications")
end

Upon running:
heroku rake send_notifications

I get the following error:
rake aborted!
getaddrinfo: Name or service not known
/app/lib/tasks/scheduler.rake:5:in `block in <top (required)>'

Any thoughts?
Thanks in advance

A: A clean solution might be to put the request logic inside a class method of a special Class you create anywhere in your Rails app directory.
# app/workers/request_worker.rb
class RequestWorker
  # Request X from Y
  def self.retrieve_testapp
    # Do anything nescessary to build and execute the request in here
  end
end

You could then schedule the request with the Heroku Scheduler addon by way of Rails runner (which let's you execute any command in the context of your Rails application.)
rails runner RequestWorker.retrieve_testapp

To actually execute an HTTP Request from Ruby / Rails there are a lot of useful gems. Nice ones are Excon and HTTP Client.

A: I decided to use the 'HTTParty' library which has taken care of it:
response = HTTParty.get('http://testapp.com/test/send_notifications')


text:
Q: how to deselect some part of data of object to not appear in response In my my mern project when the user do login in the response my server sends him the response of with hash password and reset password token is there any way to fix it

Here is my user model
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const crypto = require("crypto")

const jwt = require("jsonwebtoken");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "please Ente the your name"],
  },
  email: {
    type: String,
    required: [true, "Please Enter the email"],
    unique: [true],
    validate: [validator.isEmail, "Please Enter a valid email"],
  },
  password: {
    type: String,
    required: true,
    minlength: [8, "Passwaord must be more that 8 characters"],
    select: false,
  },
  avatar: {
    public_id: {
      type: String,
      required: true,
    },
    url: {
      type: String,
      required: true,
    },
  },
  role: {
    type: String,
    default: "user",
  },
  resetPasswordToken: String,
  resetPasswordExpire: Date,

  createdAt: {
    type: Date,
    default: Date.now,
  },
});

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }

  this.password = await bcrypt.hash(this.password, 10);
});

userSchema.methods.comparePassword = async function (password) {
  return await bcrypt.compare(password, this.password);
};

userSchema.methods.getJWTToken = function () {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE,
  });
};

// compare password

// userSchema.methods.comparePassword = async function(enterPass){
//     return await bcyrypt.compare(enterPass,this.password)
// }

// Reset Password

userSchema.methods.getResetPasswordToken = function () {
  // Generating Token
  const resetToken = crypto.randomBytes(20).toString("hex");

  // Hashing and adding resetPasswordToken to userSchema
  this.resetPasswordToken = crypto
    .createHash("sha256")
    .update(resetToken)
    .digest("hex");

  this.resetPasswordExpire = Date.now() + 15 * 60 * 1000;

  return resetToken;
};

module.exports = mongoose.model("User", userSchema);

as suggest I have used already select false and also I select reset password token I am getting error when I try to return anything except user


text:
Q: Tengo varias facturas que realizo un json desde SQL 2017, pero tengo un problema en la estructura Genero mi JSON desde SQL 2017 la cual genera esta estructura tomado desde los una tabla.
"detalle": [{
        "numero": "1",
        "codigo": [{
            "tipo": "04",
            "codigo": "593"
        }, {
            "tipo": "04",
            "codigo": "12"
        }],
        "cantidad": "1.000",
        "unidad_medida": "Unid",
        "detalle": "Tour Manglar",
        "precio_unitario": "65435.00000",
        "monto_total": "65435.00000",
        "subtotal": "65435.00000",
        "impuestos": [{
            "codigo": "",
            "tarifa": "0.00",
            "monto": "0.00000"
        }, {
            "codigo": "01",
            "tarifa": "13.00",
            "monto": "73.97000"
        }, {}],
        "montototallinea": "65435.00000"
    }
--------------------------------
pero me gustaria tenerlo asi

"detalle": [{
        "numero": "1",
        "codigo": [{
            "tipo": "04",
            "codigo": "593"
        }],
        "cantidad": "1.000",
        "unidad_medida": "Unid",
        "detalle": "Tour Manglar",
        "precio_unitario": "65435.00000",
        "monto_total": "65435.00000",
        "subtotal": "65435.00000",
        "impuestos": [{
            "codigo": "",
            "tarifa": "0.00",
            "monto": "0.00000"
             }],
        "montototallinea": "65435.00000"
    }


text:
Q: How to get current domain name in ASP.NET I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;

My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com

I want to get somedomainname.com
Please give me an idea how to get the current domain name.

A: Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.

A: I use it like this in asp.net core 3.1
 var url =Request.Scheme+"://"+ Request.Host.Value;

A: www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;

if (host.StartsWith("www."))
    return host.Substring(4);
else
    return host;

Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;

int lastDot = host.LastIndexOf('.');

int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');

if (secondToLastDot > -1)
    return host.Substring(secondToLastDot + 1);
else
    return host;

Getting the port is just like other people have said.

A: Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.

A: You can try the following code :
 Request.Url.Host +
    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)

A: Try getting the "left part" of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.

A: HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port

A: the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for

A: You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host

A: Here is a quick easy way to just get the name of the url.
            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

A: To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";

A: string domainName = HttpContext.Request.Host.Value;
this line should solve it

A: Try this:
@Request.Url.GetLeftPart(UriPartial.Authority)


text:
Q: What does the path "//" mean? I just found the direcory // on my machine and now i am wondering what it means.
user@dev:~$ cd /
user@dev:/$ pwd
/
user@dev:/$ cd //
user@dev://$ pwd
//

It is obvously the root directory, but when and why do i use the double slash instead of the single slash?
Is it related to the escaped path strings which i use while programming?
For example:
string path = "//home//user//foo.file"

I also tried it with zsh but it changes to the usual root directory /. So I think its bash specific.

A: This is part of the specification for Pathname Resolution:

A pathname consisting of a single <slash> shall resolve to the root directory of the process. A null pathname shall not be successfully resolved. If a pathname begins with two successive <slash> characters, the first component following the leading <slash> characters may be interpreted in an implementation-defined manner, although more than two leading <slash> characters shall be treated as a single <slash> character.

So your shell is just following the specification and leaving // alone as it might be implementationally defined as something other than /.


text:
Q: ES6 modules in Node v4.4.2 I recently came back to Node.js after my brief exploration of front end, and have found that IO.js has merged back with Node.js. So I downloaded Node.js v4.4.2 and I  wanted to mess around with ES6 modules, which I was doing before my aformentioned hiatus, I seem unable to use them.
I went to the Node.js website and found how to enable them (--harmony_modules), and using that flag, I still got the following error:
main.js:1
(function (exports, require, module, __filename, __dirname) { import * from "lib/Tile"
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:414:25)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

Am I doing something wrong here, or is there a bug in the Module Implementation?
The involved files are posted below:
main.js:
import * from "lib/Tile"

console.log(Tile)

lib/Tile.js
export class Tile {
    constructor(data = {}) {
        this.data = data
    }
}


text:
Q: How to calculate the inverse agm(1,x)? If we define the following function $$agm(1,x) =y$$ and its inverse, $$agm^{-1}(y)=(1,x)$$ is it possible to calculate $agm^-1(y)$. Where $agm(x)$ is the sequence $$a_{n+1}=\frac{a_n+b_n}{2}$$ and $$b_{n+1}=\sqrt(a_nb_n)$$I know how to reverse the iterations of $agm(x)$ using $$a_{n-1}=a_n-\sqrt(a_n^2-b_n^2)$$  and that  $$b_{n-1}=a_n+\sqrt(a_n^2-b_n^2)$$ However for those to work I would need two values, how can I calculate $x$ or $(1,x)$ using $y$.

A: We have
$$\text{agm}(1,x)=\frac{\pi  (1+x)}{4 K\left(\left(\frac{1-x}{1+x}\right)^2\right)}$$ Suing series expansions for large values of $x$, we have
$$\frac{\pi  (1+x)}{4 K\left(\left(\frac{1-x}{1+x}\right)^2\right)}=\frac{\pi  x}{4\log (2)+2 \log \left({x}\right)}+\frac{1-\pi  \log
   \left({4 x}\right)}{8 x \log ^2\left({4
   x}\right)}+O\left(\frac{1}{x^3}\right)$$ So, if we consider the first term only and solve for $x$ we have, as an approximation,
$$x=-\frac{2\,k }{\pi }\,W_{-1}\left(-\frac{\pi }{8\,k}\right)\qquad \text{where} \qquad k=\text{agm}(1,x)\tag 1$$ where appears the second branch of Lambert function.
To check how good or bad is this approximation, give $x$ a value, compute $\text{agm}(1,x)$ and apply $(1)$
$$\left(
\begin{array}{ccc}
 x_{given} & \text{agm}(1,x) & x_{calc} \\
 5 & 2.60401 & 4.94933 \\
 10 & 4.25041 & 9.97492 \\
 15 & 5.74991 & 14.9833 \\
 20 & 7.16581 & 19.9875 \\
 25 & 8.52468 & 24.9900 \\
 30 & 9.84096 & 29.9917 \\
 35 & 11.1236 & 34.9929 \\
 40 & 12.3787 & 39.9937 \\
 45 & 13.6105 & 44.9944 \\
 50 & 14.8223 & 49.9950 \\
 55 & 16.0167 & 54.9955 \\
 60 & 17.1955 & 59.9958 \\
 65 & 18.3605 & 64.9962 \\
 70 & 19.5129 & 69.9964 \\
 75 & 20.6539 & 74.9967 \\
 80 & 21.7844 & 79.9969 \\
 85 & 22.9053 & 84.9971 \\
 90 & 24.0173 & 89.9972 \\
 95 & 25.1209 & 94.9974 \\
 100 & 26.2167 & 99.9975
\end{array}
\right)$$
If $x$ is mall, using simple Padé approximants, we have
$$\frac{\pi  (1+x)}{4 K\left(\left(\frac{1-x}{1+x}\right)^2\right)}=\frac{1+\frac{29 }{24}(x-1)+\frac{61}{192} (x-1)^2}{1+\frac{17
  }{24} (x-1)+\frac{5}{192} (x-1)^2}$$ leading to
$$x=\frac{55-63k-4 \sqrt{229 k^2-194 k+109}}{5 k-61}\qquad \text{where} \qquad k=\text{agm}(1,x)\tag 2$$
$$\left(
\begin{array}{ccc}
x_{given} & \text{agm}(1,x) & x_{calc} \\
 1.0 & 1.00000 & 1.00000 \\
 1.5 & 1.23734 & 1.50004 \\
 2.0 & 1.45679 & 2.00079 \\
 2.5 & 1.66450 & 2.50377 \\
 3.0 & 1.86362 & 3.01071 \\
 3.5 & 2.05604 & 3.52325 \\
 4.0 & 2.24303 & 4.04282 \\
 4.5 & 2.42546 & 4.57073 \\
 5.0 & 2.60401 & 5.10818
\end{array}
\right)$$

A: From standard facts, such as in the Wikipedia article Arithmetic-geometric mean, $\, \textrm{agm}(1,k) = \frac{\pi/2}{K(k')}\,$ where $\,k\,$ is the modulus, $\,k'=\sqrt{1-k^2}\,$ is the complementary modulus, and $\,K(k)\,$ is the complete elliptic integral of the first kind. In order to find $\,\textrm{agm}^{-1}\,$ you need to find the inverse of $\,K().\,$ This involves the Jacobi amplitude function described in the Jacobi elliptic functions article.
As a practical matter, I suggest restricting to $\,0<k<1\,$ although there is analytic continuation, but you may run into branch cuts or worse.

A: $$x_{n+1}=x_n-\frac{2x_n(1+x_n)(agm(1,x_n)-y)}{agm(1,x_n)(1+x_n)(1-\frac{4}{(1+x_n)^2}\sum_{k=0}^{\infty}2^{k-1}c_k^2)-x_n}$$ and $c_k^2=a_{k+1}^2-b_{k+1}^2$ using the AGM iteration, $\lim_{n\to \infty}$ $x_n=agm^{-1}(y)$. For $x_0$ use $\frac{\pi}{2\ln(\frac{4}{x})}$ for $0<y<1$ and for larger values use $2x$ as $x_0$. Its also convergent for complex numbers.


text:
Q: nav bar to stay on top after reaching top of page I'm trying to emulate this http://jsfiddle.net/adamb/F4BmP/
in the "result" section you see how the nav bar remains at top of the page as soon as it reaches top of the page when scrolled. I used the same code but my nav bar doesn't stay on top; it continues scrolling. I don't know what I'm doing wrong here.
Here is my code:
html
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
    <head>
        <link rel="shortcut icon" href=".\favicon.ico">
        <title>rentPRO</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            var num = 210;

            $(window).bind('scroll', function () {
                if ($(window).scrollTop() > num) {
                        $('#top_menu').addClass('fixed');
                } else {
                        $('#top_menu').removeClass('fixed');
                }
            });
        </script>
    </head>

css
#header {
    background-image: url("https://lh6.googleusercontent.com/-4epq8pWSUKQ/VNX4lGi_GrI/AAAAAAAAAIo/9gDg5CubDO8/w1044-h201-no/header%2Bfinal1.jpg");
        background-size: 100% 100%;
    width: 1075px;
        height: 200px;
    margin: 0 auto;
    position: relative;
    }

#top_menu {
    display:block;
    position: absolute;
    top: 210px;
    left: 136px;
    border-radius: 4px;
    border-width: 1px 1px 1px;
    border-style:solid;
    background-color: white;
    font-family: 'Lato', sans-serif;
    font-size: 14.85px;
    height: 40px;
    width: 1075px;
    margin: 0 auto;
    border-color: #A4A4A4;
    }
.fixed {
    position: fixed;
    top: 0;
    }

A: Changing 'top_menu' to a class instead of an ID worked for me.
Working jsfiddle.
HTML:  div class="top_menu"
CSS:  .top_menu
JQuery:
$(document).ready(function(){
    $(window).bind('scroll', function () {
         if ($(window).scrollTop() > num) {
              $('.top_menu').addClass('fixed');
         } else {
              $('.top_menu').removeClass('fixed');
         }
    });
});

A: Try wrapping your Javascript with the document ready function. It should look like this:
$(document).ready(function(){

  var num = 210;

  $(window).bind('scroll', function () {
    if ($(window).scrollTop() > num) {
      $('.top_menu').addClass('fixed');
    } else {
      $('.top_menu').removeClass('fixed');
    }
  });
});


text:
Q: Best way to migrate single project from Jira 5.0 to Jira 8? I want to move a single project from a Jira 5.0 instance to a new Jira 8.0 instance being already used for other projects - so the process must not bring in configurations, workflows, etc. nor should alter existing projects.
I'm only interested in importing issues and related data:

*

*title, description, etc (obviously)

*attachments (images, files, whatever)

*issue links

*issue type (with mapping to new types in case they don't match)

*... (other properties that I'm forgetting right now)

I've just started searching for the topic and already found several options - and it's not clear if they're all available to be, mosly due to the starting Jira version, they are:

*

*Export to CSV and import to CSV

*Export to XML

*Import from JSON (though I've yet to find a JSON export)

*Rest API

*Import project from backup

*... and surely others

Of course I'd like the most complete yet less error-prone method, though if resorting to the REST API will be the only way to be sure to import all I want, I'm ready to write a script / program.
So, what should I choose?
P.S.: I'm not sure if this fits this community, is there a more proper one?

A: The easiest way is to get csv export, get all attachments (jira_home/data/attachments). Then copy attachments to a new instance to jira_home/import. You'll need to edit export file to match names and paths of your attachments in order to import them successfully.
And last step is import csv to your Jira 8 instance.
I suggest trying this on dev/stage environment first because there are many small details that can affect import.
Some useful data is here:
https://confluence.atlassian.com/adminjiraserver/importing-data-from-csv-938847533.html


text:
Q: Red dead redemption 2 strange horse problem I don't know if anyone else have had this problem. Horses just keep appearing for Arthur. First in stable all of a sudden there was extra horse. Then I had all horses in stable when I saved the game. When I load the game later there was horse next to Arthur. Map said Arthur's horse, but all previous horses were in the stable. Just little weird. Just some bug?

A: Note that when you load a save, you're not resuming the game from when you saved. By that I mean that Arthur is always shown to be doing something such as leaning against a post, sitting on a rock, ...
Additionally, the game sometimes automates a few things for you. Most notable, it auto-equips additional weapons when you leave your horse when your current mission will contain a shootout (you can use this to predict ambushes), or putting your horse in an easily accessible location (nearby, near allies' horses, ...)
It's thus not farfetched to assume that the game intentionally gives you one of your horses when loading in, as it assume  that you might need your horse.

First in stable all of a sudden there was extra horse.

If you're referring to the first stable visit (mission with Hosea), there is a second horse but it didn't come out of nowhere.
During the game, the first horse you receive is in the Adler ranch (where you rescue Sadie). This is your horse, but when you start the Hosea stable mission, Hosea gives you a second horse (and tells you to sell it).
When you enter the stables, your first horse is stabled there, and you ride in on the second horse.

Map said Arthur's horse, but all previous horses were in the stable. Just little weird. Just some bug?

This could be a horse you've ridden which became a temporary horse. Actual ownership of a horse happens by moving your saddle, but when riding a horse you don't own, it will after some time become "yours" in the sense that it listen to your whistles as you're roaming around.
This horse also persists in the game world, it will stay where you've left it. There can only be one temporary horse - when another horse becomes your temporary horse, the earlier horse is unregistered as yours.
So it's possible that when you loaded, the game spawned your temporary horse near you, while keeping your owned horses in the stables.

A: Thanks for the answer. First extra horse isn't from the mission with Hosea it's little bit further from the game. I have two horses. Horse Arthur got from the mission like you said and that horse Arthur bought with Hosea. I have given them both new names to clarify things. I have used now just those two horses so there hasn't been temporary horses lately. Just one but it disappeared earlier in the game when I got Arthur killed. These extra horses are brown Tennesee walkers. First appeared when I went to the stable to upgrade. Other when I load the game. Arthur wasn't in the same place when I saved the game last time so that is just like you said.


text:
Q: How can I get this GIF from another website? I'm creating a website and I want a certain gif background that runs automatically on page load, here is the link of the website
http://contact-festival.com/
And I want to use the moving star-background on the artist line up list
I checked my developer tools and the network , but can't seem to find a source

A: These are not gifs . These are made with canvas tags and javascript coding.

So here is an example below that you can use.

window.onload = function () {

  var element = "starfield";
  var bgColor = "#030304";
  var FPS = 30;
  var displacementRate = 5;
  var accelerationRate = 10;
  var maxSpeed = 100;
  var maxStars = 1000;

  var speedUp = setInterval(function(){
    if (accelerationRate > maxSpeed) {
     clearInterval(speedUp);
    }
    accelerationRate = accelerationRate * 1.1;
  },100);

 var Star = function() {
  this.x = 0;
  this.y = 0;
  this.z = 0;
  this.maxDepth = 0;
  this.alpha = 0;
  this.radius = 0;

  this.dx = 0;
  this.dy = 0;
  this.dz = 0;
  this.ddx = 0;
  this.ddy = 0;

  this.drawInContext = function(ctx, deltaX, deltaY) {
   ctx.beginPath();
   ctx.fillStyle = "rgba(255, 255, 255," + this.alpha + ")";
   ctx.arc(this.x + deltaX, this.y + deltaY, this.radius, 0, Math.PI * 2, false);
   ctx.fill();
  };
 };

 var requestAnimationFrame =
  window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  function(callback) {
   return window.setTimeout(callback, 1000 / FPS);
  };

 function isCanvasSupported(element) {
  return !!(element.getContext && element.getContext("2d"));
 }

 function backingScale(context) {
  if ('devicePixelRatio' in window) {
   if (window.devicePixelRatio > 1) {
    return window.devicePixelRatio;
   }
  }

  return 1;
 }

 function StarField(canvasID) {
  this.canvas = document.getElementById(canvasID);
  if (!isCanvasSupported(this.canvas)) {
   this.canvas.className = "inactive";
   this.canvas.width = window.innerWidth;
   this.isCanvasEnabled = false;
   return this;
  }

  this.isCanvasEnabled = true;

  this.ctx = this.canvas.getContext("2d");
  this.scaleFactor = backingScale(this.ctx);
  this.stars = new Array();

  function newStar() {
   var star = new Star();
   star.x = Math.random() * this.canvas.width - this.originX;
   star.y = Math.random() * this.canvas.height - this.originY;
   star.z = star.max_depth = Math.max(this.canvas.width, this.canvas.height);
   star.alpha = Math.random();
   star.radius = Math.random();

   var xcoeff = star.x > 0 ? 1 : -1;
   var ycoeff = star.y > 0 ? 1 : -1;

   if (Math.abs(star.x) > Math.abs(star.y)) {
    star.dx = 1.0;
    star.dy = Math.abs(star.y / star.x);
   } else {
    star.dx = Math.abs(star.x / star.y);
    star.dy = 1.0;
   }

   star.dx *= xcoeff * (displacementRate / 10);
   star.dy *= ycoeff * (displacementRate / 10);
   star.dz = -1;

   star.ddx = (accelerationRate * star.dx) / 10;
   star.ddy = (accelerationRate * star.dy) / 10;

   return star;
  }

  function move(star) {
   star.x += star.dx;
   star.y += star.dy;
   star.z += star.dz;

   star.dx += star.ddx;
   star.dy += star.ddy;
  }

  function updateStars(ctx, stars) {
   for (var i=0; i<stars.length; i++) {
    move(stars[i]);

    if (stars[i].x < -this.originX || stars[i].x > this.originX || stars[i].y < -this.originY || stars[i].y > this.originY) {
     // Remove
     stars[i] = newStar();
    } else {
     // Paint
     var deltaX = this.originX;
     var deltaY = this.originY;
     stars[i].drawInContext(ctx, deltaX, deltaY);
    }
   }
  }

  this.configureGeometry = function() {
   // Ensure we are always at full width
   this.canvas.width = window.innerWidth;
   this.canvas.style.backgroundColor = bgColor;
   var ratio = 1;

   // Retina support
   // See http://www.html5rocks.com/en/tutorials/canvas/hidpi/
   if (this.scaleFactor > 1) {
    var devicePixelRatio = this.scaleFactor;
    var context = this.ctx;
    var backingStoreRatio = context.webkitBackingStorePixelRatio ||
          context.mozBackingStorePixelRatio ||
          context.msBackingStorePixelRatio ||
          context.oBackingStorePixelRatio ||
          context.backingStorePixelRatio || 1;
    ratio = devicePixelRatio / backingStoreRatio;

    // Upscale the canvas if the two ratios don't match
    if (devicePixelRatio !== backingStoreRatio) {
     var canvas = this.canvas;
     var oldWidth = canvas.width;
     var oldHeight = canvas.height;

     canvas.width = oldWidth * ratio;
     canvas.height = oldHeight * ratio;

     canvas.style.width = oldWidth + 'px';
     canvas.style.height = oldHeight + 'px';

     // Now scale the context to counter the fact that we've manually scaled our canvas element
     context.scale(ratio, ratio);
    }
   }

   // Starting origin of stars
   var logicalWidth = this.canvas.width / ratio;
   var logicalHeight = this.canvas.height / ratio;

   this.originX = logicalWidth / 2;
   this.originY = logicalHeight / 2;

   var numStars = logicalWidth / 2;
   this.numStars = numStars > maxStars ? maxStars : numStars;
  }

  this.render = function() {
   setTimeout(function() {
    // Drawing
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    updateStars(this.ctx, this.stars);

    requestAnimationFrame(render);

   }, 1000 / FPS);
  };

  // Configure origin and frames before creating initial batch of stars
  this.configureGeometry();

  for (var i=0; i<this.numStars; i++) {
   this.stars.push(newStar());
  }

  return this;
 }

 var starfield = StarField(element);
 if (starfield.isCanvasEnabled) {
  starfield.render();
 }

 // Make sure we adjust the canvas whenever the window resizes
 // Don't rely on CSS rules for 100% width because that causes rendering issues
 window.addEventListener('resize', resizeCanvas, false);
 function resizeCanvas() {
  if (starfield.isCanvasEnabled) {
   starfield.configureGeometry();
  } else {
   starfield.canvas.width = window.innerWidth;
  }
 }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="starfield" width="100%" height="400px"></canvas>


text:
Q: Mysql syntax error (mysql noob here) DELIMITER ||

CREATE FUNCTION InsertEvent (IN iPatientMonitoringId BIGINT,
                             IN iTypeId SMALLINT(6),
                             IN iChannelId SMALLINT(6),
                             IN iStart TIMESTAMP,
                             IN iEnd TIMESTAMP)
RETURNS BIGINT DETERMINISTIC

BEGIN

  INSERT INTO Event
    (Id, PatientMonitoringId, TypeId, ChannelId, StartOcurrence, EndOcurrence)
  VALUES
    ('', iPatientMonitoringId, iTypeId, iChannelId, iStart, iEnd);

  RETURN LAST_INSERT_ID();

END ||

DELIMITER ;

This sql query looks ok to me but I'm not understanding the error returned by phpmyadmin:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IN iPatientMonitoringId BIGINT, IN

A: From: http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Note
Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE.
For a FUNCTION, parameters are always regarded as IN parameters.

Therefore, I believe you should drop the IN.
Try:
CREATE FUNCTION InsertEvent (iPatientMonitoringId BIGINT, iTypeId SMALLINT(6),
iChannelId SMALLINT(6), iStart TIMESTAMP, iEnd TIMESTAMP) RETURNS BIGINT
DETERMINISTIC


text:
Q: Use grid item from adapter in dialog popup as view in Android I want to set the view of popup dialog to be the grid item.
I get this item as view in OnClickListener event set in the adapter.
 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    View grid;
    final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        grid = inflater.inflate(R.layout.child_card, null);
        final TextView textView = (TextView) grid.findViewById(R.id.childName);
        //ImageView imageView = (ImageView)grid.findViewById(R.id.childImage);
        textView.setText(children.get(position).getName());

        grid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setBackgroundColor(Color.GREEN);
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setView(v);

                final Dialog dialog = builder.create();
                dialog.show();
                final Handler handler  = new Handler();
                final Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                };

                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        handler.removeCallbacks(runnable);
                    }
                });
                handler.postDelayed(runnable, 3000);
            }
        });
    } else {
        grid = (View) convertView;
    }

    return grid;
}

I got these error:
"The specified child already has a parent. You must call removeView() on the child's parent first."

A: Observations:
-Do not create redudant View Object when convertView is already available.
-Setting of data should be outside if-else loop.
-Click listener should also be outside if-else loop.
-Use ViewHolder pattern for initializing views.
-In child_card layout set Tag in xml for each textview and imageview.
For example
<TextView
android:id=""
android:layout_width =""
android:layout_height=""
android:tag="1"
/>

likewise for ImageView.
Try out below code.
 @Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    if(convertView == null) {
        holder = new ViewHolder;
        convertView = inflater.inflate(R.layout.child_card, null);
        holder.textView = (TextView) convertView.findViewById(R.id.childName);
        //holder.imageView = (ImageView)convertView.findViewById(R.id.childImage);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    // set views here.
    holder.textView.setText(children.get(position).getName());

    // add click Listener here.
    convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setBackgroundColor(Color.GREEN);
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setView(v);

                final Dialog dialog = builder.create();
                dialog.show();
                final Handler handler  = new Handler();
                final Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                };

                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        handler.removeCallbacks(runnable);
                    }
                });
                handler.postDelayed(runnable, 3000);
            }
        });

        return convertView;
}

class ViewHolder {
    TextView textView;
    ImageView imageView;
}


text:
Q: showing inclusion map from topological space to product space is continuous let $i:X \rightarrow X \times Y$ where $i(x)=(x,y_{0})$. I am to show that $i$ is continuous. ($X,Y$ topological spaces of course)
I started off by looking at an example $i:\mathbb{R} \rightarrow \mathbb{R}\times\mathbb{R}$ with $i(x)=(x,y_{0})$ where it is clear if one is to take an open ball in $\mathbb{R}\times\mathbb{R}$ and fix a $y_0$ the the ball becomes an open interval and from there it is clear the $i$ is continuous. (that is the inverse images of the open balls are clearly open intervals, since the balls are basically already intervals via $i$)
Although I am having trouble taking this concept to abstraction to prove the statement. A hint as to how to do this would be greatly appreciated.

A: I don't believe it is helpful to restrict oneself to the example where e.g. $X=Y=\mathbb R$. The result is more fundamental than that.
Let $U$ be open in $X\times Y$, then by definition of product topology we may write $$U = \bigcup_{\alpha\in I} (U_\alpha^X\times U_\alpha^Y)$$ where $U_\alpha^X$ is open in $X$ and $U_\alpha^Y$ is open in $Y$ for each $\alpha\in I$. If $y_0\notin U$ then $i^{-1}(U)=\varnothing$ is open in $X$. If $y_0\in U$, let $J\subset I$ be the set of $\beta$ such that $y_0\in U_\beta^Y$. Then
\begin{align}
i^{-1}(U) &= i^{-1}\left(\bigcup_{\alpha\in I} (U_\alpha^X\times U_\alpha^Y \right)\\
&= i^{-1}\left(\bigcup_{\beta\in J} (U_\beta^X\times U_\beta^Y \right)\\
&= \bigcup_{\beta\in J} i^{-1}(U_\beta^X\times U_\beta^Y)\\
&= \bigcup_{\beta\in J} U_\beta^X
\end{align}
is open in $X$ as the union of open sets in $X$. It follows that $i$ is continuous.

A: A general fact about any product topological space:

A function $Y \to \prod_{i \in I} X_i$ from any space $Y$ to a product space is continuous iff $\forall i\in I: \pi_i \circ f: Y \to X_i$ is continuous, where the $\pi_i$ are the standard projections on the product.

This is the universal mapping property which holds for all initial topologies, of which products are an important special case.
For your $i$, we have that $\pi_1 \circ i = 1_X: X \to X$, the identity on $X$, which is always continuous, and $\pi_2 \circ i = c_{y_0}: X \to Y$ the constant map with value $y_0$, which is also continuous, as any constant map (all inverse images of (open) sets are $Y$ or $\emptyset$, always open). So $i$ is continous. That is the whole proof.


text:
Q: How to use str.contains to identify a word within column values in Python? currently in my data I have a column that contains description of transaction. I want to use str.contains to identify which values/rows are AW (the fast food store) transaction. However, when I use data['cat_desc'].str.contains('AW', case=False, na=False), it also identifies values that have string 'aw', for example 'awxxxx' but I don't want that. How can I just identify 'AW' as a word and not string? Thanks!

A: Then use a regex with word boundaries ('\b'):
data['cat_desc'].str.contains(r'\bAW\b', case=False, na=False, regex=True)

NB. By default contains uses regex=True.

A: import re

x = "awxxx"
y = "aw"

a = bool(re.match(r"^aw$", x))
b = bool(re.match(r"^aw$", y))

print(a, b)


text:
Q: To generate pdf for every div in the html using Javascript/typescript I tried using addHTML function to generate pdf for the particular HTML page but it is generating pdf for only current page and not every div present in the HTML.
This is the code I am using to generate a pdf.
generatepdf(){
    var pdf = new jsPDF();
    pdf.setProperties({
      background:'#fff'
    });
    pdf.addHTML(document.body,function() {
      pdf.save('vehicleHistory.pdf');
  });

  }

Here i could generate pdf for the current displayed page alone and not to the other div's.
Kindly help me in resolving it. Thanks in advance.


text:
Q: What does "put the top down" mean? Well, I have been searching the meaning of "put the top down", but I didn't find anything useful. Let me show you a little bit the context.
I'm gonna put the top down
I'm gonna talk about old times
I'm gonna put the top down
I'm gonna let myself unwind
I'm gonna put the top down
I'm gonna watch the day roll by
I'm gonna put the top down
This time.

It's the song's chorus. If you want to listen it, click here.
I was searching on UrbanDictionary, they have two meanings of top down but I consider that they are not so appropriate.
If someone have any idea of what this phrase means, I will be happy.

A: "I'm gonna put the top down" is a reference to a convertible sedan, which usually has a "cloth" top  that can be hidden behind the back seat. It allows the sun to shine on the passengers and the wind to blow through their hair. People do that when they want to feel "free" and relaxed.
It's just a metaphor for "unwinding" and "relaxing" and "talking freely", although it might also mean that the singer's actually driving a convertible while talking about old times.


text:
Q: Is it possible to use Html.RenderPartial in non-MVC ASP.Net page? I want to render MVC controls in non-MVC ASP.Net pages.  Is this possible?

A: RenderPartial is an extension method that extends the HtmlHelper. The HtmlHelper's constructor takes a ViewContext.    All 3 of those are in the System.Web.Mvc namespace.  So, you'd have to a the very least reference the Mvc dll.  You would also need to create an HTML helper by creating the other 2 objects.  I'd be interested if you got it work, but I don't know if it's possible.

A: We need to reference the MVC dll into the project and also need to define similar structure like Route.config which will have default rout. Also  we would have Model, View and Controller folder, in which we should have the Views web.config as well


text:
Q: asp.net mvc routing url.action issue In my view I'm using a
<img src="@Url.Action("Method", new { Model.Url })" ...
<img src="@Url.Action("Method", new { Model.Url })/1" ...

And in that method I have params:
public ActionResult Method(string url, int ids=0)

With
var book = GetBookByUrl(url);
...
switch (ids)
{
case 1:

In my global.asax I have:
        routes.MapRoute(null,
            "{controller}/{action}/{url}/{ids}",
            new { controller = "Controller", action = "Method", url = "", ids = @"\d+" });

My view returns the correct URL's (with /1 and /2 appended), but I can't seem to get my method to retrieve the value of ids so that I can manipulate them in my action method to retrieve different results based on the Url.Action URL provided within my view, what gives?
The ids parameter seems to always be 0 (not being routed data) and the url parameter has the entire url "bla-bla/2", which I do not want.
Please note that although there are plenty of routing resources, I've read over them and can't seem to get this to work - also is this the standard way of routing data from a request to a controller?
Please show me by way of example how to solve, many thanks!


text:
Q: how to stream a console to the network I have a Linux server running and I would like to stream the first four consoles (TTY1,TTY2,TTY3,TTY4) where I have different tails with with my log-files to the network so I can receive the stream in the way I receive a webcam in my network.
The reason is that my NVR (Network Video Recorder) Device can split the screen in 4 and display 4 log-files or even 16 log files in the same time.
The NVR supports the following protocols : N1 and ONVIF
I found different solutions to stream a media file, bit none for streaming the console.

A: Honestly, I think you're working too hard.  Try looking at something like tmux which can do the console multiplexing, as well as allowing multiple connections to the console it creates.  You can also split the "screens" into multiple consoles, and switch between them.

This is something that can easily be re-connected to from as many consoles as you have access to, as well as detaching from the tmux session, without killing any processes.

A: This will create a video of TTY1 and pipe it to ffplay (you could do something else with it)
#!/bin/bash

(while sleep 1
do
    screendump 1 | anytopnm | pnmtojpeg
done) | ffmpeg -f image2pipe -r 1 -c:v mjpeg -i - -c:v copy -f matroska - | ffplay -

You can also check when LOGFILE changes. Each time that happens it will get the last 25 files, convert them to an image and feed it to ffmpeg, that creates a matroska video file and writes it to stdout, where ffplay picks it up and plays it.
I left all the pipes so that you can decide where to insert the solutions you already had for media files.
#!/bin/bash

LOGFILE=/tmp/filename

(while inotifywait -q -e modify $LOGFILE >/dev/null; do
    tail -25 $LOGFILE | anytopnm | pnmtojpeg
done) | ffmpeg -f image2pipe -r 1/8 -c:v mjpeg -i - -c:v copy -f matroska - | ffplay -


text:
Q: How to compile and watch *two* Typescript packages, one that depends on the other? I'm developing a Typescript library under src/ and examples under examples/. The directory structure is this:
examples/
    package.json
    exampleFiles.ts
src/
    index.ts
package.json

I can compile the library with these instructions, but I'm not sure how to watch both projects simultaneously, especially not when one has a dependency on the other.
examples/package.json looks like this:
{
  "dependencies": {
    "my-project": "file:..",
  }
}

i.e., I'm using a file: dependency so that I don't have to keep publishing the library to npm and reinstalling it. I'm hoping that'll help.
How can I set this up for easy development?

A: You need to generate DTS files from the src package and make those available to the examples package. One way to do this would be to create a tsconfig.json in each package.

A: This is a bit complicated, but this appears to be working:
package.json
{
  "name": "my-lib",
  "version": "0.3.0",
  "types": "src/index.ts", <-- important
  ...
}

examples/package.json
{
  "dependencies": {
    "react": "^15.6.1",
    "react-redux": "^5.0.5",
    "redux": "^3.7.2"
  },
  "devDependencies": {
    "@types/react": "^16.0.0",
    "@types/react-dom": "^15.5.1",
    "awesome-typescript-loader": "^3.2.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.4.1",
    "webpack-dev-server": "^2.6.1"
  }
}

examples/webpack.config.babel.js
import {ProvidePlugin} from 'webpack';
import {CheckerPlugin, TsConfigPathsPlugin} from 'awesome-typescript-loader';

export default {
    context: `${__dirname}/src`,
    entry: './index.tsx',
    output: {
        path: `${__dirname}/src`,
        filename: 'bundle.js',
        publicPath: '/',
        pathinfo: true,
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'awesome-typescript-loader'
            },
            {
                test: /\.(jpe?g|png|gif)($|\?)/i,
                // include: __dirname,
                loader: 'url-loader',
                options: {
                    limit: 1024 * 2,
                }
            },
        ]
    },
    target: 'web',
    resolve: {
        modules: ['node_modules'],
        extensions: ['.tsx', '.ts', '.jsx', '.js'],
        plugins: [
            new TsConfigPathsPlugin()
        ],
    },
    devtool: 'cheap-module-eval-source-map',
    plugins: [
        new ProvidePlugin({
            React: 'react',
        }),
        new CheckerPlugin(),
    ]
};

examples/.babelrc
Just allows us to use import in our webpack.config.babel.js.
{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

examples/tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "importHelpers": false,
    "removeComments": false,
    "preserveConstEnums": false,
    "sourceMap": true,
    "inlineSources": true,
    "noEmitOnError": false,
    "pretty": true,
    "outDir": "dist",
    "target": "es2017",
    "downlevelIteration": false,
    "lib": [
      "esnext",
      "dom"
    ],
    "moduleResolution": "node",
    "declaration": true,
    "module": "ESNext",
    "types": [
      "node"
    ],
    "baseUrl": ".", <-- needed
    "paths": {
      "my-lib": [
        ".."  <-- allows us to `import 'my-lib'` without having to publish it to npm first
      ]
    },
    "jsx": "React",
    "allowSyntheticDefaultImports": true
  },
  "files": [
    "src/index.tsx"
  ]
}

examples/Makefile
I like to use Make instead of npm scripts.
# these are not files
.PHONY: all clean

# disable default suffixes
.SUFFIXES:

all: yarn.lock
    npx webpack-dev-server --hot --inline --colors --port 3123 --content-base src

yarn.lock:: package.json
    @yarn install --production=false
    @touch -mr $@ $<

yarn.lock:: node_modules
    @yarn install --production=false --check-files
    @touch -mr $@ $<

node_modules .deps:
    mkdir -p $@

clean:
    rm -rf node_modules dist

Running
With all of that, you should be able to just cd into the examples dir and run make. It'll start webpack-dev-server, watch your files and automatically reload.
React component hot loading is a bit more work yet.


text:
Q: Behaviour of DefWindowProc WinApi Can somebody explain why with DefWindowProc everything is ok, but if I remove it, the string "Hello windows" appears on screen without window and any buttons? "UpdateWindow" sends to window procedure WM_PAINT message, so why the text is displayed but creation of window is skipped?
#include <windows.h>

LRESULT CALLBACK proc1 (HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT ("Program");
HWND hwnd1;
MSG msg1;
WNDCLASS wndclass1;

wndclass1.style = CS_HREDRAW | CS_VREDRAW;
wndclass1.lpfnWndProc = proc1;
wndclass1.cbClsExtra = 0;
wndclass1.cbWndExtra = 0;
wndclass1.hInstance = hInstance;
wndclass1.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndclass1.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass1.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
wndclass1.lpszMenuName = NULL;
wndclass1.lpszClassName = szAppName;

RegisterClass (&wndclass1);

hwnd1 = CreateWindow (  szAppName,
                        TEXT ("My window"),
                        WS_OVERLAPPEDWINDOW,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        NULL,
                        NULL,
                        hInstance,
                        NULL );
ShowWindow (hwnd1, iCmdShow);
UpdateWindow (hwnd1);
while ( GetMessage(&msg1, NULL, 0, 0) )
{
    TranslateMessage(&msg1);
    DispatchMessage(&msg1);
};
return msg1.wParam;
};

LRESULT CALLBACK proc1 (HWND hwnd1, UINT message, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;
    PAINTSTRUCT ps;
    RECT rect;
 switch (message)
 {
 case WM_CREATE:
    return 0 ;
 case WM_PAINT:
    hdc = BeginPaint (hwnd1, &ps) ;
    GetClientRect (hwnd1, &rect) ;
    DrawText (hdc, TEXT ("Hello windows"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
    EndPaint (hwnd1, &ps) ;
    return 0 ;
 case WM_DESTROY:
    PostQuitMessage (0) ;
    return 0 ;
};
 return DefWindowProc (hwnd1, message, wParam, lParam) ;
}

A: Not all window messages require processing.  But if you remove the DefWindowProc() call then certain messages that should be processed don't get processed.  Like WM_NCPAINT, which draws the window frame.  And WM_ERASEBKGND, which draws the window background.  Which are things that DefWindowProc() knows to do well, in no small part assisted by the WNDCLASS you created for the window and the window style flags you passed in the CreateWindowEx() call.
So sure, remove the call and you won't see a frame nor a background.  And many, many other things that a window knows how to do without your help.  DefWindowProc() implements the default behavior of a window.  Your window procedure gives it non-default behavior.

A: If you omit DefWindowProc then you are saying "For all messages I did not handle above, do nothing." Which means that a lot of messages like "Please draw the buttons" get handled as "do nothing." Result: No buttons. Pass all unhandled messages to DefWindowProc.


text: Q: NativeScript. Add new layout when a tap event occurs on actionItem element i tried creating an app that allows me to add my new pet's name and color whenevr i click on add new page, but the app is not working as i expect it, i need help, i am kinda stuck. On tapping the add a page, it navigates to a page to fill a form and then binds the details back to the main page, but it is not just obeying .[when i click, a new layout is added[it navigates to the form pageinstead of returning back to the main page with two layout, i am getting one


text:
Q: JS Regex - non capture optional quotes Struggling getting a working regex that doesn't capture quotes which are optional.
Code and jsfiddle below.
https://jsfiddle.net/zx7Lurob/1/
var txt = `#VER B 2000 20190403 "Text" 20190413`; //without quote 2000
var txt2 = `#VER B "2000" 20190403 "Text" 20190413`; //with qutoe 2000

var myRegexp = /(#VER)\s+"(.+)"|(.+)\s+(.+?)\s+(\d{8})\s+"(.+)"/g;

do {
    var match = myRegexp.exec(txt2);
    if (match != null)
    {
        match.forEach(function(value) {
        console.log(value);
    });
    //console.log(match);
  }
} while (match != null);

Gives a result with quoted values for txt2.

A: You can use
var myRegexp = /(#VER.*?)\s+(?:"([^"]*)"|(\S+))\s+(\d{8})\s+"([^"]*)"/g;

See the regex demo. Details:

*

*(#VER.*?) - Group 1: #VER and then any zero or more chars, other than line break chars, as few as possible

*\s+ - one or more whitespaces

*(?:"([^"]*)"|(\S+)) - either ", then any zero or more chars other than " (captured into Group 2), or one or more non-whitespace chars (captured into Group 3),

*\s+ - one or more whitespaces

*(\d{8}) - Group 4: eight digits

*\s+ - one or more whitespaces

*"([^"]*)" - ", then any zero or more chars other than " (captured into Group 5), and then a " char.

See the JavaScript demo:

var txt = `#VER B 2000 20190403 "Text" 20190413`;
var txt2 = `#VER B "2000" 20190403 "Text" 20190413`;

var myRegexp = /(#VER.*?)\s+(?:"([^"]*)"|(\S+))\s+(\d{8})\s+"([^"]*)"/g;

for (var txt of [txt, txt2]) {
  do {
    var match = myRegexp.exec(txt);
    if (match != null)
    {
        console.log(txt, '=>',
             [match[1], match[3] || match[2], match[4], match[5]]);
    }
  } while (match != null);
}

A: Its difficult to determine if a positional way points are intended or
a field delimiter.
Its my guess its actually a hybrid of both.
In that case a simple matching an optional quote on both sides of a
field and outside of the capture should do the trick.
/(\#VER.*)[ \t]+"?(.+?)"?[ \t]+(\d{8})[ \t]+"(.+)"/

https://jsfiddle.net/Lj4rzo2s/
 ( \#VER .* )                  # (1)
 [ \t]+

 "?
 ( .+? )                       # (2)
 "?
 [ \t]+

 ( \d{8} )                     # (3)
 [ \t]+

 "
 ( .+ )                        # (4)
 "


text:
Q: Why can't I use AddRange to add subclassed items? I have two classes.... Parcel and FundParcel...and I'm trying to convert an IEnumerable of the subtype to an IList of the supertype....
public class FundParcel : Parcel
{
  /* properties defined here */
}

public class Parcel
{
  /* properties defined here */
}

These are used in another class in a method as follows:
private IList<Parcel> ExtractParcels(IEnumerable<FundParcel> fundParcels)
{
    var parcels = new List<Parcel>();

    foreach (var fp in fundParcels)
        parcels.Add(fp);

    return parcels;
}

What I don't understand is why the foreach statement can't be reduced to:
parcels.AddRange(fundParcels);

I basically get an error that says "Argument type 'System.Colection.Generic.IEnumerable<FundParcel>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<Parcel>'"
But if that's the case then I don't understand why parcels.Add works...
I feel as though the entire method ought to be replaceable with the line:
return (List<Parcel>)fundParcels;

...or maybe the method can be scrapped alltogether since subtypes should be substitutable for their supertype..
Can anyone explain what the deal is with AddRange in this case and why the for loop may be necessary in this case?

A: This SO will probably answer your question and also will point you to references about upcoming C# 4.0 which will support Co-/Contra-variance to a certain degree.

A: Consider this code:
void AddParcelToParcelList(List<Parcel> parcels) {
  parcels.add(new Parcel());
}

List<FundParcel> fundParcels = new List<FundParcels>();
AddParcelToParcelList(fundParcels);

If containers of inherited classes also inherited from containers of the base classes, the above code would be valid, and generate a case where a list of the inherited class contains an object of the base class.


text:
Q: Investigating thread stack overflow I am experiencing segmentation fault when running my multi-threaded embedded application. GDB gave me a hint that the stack could be corrupt which lead me to believe the stack is too small for the problematic thread. Increasing the stack size seem to remove the issue but I would like to confirm it a bit further. What are my options here? Is it possible to find out the current stack size at the event of segfault?

A: In gcc compile with -fstack-usage.  That will cause the a .su file to be output for each object file which contains plain text stack report for each function. LIke:
main.c:36:6:bar    48    static
main.c:41:5:foo    88    static
main.c:47:5:main    8    static

However that reports only the stack frame for the function, the stack usage is the sum of the stack frames for each function called from that function.  Working that out for all possible call paths to determine the worst case stack depth for any non-trivial application is not practical - you need a look that can inspect the call-graph and use the .su data to work that out for you.  Here is an example of a perl script to combine the output of objdump and the .su files to generate a full stack report like:
  Func                               Cost    Frame   Height
------------------------------------------------------------------------
> main                                176       12        4
  foo                                 164       92        3
  bar                                  72       52        2
> INTERRUPT                            28        0        2
  __vector_I2C1                        28       28        1
  foobar                               20       20        1
R recursiveFunct                       20       20        1
  __vector_UART0                       12       12        1

Peak execution estimate (main + worst-case IV):
  main = 176, worst IV = 28, total = 204

The stack usage for your thread will be the stack usage of its entry-point/thread function, plus perhaps some margin for whatever thread overhead the OS may require.
Note that calls through function-pointers and recursion will defeat this method, so you may need to assess that separately by considering the stack usage of the functions called and the depth of recursion likely.
The answer to How to determine maximum stack usage in embedded system with gcc? may also be useful.
To help detect stack issues at runtime there are various instrumentation options related to stack checking and protection at https://gcc.gnu.org/onlinedocs/gcc-10.2.0/gcc/Instrumentation-Options.html#Instrumentation-Options
Knowing the"current stack size" at the point you get a seg fault is not particularly helpful.  It won't tell you tell you how much stack is needed, it will just tell you how far out of bound it happened to be at the point the MMU trapped the fault, which is likely to be as soon as it accesses outside of the allocated stack space, within the resolution of the page size.  It just tells you your stack is not big enough - which you kind of knew already.
A "dynamic" technique for stack analysis is to "oversize" the stack, fill it with single byte value, then after running the code through a test sequence designed to exercise all likely call paths you inspect the stack region to see where the "high-tide mark" is relative to the start of the region, then "right-size" your stack accordingly.  That is a common technique but depends on exercising all likely paths.  Typically error and exception handling paths are omitted, so you can end up getting a stack overflow, just when your code is trying to handle some other error - its risky.


text:
Q: .htaccess keep multiple GET params Part 1 takes care of making example.com/fr behave like example.com?lang=fr, or example.com/fr/some-page.php like example.com/some.page.php?lang=fr etc.
Part 2, which I'm currently working on not working well yet, is to obtain a new GET param for other pages called page, in this case if there's login in the url.
Problem: It seems like part of the page loads twice when going to for example example.com/login or example.com/fr/login.
Maybe un-necessary details here but for instance it says Facebook Pixel Error: Duplicate Pixel ID:, and similar errors for other tags I use like Mixpanel, and then my JS just stops working. That's all I can say about the problems I see on my side. Best chance seems to be about looking for flagrant errors in the htaccess rules.
What should be fixed in the rules so the end goal of having the GET param page and lang work fine?
RewriteEngine On

# Part 1
RewriteCond %{THE_REQUEST} \s/+[^?]*\?lang=([^\s&]+)\s [NC]
RewriteRule ^ /%2/%1? [R=301,L,NE]
RewriteCond %{REQUEST_URI} !^/js/
RewriteRule ^([a-z]{2})(?:/([^/]+))?$ $2?lang=$1 [NC,L,QSA]

# Part 2 (this is the part I am adding, which isn't fully working well yet)
# anything looking flagrantly wrong? If for example we are on `example.com/fr/login`,
# according to rules in this htaccess file we should have 2 GET params, `lang` and `page`.
RewriteCond %{REQUEST_URI} login
RewriteRule .* index.php?page=login

# adding more pages the same way
RewriteCond %{REQUEST_URI} signup
RewriteRule .* index.php?page=signup

A: You can use the following rule as your Part1
RewriteEngine on
RewriteRule ^(en|fr)/login/?$ /index.php?page=login [L]

RewriteCond %{THE_REQUEST} \?lang=([^&]+)\sHTTP
RewriteRule ^ /%1%{REQUEST_URI}? [L,R]
RewriteRule ^(en|fr)/?(.*\.php)?$ /$2?lang=$1 [L]


text:
Q: Creating a class to store threads and calling them Here is a simplified version of what I am trying to do:
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>

class client {
private:
    std::vector<std::thread> threads;
    std::atomic<bool> running;

    void main() {
        while(running) {
            std::cout << "main" << std::endl;
        }
    }

    void render() {
        while(running) {
            std::cout << "render" << std::endl;
        }
    }
public:
    client() {
        running = true;

        threads.push_back(std::thread(&client::main, this));
        threads.push_back(std::thread(&client::render, this));
    }

    ~client() {
        running = false;
        for(auto& th : threads) th.join();
    };
};

int main() {
    client c;

    std::string inputString;
    getline(std::cin, inputString);

    return 0;
}

(Note: code has been changed since question was written)
What I am trying to do is create a class that holds threads for the main loop(of the class), rendering, and a couple other things.  However I cannot get this simplified version to work.  I have tried using mutex to lock and unlock the threads, but didn't seem to help any.  I do not know why it is not working, but I suspect that it is a result of the use of this in threads.push_back(std::thread(this->main, this));.
The current structure of the code doesn't have to remain... The only requirement is that uses one of it's own member functions as a thread (and that, that thread is stored in the class).  I am not sure if this requires two classes or if my attempt to do it in one class was the correct approach.  I have seen many examples of creating an object, and then calling a member that creates threads.  I am trying to avoid this and instead create the threads within the constructor.

A: The problem here is that you do not wait for the threads to end.  In main you create c.  This then spawns the threads.  The next thing to happen is to return which destroys c.  When c is destroyed it destroys its members.  Now when a thread is destroyed if it has not been joined or detached then std::terminate is called and the program ends
What you need to do is in the destructor, set running to false and then call join on both the threads.  This will stop the loop in each thread and allow c to be destructed correctly.
Doing this however brings up another issue.  running is not an atomic variable so writing to it while threads are reading it is undefined behavior.  We can fin that though by changing running to a std::atomic<bool> which provides synchronization.
I also had to make a change to the thread construction.  When you want to use a member function the syntax should be
std::thread(&class_name::function_name, pointer_to_instance_of_class_name, function_parameters)

so in this case it would be
threads.push_back(std::thread(&client::main, this));
threads.push_back(std::thread(&client::render, this));


text:
Q: Java collection and MapKey I am new to java.
I have a database table which have following composite key:
Code
Reference_Number_1 (decimal)
Reference_Number_2 (decimal)
Time

Above keys make each row a unique row  - no dupliactes.
I need to create a class to load this table to a java collection and create a static method which will take above four arguments as key and return the entity from java collection.
I am thinking of loading the table into a HashMap but I am not sure how to define the MapKey. Should I convert Reference_Number_1, Reference_Number_2 and Time in to a string and then concatenate these four fields?
Or there is another way/collection to load this table.
Thanks,
Pete

A: Create another class which holds those 4 fields as properties and implement/autogenerate equals() and hashCode() according the contract (important! otherwise it can't be used as a proper Map key) and finally use it as (composite) key for the Map.
Here's what Eclipse has autogenerated for me (the equals() is open for improvement, it's somewhat verbose):
public class CompositeKey {

    private String code;
    private BigDecimal referenceNumber1;
    private BigDecimal referenceNumber2;
    private Date time;

    public CompositeKey(String code, BigDecimal referenceNumber1, BigDecimal referenceNumber2, Date time) {
        this.code = code;
        this.referenceNumber1 = referenceNumber1;
        this.referenceNumber2 = referenceNumber2;
        this.time = time;
    }

    public String getCode() {
        return code;
    }

    public BigDecimal getReferenceNumber1() {
        return referenceNumber1;
    }

    public BigDecimal getReferenceNumber2() {
        return referenceNumber2;
    }

    public Date getTime() {
        return time;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CompositeKey other = (CompositeKey) obj;
        if (code == null) {
            if (other.code != null)
                return false;
        }
        else if (!code.equals(other.code))
            return false;
        if (referenceNumber1 == null) {
            if (other.referenceNumber1 != null)
                return false;
        }
        else if (!referenceNumber1.equals(other.referenceNumber1))
            return false;
        if (referenceNumber2 == null) {
            if (other.referenceNumber2 != null)
                return false;
        }
        else if (!referenceNumber2.equals(other.referenceNumber2))
            return false;
        if (time == null) {
            if (other.time != null)
                return false;
        }
        else if (!time.equals(other.time))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((code == null) ? 0 : code.hashCode());
        result = prime * result + ((referenceNumber1 == null) ? 0 : referenceNumber1.hashCode());
        result = prime * result + ((referenceNumber2 == null) ? 0 : referenceNumber2.hashCode());
        result = prime * result + ((time == null) ? 0 : time.hashCode());
        return result;
    }

}

A: Encapsulate these four fields in an object:
public class Key {
    String code;
    float reference1;
    float reference2;
    Date time;

    public Key(String code, float ref1, float ref2, Date time) {
        ...
    }

    // implement equals() and hashCode()
}

Then define a Map as follows (not sure what type the "entity" is, so we will just pretend there is a class called Entity:
Map<Key, Entity> lookup = new HashMap<Key, Entity>();


text:
Q: How to get last updated row or ID in wordpress How to get last updated row or ID in wordpress.
Like :  $wpdb->insert_id;

A: I had the same problem.

There is no equivalent function. $wpdb->insert_id works only after $wpdb->insert

Alternative way
If it's an update, you can either get the id with a query based on the data you have got, or most of the time, you should have already got the id before update it.
global $wpdb;

$data = array(
    'first_name' => "John",
    'last_name' => "Doe"
);

$where = array(
    'id' => $my_id
);

$res_update = $wpdb->update( $wpdb->prefix . "my_table", $data, $where );

if( $res_update === false ){
     error_log( 'my error');
}

return $my_id;

A: Once again select the same row updated on success.
 if($wpdb->last_error !== '') {
      //throw error stuffs
    }else{
     $last_updated_row = $wpdb->get_row("SELECT * FROM $wpdb->prefix . 'my_table' WHERE id = $my_id");

    }