text:
Q: Представление отсутствия даты закрытия в БД и производительность Нередко при проектировании базы данных нужно описывать срок действия каких-либо сущностей. Почти всегда встаёт вопрос, как представлять сущность срок окончания действия, которой ещё неизвестен.
Четыре простых варианта:

*

*Два поля - дата открытия и дата закрытия. Если дата закрытия неизвестна ставим null.

*Два поля - дата открытия и дата закрытия. Если дата закрытия неизвестна ставим заранее оговоренную большая дата.

*Одно поле - только дата открытия. Всегда заполнена.

*Одно поле - только дата закрытия. Если дата закрытия неизвестна ставим null.

Первый вариант семантически правильней, но неудобен при построении запросов, может привести к проблемам с оптимизацией.
Второй вариант семантически уродливей, но удобней и вроде как производительней.
Третий и четвертый варианты самые удобные и производительные, но не позволяют фиксировать перерывы между действиями сущностей.
Я чаще пользовался вторым.
create table Presidents
(
    FullName  Varchar2(200 CHAR) NOT NULL ENABLE,
    StartDate Date NOT NULL ENABLE,
    EndDate   Date NOT NULL ENABLE
);

INSERT INTO Presidents (FullName, StartDate, EndDate)
  VALUES ('Ельцин',   to_date('dd.mm.yyyy','10.07.1991'),
                      to_date('dd.mm.yyyy','31.12.1999'));
INSERT INTO Presidents (FullName, StartDate, EndDate)
  VALUES ('Путин',    to_date('dd.mm.yyyy','07.05.2000'),
                      to_date('dd.mm.yyyy','07.05.2008'));
INSERT INTO Presidents (FullName, StartDate, EndDate)
  VALUES ('Медведев', to_date('dd.mm.yyyy','07.05.2008'),
                      to_date('dd.mm.yyyy','07.05.2012'));
INSERT INTO Presidents (FullName, StartDate, EndDate)
  VALUES ('Путин',    to_date('dd.mm.yyyy','07.05.2012'),
                      to_date('dd.mm.yyyy','31.12.2900'));

И вот я наткнулся на информацию о том, что использование слишком большой даты, как даты закрытия может навредить производительности.
Из https://stackoverflow.com/questions/687510/how-do-you-obtain-the-maximum-possible-date-in-oracle
Вопрос

Есть в Оракле встроенная функция, которая возвращает максимально возможную дату, и которую можно использовать для вставки в поле?

Комментарий

Зачем? Если вы начнёте вставлять заглушку 'большая-дата' в таблицу, это может 'сбить с толку' оптимизатор, который будет полагать, что у вас есть весь диапазон значений даты на следующие 8 тысяч лет

Насколько верен этот комментарий 2009 года и актуален в наши дни?

A: Для задачи как в вопросе - только у последнего президента дата окончания срока полномочий неизвестна, можно завершающую дату опрделить как NULL (=неизвестно) вместо большой даты.
На этапе проектирования не следует задумываться об оптимизации каких-то конкретных SQL запросов. На этом этапе главное соответствие модели данных, ограничения значений (доменов), бизнес задаче.
Попробуем так: уникальный индекс на начало и маленький функциональный индекс на завершающую дату. В итоге, подготовим данные:
create table ranges (
    id number primary key, startd date not null, endd date
);

create unique index ix_ranges on ranges (startd,endd);
create index ix_ranges_e on ranges (nvl2(endd,null,1));

insert into ranges
    select rownum, date'2020-01-01'+(rownum-1),
    case level when 10e3 then null else date'2020-01-01'+rownum end
    from dual connect by level <= 10e3;

exec dbms_stats.gather_table_stats(user, 'ranges', cascade=>true)

Самые распостранённые запросы выполняются наиболее оптимально.
Какой временной период сответствует заданной дате:
SQL> set autotrace on

SQL> select *
from ranges where sysdate between startd and endd;

Execution Plan
----------------------------------------------------------
Plan hash value: 3894254438

-------------------------------------------------------------------------------------------------
| Id  | Operation                           | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                    |           |   135 |  2700 |     3   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| RANGES    |   135 |  2700 |     3   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN                  | IX_RANGES |   135 |       |     2   (0)| 00:00:01 |
-------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("ENDD">=SYSDATE@! AND "STARTD"<=SYSDATE@!)
       filter("ENDD">=SYSDATE@!)

Или ещё не закрыт (текущий):
SQL> select *
from ranges where nvl2(endd,null,1) = 1;

Execution Plan
----------------------------------------------------------
Plan hash value: 2817486554

-----------------------------------------------------------------------------------------------------
| Id  | Operation                           | Name          | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                    |               |     1 |    21 |     2   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| RANGES        |     1 |    21 |     2   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN                  | FI_RANGES_END |     1 |       |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access(NVL2("ENDD",NULL,1)=1)

A: Начиная с версии 12c появилась возможность определять временной интервал в записи как временная действенность (Тemporal validity)

Temporal Validity Support lets you associate one or more valid time dimensions with a table and have data be visible depending on its time-based validity, as determined by the start and end dates or time stamps of the period for which a given record is considered valid.

Эта семантика определяет столбцы начала и конца временного интервала как действенный, если время конца всегда больше начала или возможно NULL, и действенность этого временного интервала включает время начала, но исключает время конца.  Подробнее см. искать по period_definition.
Для данных как в ответе столбец (скрытый) временной действенности можно добавить так:
alter table ranges add (period for validity (startd, endd));

Тогда, запросы будут выглядеть так:
select *
from ranges as of period for validity date'2047-05-21';

        ID STARTD              ENDD
---------- ------------------- -----------------------------
     10000 2047-05-18 00:00:00

select
from ranges versions period for validity between sysdate and sysdate+1;

        ID STARTD              ENDD
---------- ------------------- -------------------
       138 2020-05-17 00:00:00 2020-05-18 00:00:00
       139 2020-05-18 00:00:00 2020-05-19 00:00:00

Пока это новшество никаких преимушеств в производительности не обещает, это только часть преобразования запроса (т.н. Query Transformation).
Например, первый запрос выше до парсинга выглядит так:
Final query after transformations:******* UNPARSED QUERY IS *******
SELECT "T"."ID" "ID","T"."STARTD" "STARTD","T"."ENDD" "ENDD"
FROM "DB"."RANGES" "T"
WHERE "T"."STARTD"<=TO_DATE(' 2047-05-21 00:00:00', 'syyyy-mm-dd hh24:mi:ss')
AND ("T"."ENDD" IS NULL
  OR "T"."ENDD">TO_DATE(' 2047-05-21 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))

Но можно надеятся, что, возможно, для него будут произведены улучшения производительности в будущих версиях.
Например, после введения долгожданного SQL Assertions, и установки ограничения на непересекающиеся временные интервалы, оптимизатор найдёт более лучший способ найти запись, чем не самый оптимальный INDEX RANGE SCAN по одному столбцу.


text:
Q: Best formula/method to extract a standard set of numbers from a string? I have the following strings from which I need to extract 6 digit numbers. Since these strings are generated by another software, they occur interchangeably and I cannot control it. Is there any one method that would extract both 6-digit numbers from each of these strings?
Branch '100235 to 100236 Ckt 1' specified in table 'East Contingency' for record with primary key = 21733 was not found in branch or transformer data.
Loadflow branch ID '256574_701027_1' defined in supplemental branch table was not found in branch or transformer input.
Transmission element from bus number 135415 to bus number 157062 circuit ID = 1 defined for corridor  'IESO-NYISO' was not found in input data
I don't know VBA, but I can learn it if it means I can get the 6 digit numbers using a single method.
thanks
I have been using LEFT(), RIGHT() & MID() previously, but it means manually applying the appropriate formula for individual string.

A: If you have Microsoft 365, you can use this formula:
=LET(arr,TEXTSPLIT(SUBSTITUTE(SUBSTITUTE(A1,"'"," "),"_"," ")," "),
FILTER(arr,ISNUMBER(-arr)*(LEN(arr)=6)))

Thanks to @TomSharpe for this shorter version, using an array constant within TEXTSPLIT to add on possible delimiters.
=LET(arr,TEXTSPLIT(A1,{"_"," ",","," ","'"}),FILTER(arr,(LEN(arr)=6)*ISNUMBER(-arr)))

Data

Output

A: An alternative is:
=LET(ζ,MID(A1,SEQUENCE(,LEN(A1)-5),6),ξ,MID(ζ,SEQUENCE(6),1),FILTER(ζ,MMULT(SEQUENCE(,6,,0),1-ISERR(0+ξ))=6))

A: A couple more suggestions (if you need them):
(1) Replacing all non-digit characters with a space then splitting the resulting string:
=LET(numbers,TEXTSPLIT(TRIM(REDUCE("",MID(A1,SEQUENCE(1,LEN(A1)),1),LAMBDA(a,c,IF(is.digit(c),a&c,a&" "))))," "),FILTER(numbers,LEN(numbers)=6))

Here I've defined a function is.digit as
=LAMBDA(c, IF(c = "", FALSE, AND(CODE(c) > 47, CODE(c) < 58)))

(tl;dr I quite like doing it this way because it hides the implementation details of is.digit and creates a rudimentary form of encapsulation)
(2) A UDF - based on the example here and called as
=RegexTest(A1)

Option Explicit

Function RegexTest(s As String) As Double()

    Dim regexOne As Object
    Dim theNumbers As Object
    Dim Number As Object
    Dim result() As Double
    Dim i As Integer

    Set regexOne = New RegExp

    ' Not sure how you would extract numbers of length 6 only, so extract all numbers...

    regexOne.Pattern = "\d+"
    regexOne.Global = True
    regexOne.IgnoreCase = True

    Set theNumbers = regexOne.Execute(s)

    i = 1

    For Each Number In theNumbers

    '...Check the length of each number here

        If Len(Number) = 6 Then
            ReDim Preserve result(1 To i)
            result(i) = CDbl(Number)
            i = i + 1
        End If
    Next

    RegexTest = result

End Function

Note - if you wanted to preserve leading zeroes you would need to omit the Cdbl() and return the numbers as strings. Returns an error if no 6-digit numbers are found.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell error trying to save thumbnail to AzureAD So I'm trying to create a powershell script to sync our Active Directory user photos to AzureAD (and eventually Office365, but one task at a time, right?).  We have valid photos stored in AD.  The eventual goal is to have this script run on a regular basis.  Anyway...
import-module activedirectory
import-module AzureAD

$list = GET-ADuser <actual username here> -properties thumbnailphoto

function SaveToAzureAD()
{
    param
    (
        [Parameter(Mandatory = $true)][String] $AccountName,
        [Parameter(Mandatory = $true)][Array] $Thumbnail

    )

    Connect-AzureAD

    Write-Output "-----------------------------------------------------------------------"
    Write-Output "email address: "
    write-output "$AccountName@<insert domain here>"

    Write-Output "-----------------------------------------------------------------------"
    Write-Output "AD User account info: "
    $AdUser = Get-AzureADUser -Filter "userPrincipalName eq '$AccountName@<insert domain here>'"

    Write-Output "-----------------------------------------------------------------------"
    Write-Output "Set thumbnail: "

    Set-AzureADUserThumbnailPhoto -ObjectId $ADUser.ObjectID -ImageByteArray $Thumbnail

    return "done"
}

Foreach ($User in $list)
{

    If ($User.thumbnailphoto)
    {
        Write-Output $user.thumbnailphoto.GetType()

        SaveToAzureAD($User.SamAccountName) -Thumbnail $User.Thumbnailphoto
        Write-Output "done loop"
    }
 }

Everything works as you expect.  I get the pop up to log into with our Office365 stuff.  I'm able to pull the correct objectID and get the byte array representing the thumbnail image that I'm after (I've written the file out to disk - it's the correct one).  Then when it comes to calling Set-AzureADUserThumbnailPhoto, I pass the objectID and the byte array (in $Thumbnail) but it gives me an error and I've been beating my head against it.
I want to take the byte array and pass it to the Set-AzureADUserThumbnailPhoto call.  As near as I can tell, it's correct.  Here is the error...
Set-AzureADUserThumbnailPhoto :
At <path to script>\getphotos.ps1:87 char:9
+         Set-AzureADUserThumbnailPhoto -ObjectId $ADUser.ObjectID -Ima ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Set-AzureADUserThumbnailPhoto], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.Open.AzureAD16.Graph.PowerShell.Custom.Cmdlet.SetAzureADUserThumbnailPhotoCustom

I have done a bunch of googling trying to figure this out.

*

*There were several suggestions from Stack Overflow that suggested
that the problem was the execution policy.  I don't think that's the
case.  I have powershell set to remotesigned.

*There was a suggestion about the module not having the correct permissions/rights.  Near as I can tell, AzureAD and ActiveDirectory have what they need.

*I've tried updating the modules.

Does anyone have any suggestions about what to try next?
Also, I know I can just save the file and then read it in again and send it that way but I'd like to avoid doing that if I can.
Also, the documentation for Set-AzureADUserThumbnailPhoto REALLY needs more examples of all of the functionality...

A: Short Answer :
Looks like a issue with the code in the module.
Looks like you will not be able to update using the ImageByteArray.
Less likely can be fixed at your end.
Long Answer :
I tried decompiling the module as per the error Microsoft.Open.AzureAD16.Graph.PowerShell.Custom.Cmdlet.SetAzureADUserThumbnailPhotoCustom
This uses an internal method, ImageUtils.GetImage

I was tracking this function and saw the definition - so at the top there is a condition check :
 public static Image GetImage(Stream fileStream, string filePath, byte[] imageByteArray)
        {
            Image image;
            if (fileStream == null && filePath == null)
            {
                throw new ArgumentException(" ");
            }
.
.
.
.
<Excluding the rest code for brevitity>

This condition checks only for filestream and filepath (not for ImageByteArray - which is should not be the case. Ideally, in my opinion - there should be check for nullness of ImageByteArray )
So when you execute :
Set-AzureADUserThumbnailPhoto -ObjectId $ADUser.ObjectID -ImageByteArray $Thumbnail

by default parameters FileStream and FilePath are set to null.
On the first check, since both are null - it throws the argument exception as per the the code.


text:
Q: Flutter Get.Storage() not changing data while using Get.back() Get.back() does not change the data.
It stores data while I write in GetStorage but only Get.to()/ Get.named() these changes the data of Get.Storage(). While try to Get.back() it is not changing the data. Is there any solution for this?


text:
Q: How to interpret Hermann Minkowski's comments on the construction of spacetime What did Minkowski mean by his statement:

"The views of space and time which I wish to lay before you have sprung from the soil of experimental physics, and therein lies their strength. They are radical. Henceforth space by itself, and time by itself, are doomed to fade away into mere shadows, and only a kind of union of the two will preserve an independent reality."

In particular, the last sentence.
Should it be interpreted as follows?
Since both space and time are relative, observer dependent quantities, with the coordinates of both becoming mixed together under transformations between two inertial reference frames, this implies that form a single 4-dimensional entity since neither space nor time exist independently from one another (since, the spatial and temporal coordinates in one frame both become a mixture of spatial and temporal coordinates relative to another, and cannot be separated from one another). Additionally, in special relativity it is the spacetime interval that is absolute, implying that it is a 4-dimensional spacetime that one should consider in order to preserve any concept of an observer independent reality, with observer independent measurable physical quantities (such as the spacetime interval).

A: Yes, I agree with your interpretation of Minkowski's statement. You might be interested in reading the answers to What is time, does it flow, and if so what defines its direction? as I discuss exactly this point in the first part of my answer.
The key point is that there is no observer independent way of separating the time and spatial coordinates so spacetime has to be treated as a four dimensional manifold. I would add that understanding this is a key step in understanding general relativity.

A:
What did Minkowski mean by his statement: "The views of space and time which I wish to lay before you have sprung from the soil of experimental physics, and therein lies their strength. They are radical. Henceforth space by itself, and time by itself, are doomed to fade away into mere shadows, and only a kind of union of the two will preserve an independent reality".

He meant what he said. But that doesn't mean to say he was right. Take a look at Wikipedia. He gave his address on 21st September 1908. On 12th January 1909, less than four months later, he was dead. IMHO had he lived longer, he would have qualified the above.

Should it be interpreted as follows? Since both space and time are relative, observer dependent quantities, with the coordinates of both becoming mixed together under transformations between two inertial reference frames, this implies that [they] form a single 4-dimensional entity since neither space nor time exist independently from one another...

Most people will say yes it should. But I'm afraid most people are wrong. Because in this single 4-dimensional entity, in the block universe called spacetime, there is no motion. And we live in a world of space and motion*. Hold your hands up a foot apart and you can see the gap, the space between them. Now waggle your hands, and you can see motion with your own eyes. In this respect both space and time are empirical. But spacetime is not. It is an abstract mathematical arena. It is the "map". Not the territory.

(since, the spatial and temporal coordinates in one frame both become a mixture of spatial and temporal coordinates relative to another, and cannot be separated from one another).

There's nothing wrong with that. But think about it: you measure distance using the motion of light through space, and you measure time using the motion of light in your light clock. Then when you move, your measurements of distance and time change. One "rotates" into the other. And the underlying reason is trivially simple, see the simple inference of time dilation due to relative velocity. The Lorentz factor is just Pythagoras's theorem in disguise. And it works for you like it works for the parallel-mirror light clock because of the wave nature of matter.

Additionally, in special relativity it is the spacetime interval that is absolute

It isn't. A photon absolutely does not go from A to B instantly. That zero interval is not absolute. And when you go on a fast out-and-back trip and I stay at home, our spacetime intervals are the same merely because the light-path-lengths in our parallel-mirror light clocks are the same.

implying that it is a 4-dimensional spacetime that one should consider in order to preserve any concept of an observer independent reality, with observer independent measurable physical quantities (such as the spacetime interval).

No. One should consider space and motion to preserve the concept of observer independent reality. The mathematical model called spacetime can assist with this, but we live in a world of space and motion, not in a static block universe. The map is not the territory.

*

*See relativist Ben Crowell's answer here where he said "Objects don't move through spacetime. Objects move through space".


text:
Q: select query for multiple checkboxes? VF Page
<apex:page Controller="actionSupportController">
   <apex:form >
       <apex:pageBlock >
            Household Name: <apex:inputText value="{!ID_c}"/>
           </apex:pageBlock>
    <apex:pageBlock title="Characteristics Information">

        <apex:inputCheckbox value="{!Active_c}" />Active

        <apex:inputCheckbox value="{!Good_with_Cats_c}" />Good with Cats

        <apex:inputCheckbox value="{!sct.HighNeed__c}" />HighNeed

        <apex:inputCheckbox value="{!sct.kid_friendly__c}" />Kid Friendly

        <apex:inputCheckbox value="{!sct.Non_shedder__c}" />Non Shedder

        <apex:inputCheckbox value="{!sct.Predatory_Tendencies__c}" />Prediator Tendency

<apex:commandButton value="Search" action="{!dochar}" rerender="sblck"/>
    </apex:pageBlock>
    <apex:outputPanel id="sblck">
    <apex:pageBlock title="Search Results">
    <apex:pageBlockTable width="80%" value="{!selctchr}" var="eachpe">
        <apex:column width="80%" value="{!eachpe.Name}"/>
         <apex:column width="80%" value="{!eachpe.Pet_ID__r.Name__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Gender__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Height__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.pet__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Pet_Photo__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Status__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:outputPanel>
       <apex:commandButton value="Request Adoption"/>
   </apex:form>
</apex:page>

Controller
public class actionSupportController {
    public List<PCS_Household__c> lstQuery{get;set;}
    public List<PCS_Household__c> OnlstQuery{get;set;}
    public List<Characteristics__c> selctchr{get;set;}
    public Characteristics__c sct{get;set;}
    public string ID_c{get;set;}
    public string test{get;set;}
    public string Good_with_Cats_c{get;set;}
    public string Active_c{get;set;}
    public List<Pets_Information__c> selctpet{get;set;}

    Public Boolean Good{get;set;}

    public void dochar(){
        string query='';
        system.debug('==sct.Good_with_Cats_c=='+Good_with_Cats_c);
        query='**SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c='+Good_with_Cats_c or +Active_c**;

        system.debug('==query=='+query);
        selctchr=Database.query(query);
        system.debug('==selctchr=='+selctchr);
    }

    public PageReference incrementCounter() {
       string Query='';
        Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test';
        system.debug('==Query=='+Query);
        OnlstQuery=Database.query(Query);
        system.debug('==OnlstQuery=='+OnlstQuery);
        return null;
    }

     public Void doSearch(){
        string Query='';
        Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\'';
         system.debug('==ID_c=='+ID_c);
        system.debug('==Query=='+Query);
        lstQuery=Database.query(Query);
        system.debug('==lstQuery=='+lstQuery);
    }

    public void nullify(){
        lstQuery.clear();
    }

    public PageReference nextpage() {

        upsert OnlstQuery;

        return Page.cc;
    }
}

A: I feel below corrected version of query will work for you:
query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c=\''+Good_with_Cats_c+'\' or Active__c=\''+Active_c+'\'';


text:
Q: Trying to modify display of my url for html page What I would like to do is serve up a file such as "boat-repair" and have the url read allservicemarine.com/boat-repair/electrical-system-repair
Everything I have found so far seems to reference PHP files as part of the process is this possible with an html file and if so how can I potentially accomplish it
This code:
RewriteEngine On
RewriteRule    ^/?$    /boat-repair.html  [NC,L]

Will serve up the file when you type in allservicemarine.com
I tried putting the target file in a series of sub directories hoping the directory names would show in the address bar,but that still just pulls up the target file. I have been searching for many hours to try to find a solution and would appreciate it if anyone could point me in the right direction to accomplish the task.

A: This is the working code I came up with:
  RewriteEngine On
  RewriteRule    ^/?$    /boat-repair/electrical-system-repair  [NC]
  RewriteRule    ^boat-repair/electrical-system-repair/?$    /index.html [NC]

The first rule tells the server to serve up: boat-repair/electrical-system-repair when the root directory is entered.
The second rule tells the server if the pattern: boat-repair/electrical-system-repair is matched to serve up index.html
The file served up (index.html) in the last step can be named anything you like as it will load, but not show in the address bar.
So after both rules are implemented you get: http://yoursitename.com/boat-repair/electrical-system-repair/ in the address bar, now I just need to figure out a way to remove the trailing slash.
These rules of course get put in the htaccess file.
In order for this to work you must have the folders named in the rules even if they are just dummy folders. If dummy folders be sure to put a text document in each folder named "DO NOT DELETE THIS FOLDER" so that six months down the road you do not look at these empty folders and delete them!


text:
Q: UWP create new window for each file opened I'm trying to make an app open a window for each file.
-- Code ---
App.cs:
    protected async override void OnFileActivated(FileActivatedEventArgs Args)
    {
        //Opens Main Page
        base.OnFileActivated(Args);
        var RF = new Frame();
        var MW = new MainPage();
        AppWindow appWindow = await AppWindow.TryCreateAsync();
        var TB = appWindow.TitleBar;
        RF.Navigate(typeof(MainPage), Args);
        ElementCompositionPreview.SetAppWindowContent(appWindow, RF);
        appWindow.Equals(MW);
        Window.Current.Equals(MW);
        await appWindow.TryShowAsync();
        TB.ButtonHoverBackgroundColor = Colors.White;
        TB.ButtonHoverForegroundColor = Colors.Black;
        TB.ButtonBackgroundColor = Colors.Transparent;
        TB.ButtonPressedBackgroundColor = Colors.WhiteSmoke;
        TB.ButtonPressedForegroundColor = Colors.Black;
        TB.ButtonInactiveBackgroundColor = Colors.Transparent;
        TB.ButtonInactiveForegroundColor = Color.FromArgb(1, 3, 165, 252);
        TB.ExtendsContentIntoTitleBar = true;
        Window.Current.Activate();
    }

MainPage.cs:
    protected override async void OnNavigatedTo(NavigationEventArgs EvArgs)
    {
        //File opened arguments
        base.OnNavigatedTo(EvArgs);
        var Args = EvArgs.Parameter as IActivatedEventArgs;
        var FArgs = Args as FileActivatedEventArgs;
        string Value = GetText(REB);
        string SecValue = GetText(RTB);
        if (Args != null)
        {
            //Check if the app is opened by file
            if (Args.Kind == ActivationKind.File)
            {
                //Set file content
                TXTFile = FArgs.Files[0] as StorageFile;
                if (Value == "")
                {
                    var Str = await TXTFile.OpenReadAsync();
                    ContentDialog ED2 = FileSaveDialog;
                    ED2.PrimaryButtonClick += ED2_PrimaryButtonClick;
                    void ED2_PrimaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Save the file if it isn't saved
                        Save();
                    }
                    ED2.SecondaryButtonClick += ED2_SecondaryButtonClick;
                    void ED2_SecondaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Don't save the file
                        //Set document content
                        REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                        RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                        Str.Dispose();
                    }
                    ED2.CloseButtonClick += ED2_CloseButtonClick;
                    void ED2_CloseButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
                    {
                        //Cancel the action
                    }
                    await ED2.ShowAsync();
                    Str.Dispose();
                }
                else
                {
                    //Set document content
                    var Str = await TXTFile.OpenReadAsync();
                    REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                    RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
                    Str.Dispose();
                }
            }
        }
        else
        {
            //If there are no arguments, the file, and the RichEditBox should both remain empty
        }
    }

    public string GetText(RichEditBox RichEditor)
    {
        RichEditor.Document.GetText(TextGetOptions.FormatRtf, out string Text);
        var Range = RichEditor.Document.GetRange(0, Text.Length);
        Range.GetText(TextGetOptions.FormatRtf, out string Value);
        return Value;
    }

Note:

*

*the GetText method used is equivalent to RichEditBox.Document.GetText(TextGetOptions.FormatRtf, out string Value);

*REB is the main workspace for the user to type in

*RTB is the box that is compared with REB to see if the contents are saved or not (if the contents are saved, the GetText method should return their values equal)

Expected behavior:
If the app has a window active with text, the app should open a file on double click in a secondary window. Else, if the text is equal to "", the app should replace it with whatever is in the file.
Actual behavior:
The app overrides the text, crashes, makes windows randomly, or creates black windows that can only be killed with Task Manager or Visual Studio

A: I'm not sure what is the file type that you are using so I didn't check the text part. But I have to say that the way you are creating a new window is not correct. If you want to open a new window every time when you open a new file, you don't have to call Window.Current.Activate(); every time.  I've made a simple demo that you could check.
In App.xaml.cs:
   protected async override void OnFileActivated(FileActivatedEventArgs args)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == null)
        {
            // Create a Frame to act as the navigation context and navigate to the first page
            rootFrame = new Frame();
            // Place the frame in the current Window
            Window.Current.Content = rootFrame;

            rootFrame.Navigate(typeof(MainPage), args.Files);

            Window.Current.Activate();
        }
        else
        {
            AppWindow appWindow = await AppWindow.TryCreateAsync();

            Frame appWindowContentFrame = new Frame();
            appWindowContentFrame.Navigate(typeof(MainPage),args.Files);

            ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowContentFrame);

            await appWindow.TryShowAsync();
        }
    }

When you launch the app for the first time, you should go through the normal launch process. When the app is launched more than onetime, then you could create a new window with AppWindow.
In MainPage.cs
  protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        // this is the file you need
        var d = e.Parameter;
    }

You could try this code first to make sure that your window is created and shown correctly.


text:
Q: Gstreamer and QWidgets After reading this discussion: Draw on top of xoverlay using Qt I've ended up with this code:
class Player : public QGst::Ui::VideoWidget { ... }

void Player::play() {
  QGst::PipelinePtr pipeline = QGst::ElementFactory::make("playbin2").dynamicCast<QGst::Pipeline>();
  watchPipeline(pipeline);
  pipeline->setProperty("uri", "/path/to/my/video.mp4");
  QGst::BusPtr bus = pipeline->bus();
  bus->addSignalWatch();
  QGlib::connect(bus, "message", this, &Player::onBusMessage);
  pipeline->setState(QGst::StatePlaying);
}

So I have my video playing in this QWidget. Now I want to add another QWidget on top of this one to draw something or to place another QWidget with alpha blending. I tried this code in the main app:
Player *player = new Player(this);
QWidget *videoOverlay = new QWidget(player);
// set the videoOverlay geometry
videoOverlay->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
videoOverlay->setAttribute(Qt::WA_TranslucentBackground);

But I get a black opaque QWidget. There is no transparency at all.
What am I missing?

A: Try these:
videoOverlay->setAttribute(Qt::WA_NoBackground);
videoOverlay->setAttribute(Qt::WA_NoSystemBackground);
videoOverlay->setAutoFillbackground(false);

Or this:
videoOverlay->setAutoFillBackground(true);
videoOverlay->setAttribute(Qt::WA_PaintOnScreen);
videoOverlay->setBackgroundRole(QPalette::Window);
// make the widget transparent
QPalette transparent;
transparent.setColor(QPalette::Window, QColor(128,64,128)); // transparent color
videoOverlay->setPalette(transparent);

Third option:
videoOverlay->setAttribute(Qt::WA_TranslucentBackground);
videoOverlay->setStyleSheet("background:transparent;");

More information about how to make widgets transparent:

*

*http://www.qtcentre.org/threads/32310-Translucent-Qt-widget

*http://qt-project.org/forums/viewthread/3239


text:
Q: bootstrap datetimepicker retuns a string, how to convert this string into datetime (php) I have a bootstrap datetimepicker in a form with method POST.
In my Symfony2.7 application, I revover the $_POST['date'] like this:
$startDate = $this->get('request')->request->get('date');

I need this data to be a datetime, and only a datetime in order to use this in a doctrine dql. But when I make a var_dump($startDate); it returns me a string:
string '25/08/2015 00:00' (length=16)

Is there a way to convert this string into Datetime?
I try the method DateTime::createFromFormat but it retuns me false, of course because $startDate is a string.
There is my html code:

    <input type="datetime" class="form-control" id="startDate" name="date" required="required"/>

A: Using DateTime as instance might do the trick. Its constructor deal with the string format.
$datetime = new DateTime($startDate);
And, as you stated in comments, replace the slashes before it:
str_replace('/', '-', $startDate)


text:
Q: How to create one database object in another database's stored procedure? scenario is, I am having 2 database. db1 and db2. where as I have around more than 45 stored procedures in db2 which are having join with tables in db1. I could able to do by db1.dbo.tablename but since if I am renaming db1 to db3. All db2 stored procedures getting failed. What should approach? as per client requirement as usual he want to rename db1. By find replace in script db1 to db3 is not the good approach. because if client asks to rename again db3 databse to some another name , then it is permanent tedious and unprofessional work. What should I use here?

A: Create synonyms. Reference the synonyms in your objects. If the database changes, you just have to change one synonym per object. There's no avoiding changing the logical name in your code but if you control access through synonyms you only have to change it in one place.
For example
Without synonyms:
Six Stored Procedures in db2 refer to objects db1..Table1 and db1..Table2
When you rename db1 to db7, you need to alter two objects in six stored procedures.
With synonyms:
Six Stored Procedures refer to synonyms snTable1 and snTable2 (in the local database - note no database reference here)
The synonym snTable1 refers to db1.Table1
When you rename db1 to db7, you need to alter two synonyms to point at the new database. No changes to stored procedures are required. All objects referring to the synonyms will still work.
This requires you to create synonyms in db2 pointing at objects in db1, and an initial rewrite of your stored procedures in db2 to refer to local synonyms instead of database-qualified objects. But you need to do that anyway right?
Example Procedure

*

*Create a synonym in db2 called snTable1 that refers to Table1 in db1
USE db2
CREATE SYNONYM snTable1 FOR db1.Table1

*Alter your 45 stored procedures to refer to snTable1, not db1.Table1. You only have to do this once. Note these stored procedures are referring to objects in the local database.

*If your database gets renamed to xyz, recreate the synonym:
USE DB2
DROP SYNONYM snTable1
CREATE SYNONYM snTable1 FOR xyz.Table1
This is only useful if there are far more stored procedures/views than objects.
If you wish to change these on the fly you could probably use DMO or powershell or generate some T-SQL to do it. You just run the above commands against the database with a user that has suitable security.
Another very unpleasant option that may work is to create a linked server to your local database with a hard coded login whose default database is the database that you want. But it hides the user that is really accessing the object, and probably introduces performance issues. In short it's bad practice. I question why the database needs to be renamed so much. No end user should ever see it. If you take a look at Sharepoint databases they have hideous names but this is irrelevant to an end user.
Example linked server procedure

*

*Create a user that only has access to db1, and whose default database is db1

*Create a linked server (called MyLinkedServer for example) on the SQL Server to the local database using the user created in step 1

*Alter all your code in db2 to use four part naming through this linked server: SELECT * FROM MyLinkedServer...Table1

*If the database name changes, there are probably no changes required

This is just a theory and if it works its bad practice... worse practice than needing to rename your database.


text:
Q: How to open cmd when exec jar file (qt QProcess) I use Windows. I want to use QProcess in a running jar app (java/javaw). After starting that, open the cmd to show me information about working my jar app.
My problem is: when I exec my qt code, the Java app starts (in the background), but cmd doesn't open with the Java runtime.
My code:
QProcess process;
process.setWorkingDirectory("D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target");
process.setProgram("java.exe");
process.setArguments({"-jar","StackExp-1.0-SNAPSHOT.jar"});
process.start();
process.waitForFinished (-1);

if (!process.waitForStarted())
{
    qDebug() << "1: " +process.readAllStandardOutput();
    qDebug() << "2: " +process.readAllStandardError();
    qDebug() << "The process didnt start" << process.error();
}

My jar app built in maven and it has type: Java Application.
I use java.exe and javaw.exe, both runtimes don't open cmd.
How can I exec jar app with QProcess or otherwise, and at the same time open cmd for see information about working jar app?

A: You can use system() command to run visible command prompt window. Replace you code with a oneliner:
system(QString("java.exe -jar D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target\\StackExp-1.0-SNAPSHOT.jar").toStdString().c_str());

If you see just a flashing of the window you can add timeout call after your java call as follows to figure out what went wrong with the java call:
system(QString("java.exe -jar D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target\\StackExp-1.0-SNAPSHOT.jar & TIMEOUT 5").toStdString().c_str());

Note that system() call blocks until it returns.
If you want to keep the handle to the process you need to use QProcess. You can run command prompt as follows but you don't see it as a separate console window but it runs in the background. You can see it in task manager as command prompt process though.
QProcess process;
process.setWorkingDirectory("D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target");
process.setProgram("cmd.exe");
process.setArguments({"/c", "java.exe -jar StackExp-1.0-SNAPSHOT.jar"});
process.start();
process.waitForFinished();
qDebug() << "1: " +process.readAllStandardOutput();
qDebug() << "2: " +process.readAllStandardError();

Update:
It seems you can spawn a foreground console window by setting custom flags to the process with QProcess::setCreateProcessArgumentModifier as follows:
process.setCreateProcessArgumentsModifier(
            [](QProcess::CreateProcessArguments *args) {
    args->flags |= CREATE_NEW_CONSOLE;
    args->startupInfo->dwFlags &=~ STARTF_USESTDHANDLES;
});

Tested with ping command:
#include <windows.h>

QProcess process;
process.setProgram("cmd.exe");
process.setArguments({"/c", "ping 127.0.0.1"});
process.setCreateProcessArgumentsModifier(
            [](QProcess::CreateProcessArguments *args) {
    args->flags |= CREATE_NEW_CONSOLE;
    args->startupInfo->dwFlags &=~ STARTF_USESTDHANDLES;
});
process.start();
process.waitForFinished();


text:
Q: split different length column values to new columns/features I have a dataframe that looks like this
The f in the data set below coould be anything alphenumeric word i.e f=[A-z]+
                 flags       perf
1   -f1 -arm -loop -f12=2.5  100
2                  -f1 -f44  45
3         -f12=1.89 -f1 -fA  450
4            -stkDump -fA56  590

each item in flags column is a string. I want to transform this data frame to something like this: some flags can have a range of values e.g f12 in the above example and others are just on/off flags.
  f1 arm loop  f12  f44  fA stkDump fA56 perf
1  1  1  1     2.50   0  0   0       0  100
2  1  0  0     0.00   1  0   0       0  203
3  1  0  0     1.89   0  1   0       0   45
4  0  0  0     0.00   0  0   1       1  590

I'll be thankful if anyone can help, Please !

A: Using R and tidyverse; the main trick is using tidyr::separate_rows to transfer flags into one column and many rows based on space, then use stringr::str_extract to extract the important information before transfer back into wide format.
library(dplyr)
library(stringr)
library(tdiyr)
df %>%
   rownames_to_column(var="id_row")  %>%
   separate_rows(flags,sep = '\\s') %>%
   mutate(val=str_extract(flags,'\\d+\\.\\d+'), key=str_extract(flags,'f[0-9A-z]+')) %>%
   mutate(val=ifelse(is.na(val),1,val)) %>%
   dplyr::select(-flags) %>% spread(key, val, fill = 0)

    id_row perf f1  f12 f2 f44 f9 fA fA56 fAe
  1      1  100  1  2.5  1   0  1  0    0   0
  2      2   45  1    0  0   1  0  0    0   0
  3      3  450  1 1.89  0   0  0  1    0   0
  4      4  590  0    0  0   0  0  0    1   1

Data
df <- read.table(text ="
                   flags perf
  1   '-f1 -f2 -f9 -f12=2.5'  100
                   2               '-f1 -f44'   45
                   3      '-f12=1.89 -f1 -fA'  450
                   4            '-fAe -fA56'  590
                   ",header = TRUE, stringsAsFactors = FALSE)


text:
Q: Fragment not disappearing when I press back I'm having an issue with my code in which I have a list of "Places" in a list fragment, I am selecting a Place and it is displaying a new fragment with that places details. I then click edit and it brings up a new fragment in which I can edit the details. After I click save, it goes to the details fragment but displays the new details. In all of these transitions to new fragments I add the previous fragment to the back stack so if I press back at any point it goes back and all of this works fine except if I press back after I've saved some new details, it displays the list of places but the new details fragment hasn't disappeared. Any ideas where I could be going wrong?
I've added code in button clicks and list fragment clicks that relates to fragment transitions as I think that is the only code relevant but if more is needed please let me know.
This piece is for when I select the Place from the list:
public void onListFragmentInteraction(Place place, Integer position) {

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    //replace the fragment currently in fragment container with the new details fragment.
    transaction.replace(R.id.fragment_container, details);
    //add the transaction to the back of the stack so the back button navigates back to list fragment
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit();
}

This part is where I click the edit details floating button:
FloatingActionButton fab = view.findViewById(R.id.editPlace);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            //replace the fragment currently in fragment container with the new update fragment.
            transaction.replace(R.id.fragment_container, updatePlaceFragment);
            //add the transaction to the back of the stack so the back button navigates back to list fragment
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    });

And this part is where I click save and afterwards I press the back button to go back to the list and where my problem is occuring:
Button save = (Button) view.findViewById(R.id.updateNewPlace);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            FragmentManager manager = getFragmentManager();
            manager.popBackStack();
            manager.popBackStack();

            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            //replace the fragment currently in fragment container with the new update fragment.
            transaction.replace(R.id.fragment_container, placeDetails);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

I've been looking online for hours for solutions and I just can't work it out so any help would be greatly appreciated. Thanks.
EDIT
Just to clarify what fragments each interaction method is performed in:
The first is performed when an item in the list fragment is selected.
The second is held in the PlaceDetails fragment and clicking it takes you to a UpdatePlaceFragment fragment. The third button to save is held in UpdatePlaceFragment and is supposed to take you to PlaceDetails with the new details. Pressing back should then take you back to the list fragment, it does but the PlaceDetails is still visible. Strangely, if I select an item in the list and press back right away without editing, it goes to the list and the PlaceDetails fragment disappears.
EDIT 2:
I've updated the save button with the fixed code. Needed to add to the back stack and popBackStack twice. Thanks for the help!


text:
Q: Checkbox JavaScript does not update values I have a table with rows of textboxes as inputs that hold numbers/hours with css .hours. I am trying to get the table to update totals when the row is deleted checkbox is checked/clicked.
How to Update the totals in the row & col at the End? when the delete row checkbox is checked.
2 steps: I zero out the values in the deleted row, and then want to update the new totals.
JS fiddle with HTML

 // Call this function, When CheckBox with css .deleteRowis clicked
 $('#Maintable').on('click', '.deleteRow', function ()
    {
        if ($(this).is(":checked")) {
            var row = $(this).closest('tr').css({ 'color': 'red' });
            var hours = row.find('.hours');

            $.each(hours, function (index, item) {
                if ($(this).val()) {  // if there is a value
                    $(this).val('0');
                    // Total the rows does not work??
                    HoursChangedFunction($(this));
                }
            });
        } // :checked ends

  // when the row is deleted from the checkbox, find it and call this function
  // 1) First make all .hours 0, 2) and then redo the totals
  var HoursChangedFunction = function () {
        var columnIndex = $(this).closest('td').index();
        var row = $(this).closest('tr');
        var hours = row.find('.hours');
        var rowTotal = 0;
        $.each(hours, function (index, item) {
            rowTotal += Number($(this).val());
        });
        row.children('td.rowtotal').text(rowTotal.toFixed(2));
        var columnTotal = 0;
        var grandTotal = 0;
        var rows = $('#Maintable tr');
        $.each(rows, function (index, item) {
            columnTotal += Number($(this).children('td').eq(columnIndex).children('.hours').val());
            grandTotal += Number($(this).children('.rowtotal').text());
        });
        footer.eq(columnIndex).text(columnTotal.toFixed(2));
        total.text(grandTotal.toFixed(2));
    };

A: Because you have a lot of IDs you may avoid HoursChangedFunction.
In order to get the corresponding cell in the current col you can use the eq method
Moreover, you can use .text( function ) to simplify the task.
You can simplify the event handler from:
$('#Maintable').on('click', '.deleteRow', function ()

to:
$('#Maintable').on('change', '.deleteRow:checked', function () {

because inside the handler you execute the logic only when the checkbox is checked.
The snippet:

$('#Maintable').on('change', '.deleteRow:checked', function () {
    var row = $(this).closest('tr').css({'color': 'red'});

    $('#grandtotal').text(function(idx, txt) {
        return (+txt - +row.find('.rowtotal').text()).toFixed(2);
    });
    row.find('.rowtotal').text('0.00');

    row.find('.hours').each( function (index, item) {
        if (item.value != '0.00') {
            $('#Maintable').closest('table').find('tfoot tr td').eq(index + 2).text(function(idx, txt) {
                return (+txt - +item.value).toFixed(2);
            });
            item.value = '0.00';
        }
    });
});
.hours {
  width: 50px;
  box-sizing: border-box;
  border: solid 1px #d9e1e4;
}

        Task
        Code
        day1
        day2
        dy3
        day4
        day5
        day6
        day7
        Total
        Del

            Project 1

            code 1A

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="2.50">

            <input class="hours" type="text" value="4.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

        6.50

        <input class="bs-checkbox deleteRow" data-val="true" type="checkbox" value="true">

            Project 2

            <input type="hidden" name="Records.Index" value="1">
            code 2B

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="4.50">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

        4.50

        <input class="bs-checkbox deleteRow" data-val="true" type="checkbox" value="true">

            Project 3

            code 2C

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.50">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" ype="text" value="0.00">

            <input class="hours" type="text" value="0.00">

            <input class="hours" type="text" value="0.00">

        0.50

        <input class="bs-checkbox  deleteRow" data-val="true" type="checkbox" value="true">

        0.00
        7.50
        4.00
        0.00
        0.00
        0.00
        0.00
        11.50


text:
Q: add color to a cursor: url("data:image) How do I add a color to an SVG cursor in the existing CSS
html {
    cursor: url("data:image/svg+xml,%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='32px' height='32px' viewBox='0 0 512 512' style='enable-background:new 0 0 512 512;' xml:space='preserve'%3E %3Cpath d='M127 64A63 63 0 0 1 64 127 63 63 0 0 1 1 64 63 63 0 0 1 64 1 63 63 0 0 1 127 64Z'/%3E %3C/svg%3E"), pointer;

}

A: add fill attribute to fill='red'
html { cursor: url("data:image/svg+xml,%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='32px' height='32px' viewBox='0 0 512 512' style='enable-background:new 0 0 512 512;' xml:space='preserve'%3E %3Cpath fill='red' d='M127 64A63 63 0 0 1 64 127 63 63 0 0 1 1 64 63 63 0 0 1 64 1 63 63 0 0 1 127 64Z'/%3E %3C/svg%3E"), pointer;

}

A: Add fill attribute. but make sure use single quote when give fill attribute.

html { cursor: url("data:image/svg+xml,%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='32px' height='32px' viewBox='0 0 512 512' fill='red' style='enable-background:new 0 0 512 512;' xml:space='preserve'%3E %3Cpath d='M127 64A63 63 0 0 1 64 127 63 63 0 0 1 1 64 63 63 0 0 1 64 1 63 63 0 0 1 127 64Z'/%3E %3C/svg%3E"), pointer;

}


text:
Q: A php platform install ask me intl extension, but it seems already installed During orocrm installation (a platform developed with symfony 2) I receive this error
Fatal error: Uncaught exception 'Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException' with message 'The   Symfony\Component\Intl\Collator\Collator::__construct() method's argument $locale value 'fr_FR' behavior   is not implemented. Only the locale "en" is supported.  Please install the "intl" extension for full    localization capabilities.' in /Users/ale/Sites/educacloud-  bo/vendor/symfony/symfony/src/Symfony/Component/Intl/Collator/Collator.php:80
Stack trace:
#0 /Users/ale/Sites/educacloud-bo/app/SymfonyRequirements.php(619):   Symfony\Component\Intl\Collator\Collator->__construct('fr_FR')
#1 /Users/ale/Sites/educacloud-bo/app/OroRequirements.php(24): SymfonyRequirements->__construct()
#2 /Users/ale/Sites/educacloud-bo/app/oro-check.php(6): OroRequirements->__construct()
#3 {main}
thrown in /Users/ale/Sites/educacloud-bo/vendor/symfony/symfony/src/Symfony/Component/Intl/Collator/Collator.php on line 80

but I have installed intl extension:
# php -i | grep intl
 /usr/local/php5/php.d/50-extension-intl.ini,
 intl
 intl.default_locale => it_IT => it_IT
 intl.error_level => 0 => 0

and php_info() on my browser give me these results:
version 1.1.0
ICU version 4.6
ICU Data version    4.6

What is the problem?
thanks
Alessandra

A: By default, symfony2 is able to manage the "en" extension but to get other language, you have to install the php-intl extension.
The easiest option is to install it with the composer, because it expose global variable for you ... etc
All of this is explained here symfony/components/intl.
For the composer extension installation it's symfony/components/using_components.
So after eading this, you need to execute :
composer require symfony/intl

-- EDIT
Ok, I'm sorry, I've just test the solution, and the fact is : if you use the symfony component you have only access to "en". I have the same problem as you, my php5-intl extension was installed and activated but the error persisted. For me it was that I continue to write use Symfony\Component\Intl\DateFormatter\IntlDateFormatter; at the top of my file instead of using the basic php5 extension.

A: Do one thing that might be helpful for resolve this error
open php.ini file
remove comment from ;extension=php_intl.dll
extension=php_intl.dll

and restart the Apache server

A: You need re install package int1
apt-get install php-intl

service apache2 restart

A: Check solutions:
In Symfony 2.0:
app/config/config.yml
framework:
  session: { default_locale: it_IT }
In Symfony 2.1+:
app/config/config.yml
framework:
  default_locale: it_IT


text:
Q: Spring-boot: Servlet Environment being logged despite Log level Recently upgraded from Spring-Boot 1.5.6.RELEASE to 1.5.8.RELEASE
On doing so, we noticed the environment was being logged out as "DEBUG" and category "StandardServletEnvironment".
However, the application.properties file does not specify logging at DEBUG level. Even explicitly setting a level of warning or error for that class does not make a difference.
The code that is doing the logging is in the constructor of org.springframework.core.env.AbstractEnvironment:
public AbstractEnvironment() {
        customizePropertySources(this.propertySources);
        if (logger.isDebugEnabled()) {
            logger.debug("Initialized " + getClass().getSimpleName() + " with PropertySources " + this.propertySources);
        }
    }

Debug is not enabled, yet it logs. It seems as if it is doing this before it reads the log levels from application.properties.
Is there any explanation for this,  or a way around this?
The application.properties has:
logging.level.root=INFO
logging.level.com.mycompany=DEBUG

In the code, I see a comment about logging initialization being deferred.

A: I managed to suppress this error by creating my own WebApplicationInitializer class, in which I explicitly set the offending log-category to a log-level of INFO
class MyWebApplicationInitializer implements WebApplicationInitializer{
    @Override
    void onStartup(ServletContext servletContext) throws ServletException {

        String category = 'org.springframework.web.context.support.StandardServletEnvironment'

        ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(category)
        logbackLogger.setLevel(ch.qos.logback.classic.Level.INFO)
        logbackLogger.info("Setting log level in ${this.class.name}, for ${logbackLogger.name}, to ${logbackLogger.level}")
}

It feels like a hack. So, if someone has a better answer, please post.


text:
Q: How can I replace the auto keyword in this code? I am following this tutorial.  The following declaration found in main.cc has me intrigued:
auto say_hello = [](const HttpRequest& request) -> HttpResponse {
    HttpResponse response(HttpStatusCode::Ok);
    response.SetHeader("Content-Type", "text/plain");
    response.SetContent("Hello, world\n");
    return response;
}

This is shown in the debugging window.
I wish to replace the auto keyword with the original data type.  I have tried the following but it fails:
HttpResponse say_hello = [](const HttpRequest& request) -> HttpResponse {...}

Could someone tell me why it is wrong?  What is the correct solution?  Thank you so much!!!

A: I think it's important to know the 3 following methods when working with lambdas.
The three firsts do essentially the same thing: storing the lambda for future use.
The other seems to be what you expect from your code: you directly call the lambda and get the result, so the return type is the type returned by the lambda.
#include <iostream>
#include <functional>

int main()
{
    // Auto store the lambda
    auto auto_keyword = [](int a) -> int
    { return a; };
    std::cout << auto_keyword(42) << std::endl;

    // std::function store the lambda
    std::function<int(int)> std_function = [](int a) -> int
    { return a; };
    std::cout << std_function(42) << std::endl;

    // raw function pointer
    int (*raw_fptr)(int) = [](int a) -> int
    { return a; };
    std::cout << raw_fptr(42) << std::endl;

    // direct call to the lambda. (what you expect from your question)
    std::cout << ([](int a) -> int{ return a; })(42) << std::endl;

    return 0;
}

A lot of things happen here, and I suggest you to read at least this page from the reference for a better understanding.

A: Normally, a lambda expression is an anonymous function object and it doesn't have a named type. However, sometimes we can use type erasure. If a lambda expression doesn't capture any arguments like your example, it can convert to function pointer implicitly. If a lambda expression captures some arguments, it can convert to std::function.

A: According to cppreference, (emphasize mine)

The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type

As the type of a lambda expression is an unnamed type you cannot use it in a declaration. That is the reason why auto is the common usage for a lambda.
If you want to be more explicit for the arguments and return type, you can store the lambda in a std::function variable:
std::function<HttpResponse(const HttpRequest&)> say_hello = ...

But std::function is still not really the type of the lambda (which is unnamed...), it is just the type of a variable which is able to hold that lambda, as it could old the address of a plain function.

For further reference, draft n4860 for C++20 says at 7.5.5.1 Closure types [expr.prim.lambda.closure] §1

The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union
class type, called the closure type ...

A: From C++ standard

[C++11: 5.1.2/3]: The type of the lambda-expression (which is also the
type of the closure object) is a unique, unnamed non-union class type
— called the closure type — whose properties are described below. This
class type is not an aggregate (8.5.1). The closure type is declared
in the smallest block scope, class scope, or namespace scope that
contains the corresponding lambda-expression.

In short each instance of a lambda is its own unique unnamed type.

[C++11: 5.1.2/5]: The closure type for a lambda-expression has a
public inline function call operator (13.5.4) whose parameters and
return type are described by the lambda-expression's
parameter-declaration-clause and trailing-return-type respectively.

Since lambda has function call operator defined you can assign it to std::function

[C++11: 5.1.2/6]: The closure type for a lambda-expression with no
lambda-capture has a public non-virtual non-explicit const conversion
function to pointer to function having the same parameter and return
types as the closure type's function call operator. The value returned
by this conversion function shall be the address of a function that,
when invoked, has the same effect as invoking the closure type's
function call operator.

If the lambda does not capture anything it can be converted to a function pointer.


text:
Q: Estimating the $\chi^2$-divergence with Monte Carlo: which distribution to sample from? Notation: let the $\chi^2$-divergence between $p, q$ be defined as
$$\chi^2 (p||q) := \int \left ( \frac{p(x)}{q(x)} \right )^2 q(x)\mathrm{d}x  -1 =  \int \frac{p(x)}{q(x)}  p(x)\mathrm{d}x - 1.  $$
Suppose $q$ is a fully known prior distribution, and $p$ is a posterior distribution known up to a normalizing constant but its normalizing constant can be estimated with a reliable Monte Carlo estimator with finite variance. If it helps simplify the problem, assume exact iid samples can be drawn from both distributions.

*

*Which estimator would be less variable? A Monte Carlo estimator with samples from $q$, or samples from $p$?

*Suppose I have samples from both $p$ and $q$. Is there a method for leveraging both samples to produce a more stable estimator?

A: Given $x_1,\ldots,x_n\sim p(x)$ and $y_1,\ldots,y_m\sim q(x)$, the multiple mixture estimator of Owen and Zhou (2000) is
$$\hat\xi=\sum_{i=1}^n \left( \frac{p(x_i)^2}{q(x_i)}\right)\frac{1}{np(x_i)+mq(x_i)}+\sum_{i=1}^m \left( \frac{p(y_i)^2}{q(y_i)}\right)\frac{1}{np(y_i)+mq(y_i)} - 1$$
It is unbiased for $\chi^2(p||q)$ and by mixing both densities it brings stability to the importance weights.


text:
Q: Cleaning up json includes and usage I am importing data from json like this
import data from './data.json'

where data.json looks somewhat similar to this
{
  "data": [
    {"title": "Some title", "text": "Some text"},
    {"title": "Some title", "text": "Some text"},
    {"title": "Some title", "text": "Some text"}
  ]
}

so to use it in my file I'd usually do something like data.data[0].title which in my opinion is not the cleanest way, ideally I'd like to use it like data[0].title is there a way I can include or edit my json file to acheive this?

A: You can import {data} from './data.json. That will only import that data key from the object, and place it into a variable called data.


text:
Q: migration of clients, addresses and prestashop 1.7 orders I copied the complete folder of my prestashop 1.7.3.0 on a new folder on my server with new database, install a new theme and maj prestashop in 1.7.7.0
The concern is that now that I have finished in the meantime I have had orders and customers.
I imported the products in excel redone the variations by hand.
How can I subsequently export customers and orders?
In excel import of my last clients it tells me that the password is required for the import?
What would be the best method even going on phpmyadmin to import the customers, addresses and orders that I miss on the new store?
Thanks for your feedback.

A: To align customers and addresses you can use Prestashop's built-in CSV import feature.
Regarding orders there is no standard way to do it,
you have to perform queries on the new database synchronizing the missing data of the old one, taking care to check the various tables of the site because there are several entities involved (and structure might change between PS versions too).
Also keep in mind that there may be third party modules on the old site that save data and therefore must be synchronized.
Other options: you'll put "catalog mode" on the live store for a few days until you've finished the work on the new one or use a paid data migration module that can perform incremental migrations.


text:
Q: How to express two variables in two other variables If:
$A=R\cos x$ and $B=R\sin x$
Then how can I express $R$ and $x$ in terms of $A$ and $B$ in a rigorous way? Meaning that I take the domain and range in account?
I tried:
$$\cos x=\frac{A}{R}$$
$$x=\arccos\frac{A}{R}$$
Filling it in in the second equation gives:
$$B=R\sin\arccos\frac{A}{R}$$
$$B=R\sqrt{1-\frac{A^2}{R^2}}=\sqrt{R^2-A^2}$$
$$R=\sqrt{A^2+B^2}$$
Furthermore:
$$\frac{B}{A}=\frac{R\sin x}{R\cos x}=\tan x$$
Therefore:
$$x=\arctan\frac{B}{A}$$
However, I feel maybe this could be done in a more simple way, and also I am not sure whether this is rigorous when it comes to range and domains. Any help is appreciated!

A: You have a problem that $x$ and $R$ are not uniquely defined by $A$ and $B$. If you have a given $A$ and $B$, then for any valid $x$ and $R$ you also have
$$A=R\cos(x+2k\pi), \quad B=R\sin(x+2k\pi)$$
and
$$A=(-R)\cos(x+(2k+1)\pi), \quad B=(-R)\sin(x+(2k+1)\pi)$$
for $k\in\Bbb Z$.
So to get unique values of $x$ and $R$ you will need to set limits, such as
$$R\ge 0, \quad -\pi < x \le \pi$$
Even then, the pair $A=0,\ B=0$ will have infinitely many values of $x$. But other than that special case, with those restrictions each $A$ and $B$ will defined a unique $x$ and $R$.
Here is a simpler way to get the value of $x$. If $A\ne 0$ then $R \ne 0$, and
$$\begin{align}
\tan x &= \frac{\sin x}{\cos x} \\[2ex]
 &= \frac{R\sin x}{R\cos x} \\[2ex]
 &= \frac BA
\end{align}$$
But note that this does not work for $A=0$. Also note that this does not uniquely define $x$: for any such $x$ the values $x\pm\pi$ also satisfy the equation, so you get two such values of $x$. If one such $x$ is in the first quadrant then another valid $x$ is in the third quadrant, and if one such $x$ is in the second quadrant then another valid $x$ is in the fourth quadrant, and vice versa.
The usual solution to those problems is to avoid the arctangent function but to rather use the atan2 function. You can then uniquely define $x$ by
$$x=\operatorname{atan2}(B,A)$$
Note that some computer systems use $\operatorname{atan2}(A,B)$ instead.
You get the appropriate unique value of $R$ by
$$\begin{align}
\sqrt{A^2+B^2} &= \sqrt{(R\cos x)^2 + (R\sin x)^2} \\[2ex]
 &= \sqrt{R^2(\cos^2 x + \sin^2 x)} \\[2ex]
 &= \sqrt{R^2\cdot 1} \\[2ex]
 &= R
\end{align}$$
remembering that we restricted $R\ge 0$.
So the final answer is

$$x=\operatorname{atan2}(B,A)$$
  $$R=\sqrt{A^2+B^2}$$

This gives the unique $x,R$ that satisfy $-\pi<x\le\pi,\ R\ge 0$, with the sole exception of $A=0,\ B=0$ which would allow any value of $x$. But that solution always works.
If you do not like the atan2 function, the Wikipedia article on atan2 gives some other ways to express the same result, but those other ways are much more verbose.

A: Draw a right angle triangle with angle $x$ and hypotenuse of length 1. You will immediately see that $B^2 + A^2 = R^2$. Any number of trigonometric identities may then be used to express $x$.


text:
Q: Is there the way how to transform this kind of code into cycle for n-dimension? I have this code for n = 4
b_11 <- (1 / 2) * (wi[1] - wi[1] + 1); b_11
b_12 <- (1 / 2) * (wi[1] - wi[2] + 1); b_12
b_13 <- (1 / 2) * (wi[1] - wi[3] + 1); b_13
b_14 <- (1 / 2) * (wi[1] - wi[4] + 1); b_14

b_21 <- (1 / 2) * (wi[2] - wi[1] + 1); b_21
b_22 <- (1 / 2) * (wi[2] - wi[2] + 1); b_22
b_23 <- (1 / 2) * (wi[2] - wi[3] + 1); b_23
b_24 <- (1 / 2) * (wi[2] - wi[4] + 1); b_24

b_31 <- (1 / 2) * (wi[3] - wi[1] + 1); b_31
b_32 <- (1 / 2) * (wi[3] - wi[2] + 1); b_32
b_33 <- (1 / 2) * (wi[3] - wi[3] + 1); b_33
b_34 <- (1 / 2) * (wi[3] - wi[4] + 1); b_34

b_41 <- (1 / 2) * (wi[4] - wi[1] + 1); b_41
b_42 <- (1 / 2) * (wi[4] - wi[2] + 1); b_42
b_43 <- (1 / 2) * (wi[4] - wi[3] + 1); b_43
b_44 <- (1 / 2) * (wi[4] - wi[4] + 1); b_44

trB <- c(b_11, b_12, b_13, b_14,
         b_21, b_22, b_23, b_24,
         b_31, b_32, b_33, b_34,
         b_41, b_42, b_43, b_44)

Is there any way how to simplify (or make cycle) it for other cases, where n could be bigger than 4?
(wi[i] is a vector).
Formulas in case this helps:

A: This can be vectorised as:
set.seed(0)
wi <- runif(4)  #or whatever
0.5* (outer(wi,wi,"-")+1)

to produce a matrix. Now the code is independent of the length of wi. If you prefer the vector that you currently have, the output could be reshaped with:
c(t(0.5* (outer(wi,wi,"-")+1)))


text:
Q: Laravel Get products from multiple taxonomies I have 3 tables, products, taxonomies and product_taxonomy. The 3rd table is a pivot table that contains product_id and taxonomy_id, meaning that product and taxonomy are many to many relationship. Given a list of taxonomy ids, how can I get all the products that belong to these taxonomies? NOTE: I want to have the products result set being able to paginated or order by maybe it's price or something.

A: You need to create many-to-many relationship and that requires relationship methods like:
// Product Model
public function taxonomies()
{
    return $this->belongsToMany('Taxonomy');
}

// Taxonomy Model
public function products()
{
    return $this->belongsToMany('Product');
}

The query:
$listOfTaxonomyIds = [1,2,3];
$products = Product::whereHas('taxonomies', function($query) use ($listOfTaxonomyIds){
    $query->whereIn('taxonomy_id', $listOfTaxonomyIds);
})->get();


text:
Q: how to get json encode from render function in symfony2 I'm trying to work with ajax in symfony but is some hard for me. I have a form in twig where I get a value that I'm using for search a product in my database:
This is the form in twig:
<form id="myForm" method="post" action="{{ path('my_app_greeting') }}">

          <input id="name_id" name="name" type="text" class="form-control" placeholder="Buscar repuesto..." required />

              <button id="search-button" class="btn btn-default"             type="button">Buscar</button>

    </form>
This is my code using jquery in the same twig template for send the data with ajax:
$(document).ready(function(){
    $("#myForm").submit(function(){
    var value = $("#name_id").val();
    $.ajax({
        type: "POST",
        data: { productValue: value },
        url: "/ventas/test/ajax/"
    })
    .done(function(response){
        template = response;
        $('#output').html(template.content);
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        alert('Error : ' + errorThrown);
    });
    return false;
    });
});

Later I read about how symfony works with ajax and I thought the best solution for my "problem" is create a new twig template called "ajaxContent.html.twig" for example and do this with the controller:
public function testAction()
{
    $request  = $this->get('request');
    $name     = $request->request->get('productValue');
    $template = $this->renderView('AcmeDemoTwoBundle:Ventas:ajaxContent.html.twig', array('value' => $name));
    $json     = json_encode($template);
    $response = new Response($json, 200);
    $response->headers->set('Content-Type', 'application/json');
    return new Response($response);
}

Of this way later I want to put all the html content inside my original template but I have a problem with json encode. I don't understand very well how it works and how is the better way for receive the data and show it in the twig template. How can I do this? ( I tried to show the data using $('#output').html(template.content); but doesn't work).
Thanks for your help!

A: Your code in controller seems to be not good.
I mean if you want to return json then what for do you render html (not json) twig template? That's the first.
Then you can get json response by using JsonResponse instead of setting header for standard response.
I don't know what's happening in ajaxContent.html.twig, but I would do something like this:
public function testAction(Request $request)
{
    $name     = $request->get('productValue');
    $response = $this->get('my_response_sercive')->giveMeResponseForTestAction($name);

    return new JsonResponse($response);
}

If you are waiting for html response in you javascript you have to set option dataType: 'html' for your ajax request.
Then in testAction you don't have to set 'application/json' header and don't have to json_encode $template variable - but just render your template as you are doing it now.
So in this case you could do something like this:
public function testAction(Request $request)
{
    $name     = $request->get('productValue');

    return $this->renderView('AcmeDemoTwoBundle:Ventas:ajaxContent.html.twig', array('value' => $name));
}

After that you can put html into your #output block directly:
$('#output').html(response);

A: You should use form array first for your problem try this
$template['content']


text:
Q: javascript objects sorting by array Is there a way to sort array of objects in structure like:
var objs = [{
    "name": "B",
    "value": 1
}, {
    "name": "D",
    "value": "45"
}, {
    "name": "E",
    "value": "234"
}, {
    "name": "A",
    "value": "543"
}, {
    "name": "C",
    "value": "250"
}, {
    "name": "B",
    "value": 6
}, {
    "name": "D",
    "value": "234"
}, {
    "name": "E",
    "value": "67"
}, {
    "name": "A",
    "value": "78"
}, {
    "name": "C",
    "value": "12"
}];

by the elements in another array:
var orderedArray = ["E", "C", "B", "A", "D"];

in order to get structure like:
    {
            "name": "E",
            "value": "234"
        },
    {
            "name": "C",
            "value": "250"
        },
    {
            "name": "B",
            "value": 1
        },
{
        "name": "A",
        "value": "543"
    },
{
        "name": "D",
        "value": "45"
    },
{
        "name": "E",
        "value": "67"
    },
{
        "name": "C",
        "value": "12"
    },
{
        "name": "B",
        "value": 6
    },
{
        "name": "A",
        "value": "78"
    },
{
        "name": "D",
        "value": "234"
    }

I'm trying with sort() function by index of name key:

var objs = [{ "name": "B", "value": 1 }, { "name": "D", "value": "45" }, { "name": "E", "value": "234" }, { "name": "A", "value": "543" }, { "name": "C", "value": "250" }, { "name": "B", "value": 6 }, { "name": "D", "value": "234" }, { "name": "E", "value": "67" }, { "name": "A", "value": "78" }, { "name": "C", "value": "12" }];

var orderedArray = ["E", "C", "B", "A", "D"];
var sorted = objs.sort((a, b) => orderedArray.indexOf(a.name) - orderedArray.indexOf(b.name));
console.log(sorted);

but the result isn't in the right order.
Example: jsfiddle

A: You could take a sorting with map and take the group and the order for getting a sequence sorting.

var array = [{ name: "B", value: 1 }, { name: "D", value: "45" }, { name: "E", value: "234" }, { name: "A", value: "543" }, { name: "C", value: "250" }, { name: "B", value: 6 }, { name: "D", value: "234" }, { name: "E", value: "67" }, { name: "A", value: "78" }, { name: "C", value: "12" }],
    order = ["E", "C", "B", "A", "D"],
    groups = Object.create(null),
    result = array
        .map((o, i) => ({ index: i, order: order.indexOf(o.name), group: groups[o.name] = (groups[o.name] || 0) + 1 }))
        .sort((a, b) => a.group - b.group || a.order - b.order)
        .map(({ index }) => array[index]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: How to migrate android app to ios (easy way?) I have some years experience as Java (specially) and Android developer, and I have an interesting Android app with more tan 10k downloads, so I am thinking to move app also to iOS, but I don´t know neither Objective C nor iOS programming in general (I have been making research but it seems hard...
Is there any easy way (don´t suggest Phonegap because it has some complicated logic behind)
to make an iOS app from my ANDROID SOURCE CODE?

A: I could try to use Java2ObjC. This tool could migrate Java code to Objective C. But this tool doesn't migrate UI, it is only for logic. It means that all UI related code you have to write manually.


text:
Q: Process gets killed automatically in Fedora I have a Automation process which is a java program running on fedora 6/14. A problem that I face very frequently is that this process is getting killed automatically. Ideally this process has been programmed to run at-least for 12-14 hours. But somewhere in between it gets killed. I have checked whether OOM Killer was the root cause, but there aren't any tracelogs in /var/log/messages to suggest that.
Any other bright ideas?

A: You need to capture the output and error output so you can see what's happening. If you're just running the program in the background, you could use redirection
program >out 2>errs &

Probably it's a memory leak, but you won't know for sure without capturing the errors.


text:
Q: How to define and manipulate Date variable in JavaScript? I need to use the Date object for three different purposes, can I do this as follows?
I am very new to JavaScript, so I am not sure if the following define is OK for all the browsers.
Date.prototype.yyyymmdd = function()
{
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth()+1).toString();
  var dd  = this.getDate().toString();
  return yyyy+"-" + (mm[1]?mm:"0"+mm[0])+"-" + (dd[1]?dd:"0"+dd[0]);

};

Date.prototype.mmddyyyy = function()
{
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth()+1).toString();
  var dd  = this.getDate().toString();

  return (mm[1]?mm:"0"+mm[0])+"-" + (dd[1]?dd:"0"+dd[0])+"-" + yyyy;
};

Date.prototype.mmdd = function()
{
   var yyyy = this.getFullYear().toString();
   var mm = (this.getMonth()+1).toString();
   var dd  = this.getDate().toString();
   return (mm[1]?mm:mm[0])+"/" + (dd[1]?dd:dd[0]);
};

var d0 = new Date();
console.log(d0.mmddyyyy);

var d1 = new Date();
console.log(d1.yyyymmdd);

var d2 = new Date();
console.log(d2.mmdd);

A: You just missed the brackets - it should run in any browser (but will currently fail if console is not supported or in IE8, open)
DEMO
var d0 = new Date();
console.log(d0.mmddyyyy());

var d1 = new Date();
console.log(d1.yyyymmdd());

var d2 = new Date();
console.log(d2.mmdd());

I would personally prefer one prototype
DEMO:
Date.prototype.formatDate=function(fmt) {
  fmt = fmt || "yyyymmdd";
  var yyyy = this.getFullYear();
  var mm = this.getMonth()+1;
  if (mm<10) mm="0"+mm;
  var dd  = this.getDate();
  if (dd<10) dd="0"+dd;
  if (fmt==="yyyymmdd") return yyyy+"-" + mm+"-" + dd;
  if (fmt==="mmddyyyy") return ""+mm+"-" + dd +"-" + yyyy;
  if (fmt==="mmdd")  return ""+mm+"/"+dd;
};

var d0 = new Date();
console.log(d0.formatDate("mmddyyyy"));
console.log(d0.formatDate("yyyymmdd"));
console.log(d0.formatDate("mmdd"));


text:
Q: Convert JObject to multi-dimensional array How do you convert a JObject to a 3D array? I have a JObject that is formatted as such:
{
  "0": [
    [
      1.0,
      2.0,
      3.0
    ],
    [
      4.0,
      5.0,
      6.0
    ]
  ],
  "1": [
    [
      7.0,
      8.0,
      9.0
    ],
    [
      10.0,
      11.0,
      12.0
    ]
  ]
}

I've tried casting it to a double[,,] but it fails with an error stating
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Double[,,]'.

A: The following works for me:
var deserailizationExp = JsonConvert.DeserializeObject<Dictionary<string, double[,]>>(@"
          {""0"": [
            [
              1.0,
              2.0,
              3.0
            ],
            [
              4.0,
              5.0,
              6.0
            ]
          ],
          ""1"": [
            [
              7.0,
              8.0,
              9.0
            ],
            [
              10.0,
              11.0,
              12.0
            ]
          ]
        }");

You could then either use the dictionary directly or transform it to an array. Edit: As pointed out in the comments on this, you could also consider deserializing this to the type SortedDictionary<int, double[,]>. I tested that as a type and it worked for me.
Alternatively, if you modify the JSON you can do the following:
var otherDes = JsonConvert.DeserializeObject<double[,,]>(@"
          [[
            [
              1.0,
              2.0,
              3.0
            ],
            [
              4.0,
              5.0,
              6.0
            ]
          ],
          [
            [
              7.0,
              8.0,
              9.0
            ],
            [
              10.0,
              11.0,
              12.0
            ]
          ]
        ]");

As you can see, I just removed "0" and "1" and replaced {} with []. If you have the ability to control how you're receiving the JSON somehow this would probably be the better solution in my opinion since it matches your requested type without having to do any further operations on it.

A: Json.NET expects a multidimensional array to be formatted like a 3d jagged array in the JSON file, however yours is formatted like a dictionary of 2d jagged arrays.  You can use a custom JsonConverter to convert JSON in such a format to a 3d array, like so:
public class Array3DConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        if (!objectType.IsArray)
            return false;
        return objectType.GetArrayRank() == 3;
    }

    object ReadJsonGeneric<T>(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        if (reader.TokenType == JsonToken.StartArray)
        {
            // Handle case when it's actually a 3d array in the JSON.
            var list = serializer.Deserialize<List<List<List<T>>>>(reader);
            return list.Select((l, i) => new KeyValuePair<int, List<List<T>>>(i, l)).To3DArray();
        }
        else if (reader.TokenType == JsonToken.StartObject)
        {
            // Handle case when it's a dictionary of key/value pairs.
            var dictionary = serializer.Deserialize<SortedDictionary<int, List<List<T>>>>(reader);
            return dictionary.To3DArray();
        }
        else
        {
            throw new JsonSerializationException("Invalid reader.TokenType " + reader.TokenType);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        try
        {
            var elementType = objectType.GetElementType();
            var method = GetType().GetMethod("ReadJsonGeneric", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            return method.MakeGenericMethod(new[] { elementType }).Invoke(this, new object[] { reader, objectType, existingValue, serializer });
        }
        catch (TargetInvocationException ex)
        {
            // Wrap the TargetInvocationException in a JsonSerializerException
            throw new JsonSerializationException("Failed to deserialize " + objectType, ex);
        }
    }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

public static class EnumerableExtensions
{
    public static T[,,] To3DArray<T>(this IEnumerable<KeyValuePair<int, List<List<T>>>> jaggedArray)
    {
        if (jaggedArray == null)
            throw new ArgumentNullException("jaggedArray");
        var counts = new int[3];
        foreach (var pair in jaggedArray)
        {
            var i = pair.Key;
            counts[0] = Math.Max(i + 1, counts[0]);
            if (pair.Value == null)
                continue;
            var jCount = pair.Value.Count;
            counts[1] = Math.Max(jCount, counts[1]);
            for (int j = 0; j < jCount; j++)
            {
                if (pair.Value[j] == null)
                    continue;
                var kCount = pair.Value[j].Count;
                counts[2] = Math.Max(kCount, counts[2]);
            }
        }
        var array = new T[counts[0], counts[1], counts[2]];
        foreach (var pair in jaggedArray)
        {
            var i = pair.Key;
            if (pair.Value == null)
                continue;
            var jCount = pair.Value.Count;
            for (int j = 0; j < jCount; j++)
            {
                if (pair.Value[j] == null)
                    continue;
                var kCount = pair.Value[j].Count;
                for (int k = 0; k < kCount; k++)
                    array[i, j, k] = pair.Value[j][k];
            }
        }
        return array;
    }
}

Then use it like:
var array = JsonConvert.DeserializeObject<double[, ,]>(jsonString, new JsonSerializerSettings { Converters = new[] { new Array3DConverter() } });

Or, if you have already parsed your JSON string into a JObject, you can use JToken.ToObject<T>(JsonSerializer) to deserialize to your desired type using your converter:
var array = jObj.ToObject<double[, ,]>(JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new[] { new Array3DConverter() } }));

For flexibility in use, the converter tests to see whether the incoming JSON is formatted as an object or array and responds appropriately.
Note - only lightly tested.


text:
Q: What's the point of the axiom of extensionality? The axiom of extensionality is:

${\forall}a({\forall}b({\forall}c(((c{\in}a){\iff}(c{\in}b)){\iff}(a=b))))$

The definition of $(P{\iff}Q)$ is:

${\lnot}((P{\implies}Q){\implies}({\lnot}(Q{\implies}P)))$

or, in other words

$(P{\land}Q){\lor}({\lnot}P{\land}{\lnot}Q)$

In the case of the statement $((c{\in}a){\iff}(c{\in}b))$, this leads us to two options: $((c{\in}a){\land}(c{\in}b))$ and $({\lnot}(c{\in}a){\land}{\lnot}(c{\in}b))$. So far nothing weird.
Now, let's see all the possible results of the axiom.

1.$((c{\in}a){\land}(c{\in}b)){\land}(a=b)$
2.${\lnot}((c{\in}a){\land}(c{\in}b)){\land}{\lnot}(a=b)$
3.$({\lnot}(c{\in}a){\land}{\lnot}(c{\in}b)){\land}(a=b)$
4.${\lnot}({\lnot}(c{\in}a){\land}{\lnot}(c{\in}b)){\land}{\lnot}(a=b)$

Coincidentally, they are also all possible statements regarding the statements $((c{\in}a){\land}(c{\in}b))$ and $(a=b)$: both parts are true, the first part is true and the other is false, the second part is true and the first is false and neither is true. The axiom seems not to state anything new, because rephrased it's just produces a list of all possible options regarding the two parts of the statement. Worse, it doesn't seem to say anything about equality, since it allows for $a=b$ with both $(c{\in}a){\land}(c{\in}b)$ and ${\lnot}((c{\in}a){\land}(c{\in}b))$.
So, what is the point of this axiom? And in what way does it say anything about equality?

A: You are misunderstanding the point of extensionality: its purpose is basically to help us prove that sets are equal. With Extensionality, if I can prove that A and B have the same elements, then I've proved that A=B. Without Extensionality, you could have two sets which are not equal but which have the same elements.
Put another way, Extensionality says that a set is determined by its elements. That may seem obvious; if so, great! The axiom is what codified this 'obvious' fact. (Also note that there are interesting set theories which reject Extensionality - it's not obviously true in all contexts!)

A: If you read Frege's papers, you will find him to be critical of intensional logicians.  By contrast Frege's logic had as its ground of truth an extensional semantics.  This is why Frege so adamantly distinguished between a
concept and the extension of a concept.  The original distinction between intension and extension is order-theoretic.  Aristotelian term logic semantics is extensional - arising with respect to a correspondence theory of truth based on individuals.  So, a "whole" class has as least as many individuals as its "parts" (fish are a part of the class of animals).  Leibniz inverted this sense of the part-whole relation to its converse ordering.  Hence Leibnizian logic is the intensional logic that Frege had been criticizing (although he had been motivated by Leibniz in other ways).
A problem that Frege ran into is that a function can be described in a multiplicity of ways.  The expression $x^2$ is not the expression $x*x$ even though they are "the same".  The modern notion of intension is characterized by this diversity of grammatical forms.  Extensionality is precisely how mathematicians may speak of different grammatical forms as being the same.
Now, as has been observed in the comments, you have not written the axiom of extensionality in the form of the received paradigm.  Because of Skolem's criticism of Zermelo in the first half of the twentieth century, set theory defers the account of identity to first-order predicate logic.  That is, set
theory is "just another theory" according to this view.  And, predicate logic only needs to interpret the sign of equality with respect to substitutability.  It does not warrant the uses of identity.  The direction of your biconditional with the identity statement as the antecedent is an instantiation of Leibniz' indiscernibility of identicals.  This is considered part of first-order predicate logic.  The direction of your biconditional with the identity statement as the consequent is the warrant for using identity statements within the theory.  It is only that direction which is the axiom of extension under the received paradigm.
At the heart of this division is what is called the ontological view of identity.  It is often attributed to an author named Wittgenstein.  Since it is conceivable that two objects which are not the same will satisfy every available predicate, except for those involving names, one may not be able to depend upon warranting to determine an individual.  So warranted identity is not part of the standard account for first-order predicate logic.


text:
Q: Valid C code doesn't work in Swift project I have code:
#define SOCK_PATH "/Users/piotr/swigo.sock"

int ux_server_socket() {
    const int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1) {
        printf("%s\n", strerror(errno));
        return -1;
    }
    struct sockaddr_un addr;
    bzero(&addr, sizeof(addr));
    addr.sun_len = sizeof(addr);
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, SOCK_PATH);

    if (unlink(addr.sun_path) == -1) {
        printf("unlink: %s\n", strerror(errno));
    }

    int retv = bind(fd, (struct sockaddr*)&addr, (socklen_t)SUN_LEN(&addr));
    if (retv == -1) {
        printf("bind: %s\n", strerror(errno));
        return -1;
    }

    printf("valid socket: %d\n", fd);
    return fd;
}

When I create a project in C language in Xcode, this code works without any problems (in the console appears: valid socket: 3). However, when I create a project in Swift (Cocoa App), I added a C file to the project with this function (and the appropriate file h and bridge header too) something does not work.
I see messages in the console:
unlink: Operation not permitted
bind: Address already in use

Why doesn't this valid C code work in a Swift project — any ideas?

A: It was the problem with sandbox, the valid solution is idea of Ken Thomases in another task, i needed to set two checkboxes (App Sandbox, Network: Incoming Connections (Server) and Outgoing Connections (Client)):

see: Creating and binding socket on Mac OS Hight Sierra


text:
Q: Using Docusign Connect with multiple environments I am running into conflicts using Docusign connect with multiple environments.
My Sandbox account is being used by Staging, Review apps & Dev environments. Docusign Connect is sending out envelope-events to environments that have not created the envelope which is causing lots of confusion.
This must be a common issue - is there a recommended way of handling it?

The only work-around I can think of is to add an sending_environment custom field with each envelope and then filter out the envelope-events when they are sent to each environment.
Thanks

A: Yes, using custom fields is a good approach.
I assume when you say "multiple environments" you mean your company/app/IT etc. not DocuSign's.
If it was DocuSign's (demo/sandbox vs. production) you could tell based on many things, account number, envelope ID, URL etc.
in any event, putting a text field that you can retrieve on the other end is a good way to handle this.
What I think you can also do, is have a different DocuSign configuration for each of your environments, such that they use different URLs for the callback from DocuSign. That approach may be more or less work than the other approach. Your call.

A: The solution we have gone for:

*

*Each Dev sets up their own 'user' account (invited via the docusign account dashboard)

*Devs use their credentials locally

*Staging & Review apps use the default sandbox docusign user account

*Production uses the default production docusign user account

Once this is done, we set up a permissions check on each envelope event that arrives, ensuring the user <Email> field matches that of the current environment
    <?xml version="1.0" encoding="utf-8"?>
    <DocuSignEnvelopeInformation>
      <EnvelopeStatus>
        <TimeGenerated>2020-05-18T12:00:00</TimeGenerated>
        <EnvelopeID>abcdef</EnvelopeID>
        <Email>me@gmail.com</Email>
      </EnvelopeStatus>
    </DocuSignEnvelopeInformation>

This ensures Dev environments don't conflict with staging & review apps.

Next we need a way of distinguishing Staging and each Review app. For this we add a <CustomField> to each envelope that we create, and in Staging & Review app environments, add an additional check for that custom field to filter out any envelopes that were not created in the current environment.


text:
Q: How to integrate rest Api with Magento Hello I have Third Party REST API And I want to integrate that REST API with my Magento Project
so, is that Possible in Magento??
And If Yes then how to integrate it in my Magento Project
Please Help......
Thank in advance

A: Yes,
Magento has a REST API, more usually with Soap Client.
Some examples: http://www.magentocommerce.com/api/soap/introduction.html
Try to use last version (V2) of integration and get attention for examples that is for V2 Magento API.
First you need to create user to consume this API:
Magento Admin -> System -> Web Service -> SOAP/XML Users
and create your user for get api integration functionality.