text:
Q: Maximum increase of a function along a surface I'm not quite sure how to approach this question - it's a practice problem, and there is no answer key. Someone told me the answer was to project the gradient onto the surface, but I'm not sure how to do this since using the projection formula with the normal would project it onto the normal. I'm also not sure how this works for the question. I'd really appreciate any insight!

A: As  the increase of a function in a direction is given its derivative in that direction, one wants to look for the direction of extremal increase of such derivative. However, since we are in a surface we are only interested of the extremal value for directions tangent to the surface (as they come from curves in the surface). Now,
(i) The directional derivatives of $T$ are (in our point)
$$
dT(x,y,z)(u,v,w)=(y,x,-2z)(u,v,w)^t=(-1,0,-2)(u,v,w)^t=-u-2w.
$$
(ii) The tangent space to our surface in the point is given by (with some loosy notation)
$$
d[z^3+zx+y^2-2](u,v,w)=(z,2y,x+3z^2)(u,v,w)^t=(1,-2,3)(u,v,w)^t=u-2v+3w=0.
$$
Now to look for extrema we restrict to the compact set $u^2+v^2+w^2=1$ and we have a Lagrange multipliers problem in the three variables $(u,v,w)$:
(iii) find the critical points of $h=-u-2w$ with the conditions $f_1=u-2v+3w=0$, $f_2=u^2+v^2+w^2-1=0$.
Quickly, Lagrange says that $\nabla h$ must depend on $\nabla f_1,\nabla f_2$, or in other words, the $3\times 3$ matrix $(\nabla h,\nabla f_1,\nabla f_2)$ must have $\det=0$, that is
$$
0=\det\begin{pmatrix}-1&0&-2\\1&-2&3\\2u&2v&2w
\end{pmatrix}=4w-8u+2v.
$$
Consequently, the direction to give the ant is the solution of the system
$$
-8u+2v+4w=u-2v+3w=u^2+v^2+w^2-1=0.
$$
Since norm 1 is not a condition, only the two first equations matter, and we obtain $(u,v,w)=(1,2,1)$. This gives negative increase, and $(-1,-2,-1)$ positive increase, both maximal in absolute value.


text:
Q: SQL Server and intermediate materialization? After reading this interesting article about intermediate materialization - I still have some questions.
I have this query :
SELECT    *
FROM  ...
WHERE       isnumeric(MyCol)=1  and ( CAST( MyCol AS int)>1)

However, the where clause order is not deterministic.
So I might get exception here.( if he first tries to cast "k1k1" )
I assume this will solve the problem
SELECT MyCol
FROM
    (SELECT TOP 100 PERCENT foo From MyTable WHERE ISNUMERIC (MyCol ) > 1 ORDER BY MyCol ) bar
WHERE
    CAST(MyCol AS int) > 100

*

*why does putting top 100 + order will change VS my regular query ?

I read in the comments  :

(the "intermediate" result -- in other words, a result obtained during
  the process, that will be used to calculate the final result) will be
  physically stored ("materialized") in TempDB and used from there for
  the remainder of the user, instead of being queried back from the base
  tables.

*

*what difference does it makes if it is stored in tempDB or queried back from the base tables? it is the same data !

A: The supported way to avoid errors due to the optimizer reorganizing things is to use CASE:
SELECT *
FROM YourTable
WHERE
    1 <=
    CASE
        WHEN aa NOT LIKE '%[^0-9]%'
        THEN CONVERT(int, aa)
        ELSE 0
    END;

Intermediate materialization is not a supported technique, so it should only be employed by very expert users in special circumstances where the risks are understood and accepted.
TOP 100 PERCENT is generally ignored by the optimizer in SQL Server 2005 onward.

A: By adding the TOP clause into the inner query, you're forcing SQL Server to run that query first before it runs the outer query - thereby discarding all rows for which ISNUMERIC returns false.
Without the TOP clause, the optimiser can rewrite the query to be the same as your first query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I implement an offline geocoder for a single city using OSM data in android? I am trying to develop an offline android map that makes use of OSM map tiles of a particular zoom level, For this purpose I used an open source library : Osmdroid
Now, I am looking into the possibility of creating an offline geocoding/ reverse geocoding for a single city that can be integrated with my application,
can I use Osm xml data for that purpose? if so , then can anyone suggest/explain how to use it to create SQlite db.. to be used with my app
I read here and also here about Spatialite
But cannot quite understand its working and implementation
Thanks

A: With the Skobbler SDK you have offline maps and (reverse) geocoding.

A: This has an answer in here
https://stackoverflow.com/a/64811929/13794189
and goes as follows:
To use Open Street Maps (OSM) in offline mode you need to first implement a download manager like the one shown here on the post liked bellow. It has resume capabilities which is good for very large files :
https://stackoverflow.com/a/64811752/13794189
next you can load the downloaded OSM maps file in to a mapView like this:
     org.osmdroid.config.IConfigurationProvider osmConf = org.osmdroid.config.Configuration.getInstance();
    File basePath = new File(SessionData.offlineMapsDirectoryPath, "osmdroid");
    osmConf.setOsmdroidBasePath(basePath);
    File tileCache = new File(SessionData.offlineMapsDirectoryPath, "tile");
    osmConf.setOsmdroidTileCache(tileCache);

    map = (MapView) getActivity().findViewById(R.id.map);  // create basic map
    //map.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
    map.setTilesScaledToDpi(true);
    map.setMultiTouchControls(true);
    map.setUseDataConnection(false);

    // add compass to map
    //CompassOverlay compassOverlay = new CompassOverlay(getActivity(), new InternalCompassOrientationProvider(getActivity()), map);
    //compassOverlay.enableCompass();
    //map.getOverlays().add(compassOverlay);

    //attach listeners
    MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this);
    map.getOverlays().add(0, mapEventsOverlay);

In the code above, SessionData.offlineMapsDirectoryPath is the path where the downloaded file is saved.
Don't forget to add in your gradle file the following implementations:
implementation 'org.osmdroid:osmdroid-android:6.1.0'
implementation 'com.github.MKergall:osmbonuspack:6.6.0'


text:
Q: ASP.Net MVC DisplayFormat DataFormatString show unit of measurment I know that when a ASP.Net MVC applicaion model has a cost property decorated like this
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal Cost { get; set; }

Then on the view I display
@Html.DisplayFor(model => model.Cost )

Ill get a label with with the currency symbol then the cost.
But I was wondering could it be used for unit of mesurment so the
[DisplayFormat(DataFormatString = "{0:mm}")]
public decimal Size{ get; set; }

Then on the view I display
@Html.DisplayFor(model => model.Size)

Gives 55 mm

A: I'm guessing the DataFormatString would be used for input to a String.Format in some fashion, so changing "{0:mm}" to "{0} mm" should be what you are looking for.


text:
Q: I want to print the value in sales I want to print the value of the amount of sales entered by user times .10. My first issue is I want to store a value that a user enters into sales then times that by .10 then print the value of sales. We I run the program I get two lines one is the amount of sales entered the other is .5.
        const double COMMRATE = 0.10;

        string inputstring;
        double sales =5;
        char response;
        Console.Write("Do you want to Calculate Sales A or B or E...");
        inputstring = Console.ReadLine();
        response = Convert.ToChar(inputstring);
        while (response == 'A')
        {

            Console.WriteLine("Enter Sales", sales.ToString("C"));
            sales = sales * COMMRATE;
            inputstring = Console.ReadLine();
            response = Convert.ToChar(inputstring);
        }

A: Is this what you intend?
    const double COMMRATE = 0.10;

    string inputstring;
    double sales;
    char response;
    Console.Write("Do you want to Calculate Sales A or B or E...");
    inputstring = Console.ReadLine();
    response = Convert.ToChar(inputstring);
    while (response == 'A')
    {
        Console.WriteLine("Enter Sales");
        inputstring = Console.ReadLine();
        sales = Double.Parse(inputstring);
        Console.WriteLine("Sales = " & sales);
        Console.WriteLine("Commission = " & sales * COMMRATE);
    }

A: Your .5 is coming about because you've set the default value of sales to be 5, and 5 * 0.1 = 0.5.
But why is that happening? Let's take apart your loop:

*

*It asks the user to enter an amount of sales.  The second parameter is ignored, because "Enter Sales" has no format string placeholders. It does not perform line-reading of any form.

*Without asking for input, it multiplies Sales by the commission rate and stores that to Sales.

*Now it asks for user input,

*which it immediately spits back out exactly as written (the amount-of-sales-entered line.)

What you actually need to be doing is a second Console.ReadLine() to get a string for the amount of sales, then use Double.ParseDouble() to get the entered amount of sales. Multiply that by your COMMRATE and print that back out- then give your "Do you want to Calculate..." question again, and then use the response from that to decide whether or not to continue the loop- currently, response is never getting modified, so you've created an infinite loop.
Unfortunately, you aren't even really close to the right code here. Your loop should look more like
while (response == 'A'){
    Console.WriteLine("Enter Sales");
    string salesStr = Console.ReadLine();
    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
    Console.WriteLine("Enter A to continue, anything else to quit");
    response = Convert.ToChar(Console.ReadLine());
}

...which should get you started towards making your program do what you want.

A: I'm having a hard time discerning what exactly you're asking.
If you want to print the value multiplied by the COMMRATE then you should probably put the calculation above the write statement.
sales = sales * COMMRATE;
Console.WriteLine("Enter Sales", sales.ToString("C"));

Although since you said you want to STORE the value entered by the user and THEN print it times the COMMRATE maybe you should use something like
double calculatedSales = sales * COMMRATE
Console.WriteLine("Enter Sales", calculatedSales.ToString("C"));

so that you're not redefining the original sales amount


text:
Q: Are foreign key constraints enforced on DELETE when deleting the child? I want to delete rows on a child table. I receive the error

The DELETE statement conflicted with the REFERENCE constraint
  "FK_Address_UserDataSet".  The conflict occurred in
  database "XYZ", table "dbo.Address", column
  'DataSetId'. The statement has been terminated.

I have a database structure with a parent UserDataSet and child  Address table (where a parent can have any number of childs).
There is a foreign key constraint (mentioned in the error) that requires the child's DataSetId to relate to a valid UserDataSet.
Here are the table and constraint scripts, created with MS SQL Server  Management Studio 2008 in simplified form:
CREATE TABLE [dbo].[Address](
    [AddressId] [int] IDENTITY(1,1) NOT NULL,
    [DataSetId] [int] NOT NULL,
        --other fields
 CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED
(
    [AddressId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

---

CREATE TABLE [dbo].[UserDataSet](
    [DataSetId] [int] IDENTITY(1,1) NOT NULL,
        --other fields
 CONSTRAINT [PK_UserDataSet] PRIMARY KEY CLUSTERED
(
    [DataSetId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

---Create the constraint

ALTER TABLE [dbo].[Address]  WITH NOCHECK ADD  CONSTRAINT [FK_Address_UserDataSet] FOREIGN KEY([DataSetId])
REFERENCES [dbo].[UserDataSet] ([DataSetId])
GO

ALTER TABLE [dbo].[Address] CHECK CONSTRAINT [FK_Address_UserDataSet]
GO

But, how can deleting a child (not the parent) be a problem in this setup?
Can it be that the row to delete is currently invalid, probably added while the constraint was not (yet) in use), an the constraint now is enforced while deleting the child with an invalid foreign key?

A: Why are you adding the constraint with NOCHECK?
From MSDN documentation...

If you do not want to verify new CHECK or FOREIGN KEY constraints
  against existing data, use WITH NOCHECK. We do not recommend doing
  this, except in rare cases. The new constraint will be evaluated in
  all later data updates. Any constraint violations that are suppressed
  by WITH NOCHECK when the constraint is added may cause future updates
  to fail if they update rows with data that does not comply with the
  constraint.


text:
Q: Change button color on single target I have a Xamarin Forms project (Portable) and see that the colors on one target (UWP) aren't that good. I want to change the color of a button on that target only, but I can't find how to do that.
I've looked at the files, but it seems to load the whole LoadApplication(new TheApp.App()); as a whole.

A: use Device to customize properties per platform
myButton.BackgroundColor = Color.Green;

// on Windows only, change color
if (Device.OS == TargetPlatform.Windows) {
  myButton.BackgroundColor = Color.Blue;
}


text:
Q: JSTL - how to get a value of value? I have this in my jsp page :    ${category.name_ENG}  which has "Car" as value
but i have the local language in an another varialbes : ${locale}. So in my jsp i want to display the car value depending on the locale variable.
I tried those :
${category.name_${locale}}
${category['name_${locale}']}
${category['name_{locale}']}

but none of them worked?
any help?

A: Use JSTL <c:set> to concatenate a string in EL and then use brace notation [] to access properties with a dynamic key.
<c:set var="name" value="name_${locale}" />
${category[name]}

By the way, if the sole functional requirement is internationalization/localization, then there are way much better ways than fiddling like this: How to internationalize a Java web application?


text:
Q: Icons are not displayed in vim-airline and NERDTree I've just installed plugins for my Neovim using vim-plug.
The plugins are working perfectly,
but it's the icons within them that are haunting me.
I've provided screenshots of them below.
NERDTree:

vim-airline:

They look very weird and it's hard to use.
Here's what I've tried:

*

*Installed the plugin https://github.com/ryanoasis/vim-devicons

*Installed https://github.com/ryanoasis/nerd-fonts#font-installation

*Added this let g:airline_powerline_fonts = 1
I am using Debian Linux AMD64.

A: It is a very common problem with many users after their very first installation of vim-airline plugin. So here are a few steps you have to carry out to see the icons in the vim-airline as well as in the NERDTree plugin.
Step 1
Install vim-devicons https://github.com/ryanoasis/vim-devicons using any plugin manager (I prefer vim-plug for this. https://github.com/junegunn/vim-plug) and place it just before the call plug#end() command or try to load this plugin at the end of all other plugins(if you are using any other methods to install your plugin) and at the next line paste set encoding=UTF-8
example:
call plug#begin()
.
.
.
Plug 'https://github.com/ryanoasis/vim-devicons'
set encoding=UTF-8
call plug#end()

Step 2
Paste the following code after the previous loop
let g:NERDTreeDirArrowExpandable="+"
let g:NERDTreeDirArrowCollapsible="~"

" air-line
let g:airline_powerline_fonts = 1

if !exists('g:airline_symbols')
    let g:airline_symbols = {}
endif

" unicode symbols
let g:airline_left_sep = '»'
let g:airline_left_sep = '▶'
let g:airline_right_sep = '«'
let g:airline_right_sep = '◀'
let g:airline_symbols.linenr = '␊'
let g:airline_symbols.linenr = '␤'
let g:airline_symbols.linenr = '¶'
let g:airline_symbols.branch = '⎇'
let g:airline_symbols.paste = 'ρ'
let g:airline_symbols.paste = 'Þ'
let g:airline_symbols.paste = '∥'
let g:airline_symbols.whitespace = 'Ξ'
" airline symbols
let g:airline_left_sep = ''
let g:airline_left_alt_sep = ''
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ''

let g:WebDevIconsUnicodeDecorateFolderNodes = 1
let g:WebDevIconsUnicodeDecorateFolderNodeDefaultSymbol = ''

let g:WebDevIconsUnicodeDecorateFileNodesExtensionSymbols = {}
let g:WebDevIconsUnicodeDecorateFileNodesExtensionSymbols['nerdtree'] = ''

Step 3
Download any of the font from https://www.nerdfonts.com/font-downloads. I prefer DejaVuSansMono Nerd Font.
Step 4
unzip DejaVuSansMono.zip and do mv ~/.fonts and cd ~/.fonts
Step 5
Finally you have to run fc-cache -fv to manually rebuild the font cache. Now reopen the vim or nvim and now you will find that the icons are visible correctly.

A: Try setting set guifont=<Your\ Nerd\ Font> in your .vimrc.


text:
Q: Spring boot application crashes with EXCEPTION_ACCESS_VIOLATION error I have a spring boot java application which crashes from time to time. The only thing I have is a thread dump file generated after a crash. Could somebody help me to analyze this thread dump because I don't see there something useful?
I have to attach a link to the file because it's to big to add it here like a text. thread dump
Update
The problem has gone once I've deleted and created a DB schema (we are using postgres). But I have absolutely no idea how such a thread dump related to postgres. So I think the initial question is still relevant.


text:
Q: How can I programmatically generate keypress events? What the java program should do is it should trigger keyboard press on some condition without a person pressing a keyboard key. So any program running in windows and in focus which requires keyboard input will get the input without a person actually pressing the keyboard.
I found these related questions here :
question 1,
question 2
I was wondering if there is any method to do this in Java.

A: Use the Robot class.
Code snippet:
import java.awt.Robot;
import java.awt.KeyEvent;

Robot r = new Robot();
int keyCode = KeyEvent.VK_A; // the A key
r.keyPress(keyCode);
// later...
r.keyRelease(keyCode);

However, if you are trying to automate a task on your computer, I would recommend AutoHotKey. It's dedicated to automating common tasks, so it would be easier to use it instead of Java.


text:
Q: User authentication on Android before CRUD operations I have a database which has some data tables and a user table. This database is queried only through a php page, which executes classical CRUD operations. Then, I have an Android app which calls the php page (through Volley) to read/write data, and shows data back to the user.
I'd like to implement a login layer, i.e. the app user does a login, and then can operate on data.
So: user inputs user&pass, pass is hashed, php page is called with action=login user and hashpass, php page queries the db to check credentials, the record is found, the php page sends a "success" back to the app. But then, how to keep authentication in the next CRUD operations? What are the best practices to handle this in a safe and robust way?
Thanks a lot

A: Use SharedPreferences class to store authorization token. So when you successfully log in send token as request and save it there. On log out clear SharedPreferences. Good luck


text:
Q: Lua 4.0 script fails and complains about outer scope The following Lua 4.0 script fails due to some of the variables being in an 'outer' scope. What are the different ways I can fix this? I would like to avoid putting things in the global scope completely if possible. Thanks.
function flokalAdd(iNx, iNy, iXmin, iSym, fEcc, bInside, fScale)
    TWO_PI = 2 * PI;
    iSx = 4;
    iSy = 4;
    function pow(fA, fB)
        return fA^fB
    end
    function mag(fX, fY)
        return dist(fX, fY, 0, 0)
    end
    function dist(fX1, fY1, fX2, fY2)
        return sqrt(pow(fX2 - fX1, 2) + pow(fY2 - fY1, 2))
    end
    function norm()
        local fY1 = 0;
        local fX1 = 0;
        local fX2 = exp(fX1) * cos(deg(fY1));
        local fY2 = exp(fX1) * sin(deg(fY1)) + fEcc;
        local fD = 0;
        if (bInside == 1) then
            fD = pow(mag(fX2, fY2),  1/iSym);
        else
            fD = pow(mag(fX2, fY2), -1/iSym);
        end
        local fArg = rad(atan2(fX2, fY2)) * -1/iSym;
        local fX3 = fD * cos(deg(fArg))/TWO_PI;
        local fY3 = fD * sin(deg(fArg))/TWO_PI;
        return mag(fX3, fY3)
    end
    function fn(fX, fY)
        local aP = {};
        local fX1 = exp(fX) * cos(deg(fY));
        local fY1 = exp(fX) * sin(deg(fY)) + fEcc;
        local fD = 0;
        if (bInside == 1) then
            fD = pow(mag(fX1, fY1),  1/iSym);
        else
            fD = pow(mag(fX1, fY1), -1/iSym);
        end
        local fArg = rad(atan2(fX1, fY1)) * -1/iSym;
        for i = 0, iSym - 1 do
            local fX2 = fD * cos(deg(fArg + i * TWO_PI/iSym))/TWO_PI;
            local fY2 = fD * sin(deg(fArg + i * TWO_PI/iSym))/TWO_PI;
            aP[i + 1] = {fX2, fY2};
        end
        return aP
    end
    function lines(aP1, aP2)
        for i = 0, iSym - 1 do
            local fX1 = aP1[i + 1][0 + 1];
            local fY1 = aP1[i + 1][1 + 1];
            local fX2 = aP2[i + 1][0 + 1];
            local fY2 = aP2[i + 1][1 + 1];
            --addPebble(<sPebbleType>, <tPosition>, ?, ?, ?)
            --addPebble("Pebble_2", {fX1 * fScale/fNorm, 0 * fScale/fNorm, fY1 * fScale/fNorm,}, 0, 0, 0)

            -----------------------
            -- DO SOMETHING HERE --
            -----------------------
        end
    end
    -- calculate the distance from the origin to the center of each eye, then use it to normalize the shape to within 1 unit of the center
    fNorm = norm();
    for i = 0, iNy - 1 do
        local fY = i * TWO_PI/iNy;
        for j = iXmin * iSx, iNx * iSx - 1 do
            local fX1 = j * TWO_PI/iNx/iSx;
            local fX2 = (j + 1) * TWO_PI/iNx/iSx;
            lines(fn(fX1, fY), fn(fX2, fY))
        end
    end
    for i = iXmin, iNx do
        local fX = i * TWO_PI/iNx;
        for j = 0, iNy * iSy - 1 do
            local fY1 = j * TWO_PI/iNy/iSy;
            local fY2 = (j + 1) * TWO_PI/iNy/iSy;
            lines(fn(fX, fY1), fn(fX, fY2))
        end
    end
end

flokalAdd(16, 16, 12, 5, 256, false, 20000)

A: This happens due to Lua 4.0 scoping rules:

Function scopes have a special limitation in that outer scopes (other than the global scope) may not be accessed. This applies to any function, but is most noticeable in the case of nested functions where you may want to access locals of the enclosing scope.

In your code fEcc is defined in the scope of function flokalAdd, so it can't be accessed from the inner norm function.
You can fix this using upvalues:

Upvalues were added to work around the function scope limitation. Prefixing an outer-scope variable reference with % produces a copy of that variable as of the function's instantiation. Only the immediate scope containing the function and the global scope may be accessed in this manner.

Looking at the code, it seems that copying by value is OK. Here is the fixed version.


text:
Q: Crystal Reports группировать данные по "плавающим" часам стоит такой вопрос. Существует таблица SQL с данными по расписанию поездов. В ней две колонки - rasp_date, которая отвечает за выезд поезда, и race_hours, которое указывает на время поездки этого поезда до конечного пункта. Приведу пример данной таблицы:
RASP_DATE                  RACE_HOURS
01.10.2020 15:05:00        4
01.10.2020 15:35:00        3
01.10.2020 16:10:00        8
01.10.2020 16:25:00        6

Нужно разработать отчет на основе этих данных, посчитать, какое суммарное время поездки каждый час. Например, по примеру выше отчет выдаст, что с 15:00 до 16:00 суммарное время поездки - 7 часов, с 16:00 до 17:00 - 14 часов. Данная задача легко выполняется при помощи группировки.
Однако, стоит задача немного другая - рассчитать количество часов поездки в "плавающем" часе. Пользователь вводит параметр "время минут" (например, 15), который кратен 5, и теперь "окна" должны рассчитываться не с 15:00 до 16:00, а с 15:15 до 16:15, с 17:15 до 18:15, и т.д.
Скорее всего, для этого нужно менять группировку, но точно не знаю, как это сделать. Прошу, пожалуйста, подсказать.

A: Пример получения данных по указанному размеру окна. СУБД и версия не указана, использован MySQL версии 8. Суммарная длительность посчитана в минутах.
WITH RECURSIVE
cte1 AS ( SELECT FROM_UNIXTIME((UNIX_TIMESTAMP(MIN(start)) DIV 3600) * 3600) start,
                 TIMESTAMP(FROM_UNIXTIME((UNIX_TIMESTAMP(MIN(start)) DIV 3600) * 3600), @chunk) finish
          FROM test
        UNION ALL
          SELECT TIMESTAMP(start, @chunk), TIMESTAMP(TIMESTAMP(start, @chunk), @chunk)
          FROM cte1
          WHERE start < ( SELECT MAX(start + INTERVAL length HOUR)
                          FROM test ) )
,
cte2 AS ( SELECT start, start + INTERVAL length HOUR finish
          FROM test )
SELECT cte1.start,
       cte1.finish,
       SUM(TIMESTAMPDIFF(MINUTE, GREATEST(cte1.start, cte2.start), LEAST(cte1.finish, cte2.finish))) total,
       GROUP_CONCAT(cte2.start) starts
FROM cte1
JOIN cte2 ON cte1.start <= cte2.finish AND cte2.start <= cte1.finish
GROUP BY cte1.start,
         cte1.finish;

test - таблица исходных данных
@chunk - (введённый юзером) размер окна
fiddle
Запрос дополнительно, для контроля, выводит список start тех записей, которые учтены в суммарном времени для текущего окна.
Если необходимо вывести данные не за весь период, а только за определённый отрезок, измените соотв. образом cte1 и генерируйте список окон на основании требуемых границ.

A: В итоге, пришел к решению вопроса. Делается группировка по плавающему часу вот так:

*

*Создать параметр "minutes".

*Создать новую формулу "floating_hour":
if minute({TableName.RASP_DATE}) < {?minutes} then
time(hour({TableName.RASP_DATE})-1,{?minutes},0) else
if minute({TableName.RASP_DATE}) >= {?minutes} then
time(hour({TableName.RASP_DATE}),{?minutes},0)

*Создана группа и группировка по "RASP_DATE" (По неделям)

*Создана группа и группировка по формуле "floating_hour".

*При помощи инструментов CR просуммировано RACE_HOURS по группе "floating_hours".


text:
Q: Prove that the range of $f$ is all of $\mathbb{R}$. Let $f:\mathbb{R} \rightarrow \mathbb{R}$ be a continous function such that  $|f (x)−f (y)| \geqslant |x −y|$, for all real $x$ and $y$. I need to prove that the range of $f$ is all of $\mathbb{R}$. I tried to solve the inequality to get a general form for the functions, but it just ended up in a mess.

A: Hint: Since $f$ is a continuous function the range $f(\mathbb{R})$ is an interval, and since $|f(x)-f(y)|\geq |x-y|$ the range is unbounded in both directions, hence $f(\mathbb{R})=\mathbb{R}$.

A: From the inequality we can directly deduce that $f$ is injective. We can also see that $f$ transforms unbounded intervals into unbounded intervals. The sets $f ((−\infty, 0])$ and $f ([0,\infty))$ are unbounded intervals which intersect at one point. Hence, they must be two intervals that cover the entire real axis.

A: *

*The function is injective.

*Fix $y=0$. Then $|f(x)-f(0)| \geq |x|$ for all $x$, so as $x \to \infty$, $|f(x)| \to \infty$ (by continuity).

*As $x \to -\infty$, $|f(x)| \to \infty$.

*Intermediate value theorem.

*Injectivity prevents the sign of the limits from being the same.

A: Well, let's think.
Is it possible that that $f(x)$ is bounded above or below?  Probably not as $|f(x)- f(y)| \ge |x-y|$ and $|x-y|$ seems likely to be arbitrarily large.
So Lemma 1:  $f(x)$ is unbounded. (We'll prove that.)
If $f$ is unbounded does it have to take on every value.  This seems reasonable as a variation of the Intermediate value theorem.  After all if $f$ is continuous and $f(x) < f(y)$ then for all $c \in (f(x),f(y)$ there is an $d$ between $x$ and $y$ so that $f(d) = f(c)$.  So wouldn't it be reasonable that for all $c: \inf f < c < sup f$ there is a $d$ so that $f(d) =c$?  And that if $f$ is continuous unbounded that for all $c$ there is a $d$ so that $f(d) = c$?
So Lemma 2: if $f$ is a continuous real-valued unbounded function, the for all $y \in \mathbb R$ there is an $x$ so that $f(x) = y$.
Proof of Lemma 1:
If $|f(x)| \le M$ for all $M$ then $|f(x) - f(y)| \le |f(x) + |f(y)| \le 2M$ for all $x,y$.  So $2M \ge |f(x) - f(y)| \ge |x-y|$ for all $x,y$.  Which means for all $x \in \mathbb R$ then $|x| = | x-0| \le 2M$ so $\mathbb R$ is bounded.
This is false so $f$ is not bounded.
Lemma 2:
$f$ is unbounded so, For any $y \in \mathbb R$ there exists an $x_0$ so that $f(x_0) > y$ and an $x_2$ so that $f(x_1) < y$.  $f$ is continuous so by Intermediate Value Theorem there is a $d$ so that $f(d) = y$.
And that is it... it would seem.  $\mathbb R \subset f(\mathbb R) = range f \subset \mathbb R$ so the range of $f$ is all $\mathbb R$.

A: If $f$ is injective and continuous it must be strictly monotonic. By looking at $-f$ if necessary, we can assume that $f$ is strictly increasing and so we have $f(x)-f(y) \ge x-y$ whenever $x \ge y$.
In particular, $\lim_{x \to \infty} f(x)-f(y) = \infty$ and
$\lim_{y \to -\infty} f(x)-f(y) = \infty$.
Hence the range is unbounded in both directions and the intermediate function theorem shows that the range must be $\mathbb{R}$.


text:
Q: Can you force Windows to disallow SSL in all WINHTTP and HTTPAPI system calls? Title says it all. Is there a registry setting or something that will prevent the Windows built-in libraries: WINHTTP and HTTPAPI to not support SSL3?

A: Both those APIs use, as far as I know, the SCHANNEL API to provide their SSL functionality. Disable SSL 3.0 in the SCHANNEL configuration and any applications using those APIs shouldn't be able to do SSL 3.0 anymore. (No, I haven't actually tested this-- I'm just going on my memory about those APIs.)


text:
Q: $\lambda P( \min_{1 \leq k \leq n}X_k\leq -\lambda) \leq \int_{\{\min_{1 \leq k \leq n}X_k> -\lambda\}}X_ndP - E[X_0]$ Let $n \in \mathbb{N}^*.$ $(X_k)_k$ is a submartingale, $\lambda>0,$ by considering, for $1 \leq k \leq n, E_k=\bigcap_{r=1}^{k-1}\{X_r >-\lambda\}\cap\{X_k \leq -\lambda\},$ prove that $$\lambda P( \min_{1 \leq k \leq n}X_k\leq -\lambda) \leq \int_{\{\min_{1 \leq k \leq n}X_k> -\lambda\}}X_ndP - E[X_0].$$
$\{\min_{1 \leq k \leq n}X_k \leq -\lambda\}=\bigcup_{k=1}^nE_k,$ also $E_k$ are disjoint so $P(\min_{1 \leq k \leq n}X_k\ \leq - \lambda)=\sum_{k=1}^nP(E_k)$ also $\int_{E_k}X_kdP \leq -\lambda P(E_k).$
Also $X_k \leq E[X_n |\mathcal{F}_k].$
Having a problem how to continue from here, especially how to use that $(X_k)_k$ is a submartingale ?

A: Let $A=\{ \min_{1 \leq k \leq n}X_k\leq -\lambda\}$, and
$$N=\inf\{m: X_m\leq-\lambda\text{ or }m=n\},$$
then $X_N\leq-\lambda$ on $A$ and $X_N=X_n$ on $A^c$. Hence $E[X_N1_A]\leq-\lambda P(A)$ and
$$E[X_n1_{A^c}]=E[X_N1_{A^c}]=E[X_N]-E[X_N1_A]\geq E[X_N]+\lambda P(A).$$
Since $N$ is a bounded stopping time with $P(N\leq n)=1$ and $X_n$ is a submartingale, we have
$$E[X_0]\leq E[X_N]\leq E[X_n].$$
Therefore
$$E[X_n1_{A^c}]\geq E[X_0]+\lambda P(A),$$
as desired.


text:
Q: How can I optimize let's encrypt to have very low latency Hello I have a site hosted in us region. I have let's encrypt ssl .
I am from India and when I request the site, I see lot of ssl latency even after first byte .
I have done oscp stapling , ssl session caching and also tried to use http 2 but still no fix!
How does big sites like Netflix Bing Google Yahoo does that, not having any ssl latency after the first byte to any part of the domain


text:
Q: Luracast Restler 3 logging onRespond Follow up questions for this solution: https://stackoverflow.com/a/31883204/3548238

*

*If i want to log the request in "onRespond()" event, how can i access to the status code? For example: if request responds with status code 200, i'd want to log "success = 1" and if its something else, then "success = 0"

*Can i somehow access the message, if my API throws exception with "throw new RestException(404, "Example not found");" or if auth failed or whatever the cause is.

*Can i/how can i make some of the requests so that they wont be logged in any situation? I know i should create some kind of annotation for it, but: how?

For example something like this:
/**
 *
 * @status      200
 *
 * @description Get all logs
 * @url         GET logs
 * @access      protected
 * @class       AccessControl {@requires admin}
 *
 * @log         false
 *
 * @throws RestException
 */
public function list_all_logs() {
...
...

A: You should be using onComplete instead of onRespond
Why?

*

*onRespond() - fired before sending response

*onComplete() - fired after sending response

Here is the complete solution that answers all your questions, assuming you are adding @log false comment to the api method you want to exclude
use Luracast\Restler\Restler;
use Luracast\Restler\User;

$r = new Restler();
$r->onComplete(function () use ($r) {
    if (
        !isset($r->apiMethodInfo->metadata['log']) ||
        $r->apiMethodInfo->metadata['log'] == 'true'
    ) {
        $success = $r->responseCode == 200;
        $info = array(
            'success' => $success,
            'message' => $success ? '' : $r->exception->getErrorMessage()
        );
        print_r($info); //your logging function here!
    }
});
$r->addAPIClass('Say');
$r->handle();


text:
Q: I need to create a referral system e.g. "site.com.br/nomedequemindicou" in Shopify that returns points for those who indicated The system is based on .liquid .json .js, the person who refers will earn and accumulate points that will be exchanged for products that the store sells, the indications will come from physiotherapy professionals, according to the code of ethics they cannot receive amounts and yes points.
I tried to use a rewards plugin but I didn't find anything geared to what I need..


text:
Q: Laravel - order by relationship table I have 2 tables issues and magazines and they have a relationship set up like this:
Magazines model:
 public function issues()
 {
     return $this->hasMany('App\Issue');
 }

Issues model:
public function magazine()
{
    return $this->belongsTo('App\Magazine');
}

In the magazines table I have a column order where the order number of the magazine is. I need to display the latest issue of each magazine, ordered by the magazine order.
Now I am displaying latest issue of each magazine ordered by the date of issues.
        $issues = Issue::orderBy('date', 'desc')->get()->groupBy('magazine_id');

        foreach ($issues->first() as $issue)
        {
            $images[] = $issue->image;
        }

And that works fine.
But with the new query:
         $magazines = Magazine::with('issues')->orderBy('order')->get();

        foreach ($magazines as $magazine)
        {
            $issues = $magazine->issues()->first();
            $images[] = $magazine->issues()->first()->image;
        }

I get the error:

Trying to get property of non-object

A: Just check if issue is_null, if not, add the image to $images:
    foreach ($magazines as $magazine)
    {
        $issue = $magazine->issues()->first();
        if (!is_null($issue) {
            $images[] = $issue->image;
        }
    }


text:
Q: mysql stored procedure construct with GROUP_CONCAT and IN clause For some reason i need to explode a query in multisteps (very large rows and many join) , I know its possible to perform the query like SELECT IN (subquery) but its not what i need to achieve.
How to construct my query into step where query 2 can use the result of query 1 (without using temporary table) with an IN clause ; expected query 2 should look like this : select otherstuff where foo IN(id,id,id,id,longlistid,)
query 1 => select stuf as result1
query 2 => select otherstuf where foo IN (result1)
I thought to use shortcut @ don't know if its appropriate , here is my try :
 CREATE PROCEDURE `exemple`()
    BEGIN

     SELECT @query1 :=
    `id`  FROM `table`
    WHERE `stuf`= 'cat'
    UNION ALL SELECT `id`
    FROM `table`
    WHERE `dog`= 'hard' ;

    SELECT please FROM help WHERE me IN(@query1) ;

    END

The IN clause seems not correct like this..
Another try , store result in a declared locale variable :
CREATE PROCEDURE `exemple`()
    BEGIN

     DECLARE resultquery1 VARCHAR(5000);

    SELECT
    `id`  FROM `table`
    WHERE `stuf`= 'cat'
    UNION ALL SELECT `id`
    FROM `table`
    WHERE `dog`= 'hard'
    INTO resultquery1 ;

    SELECT please FROM help WHERE me IN(resultquery1) ;

    END

Not enought , i got this logical error :
Error Code: 1172. Result consisted of more than one row
regards,
Jess

A: Use a Temporary Table instead and have the query1 value inserted in that table. then in your query2 you can directly fetch the data from temporary table; like below (A code sample)
CREATE PROCEDURE `exemple`()
BEGIN

create temporary table temptest(col varchar(20));
insert into temptest
 SELECT `foo`  FROM `table`
WHERE `stuf`= 'cat'
UNION ALL SELECT `bar`
FROM `table`
WHERE `dog`= 'hard' ;

SELECT please FROM help WHERE me IN (select distinct col from temptest) ;

DROP TABLE temptest;
END

EDIT:
You may not need the temporary table at all. Per your post explanation, you can  include the query directly in IN clause like below. Hope this helps.
 SELECT please FROM help
 WHERE me IN (
     SELECT `foo`  FROM `table`
    WHERE `stuf`= 'cat'
    UNION ALL SELECT `bar`
    FROM `table`
    WHERE `dog`= 'hard'
    ) ;

FINAL EDIT:
A inlist is a comma separated value, you can't simply store like the way you are trying cause it's a scalar variable where you are trying to store and it's incorrect;
You may do little trick like below and store it but that's not guaranteed to work.
set @inlist := (
select group_concat(unitid)
from (
SELECT unitid, 1 as 'ID'  FROM teachers
    WHERE username= 'abcdced'
    UNION ALL
    SELECT unitid, 1 as 'ID'  FROM teachers
    WHERE username= 'harikas'
) x
group by ID);

Moreover, I am not sure who told you that going through variable will be efficient.
I may agree that TEMPORARY table may pose some issue based on your situation but
the subquery option I given (Or the suggestion provided by Gordon in below answer) will be much efficient than the way you are trying to do. At least it will not incurr the cost of fetching and storing into variables (If at all it works).

A: I add an answer here To follow the @Rahul correct answer in final edit , for thoses who need to achieve this particular case  (when subquery cannot perform as well you'd like) ,
here is the final form of the procedure using the mysql GROUP_CONCAT and CONCAT function :
temp is the declared local variable for storing first result
SET SESSION group concat to avoid the group_concat limitation length
    CREATE PROCEDURE `exemple`()
    BEGIN

    DECLARE temp VARCHAR(10000);
    SET SESSION group_concat_max_len = 100000;

    SELECT GROUP_CONCAT(foo) FROM bar
    WHERE cible = x GROUP BY cible INTO temp;

    SET @S = CONCAT
   (
    "SELECT * FROM anothertable WHERE whatyouwant IN(", temp," ) "
   );

    PREPARE STMT FROM @S;
    EXECUTE STMT;

    END

A: Often the most efficient way to approach this is with two conditions in the where clause:
select please
from help h
where exists (select 1
              from table t1
              where stuf = 'cat' and h.me = t1.foo
             ) or
      exists (select 1
              from table t1
              where dog = 'hard' and h.me = t1.bar
             );

These queries can take advantage of indexes on the table used in the subquery:  table(foo, cat) and table(bar, hard).


text:
Q: Java inflector to convert plurals to singular forms I am using the Java Inflector library to convert singular forms to plurals, example : 2 boat => 2 boats.
However, it fails when the inputs are already plural.
1 boats => boats,
butterflies => butterflieses
Is there any other Java utility that -
1. Converts plurals to singular when necessary, example : 1 boat => boat
2. Retains plural as it is, if the plural form is required.
Thanks!

A: You know, you can make a simulation, first avoid to convert verbs that are already in plural, how? take the verb and convert it to singular, then convert it in plural and check if the result string is the same than the string that is in the input, if not, thats ok, know you know that is not in plural.


text:
Q: MongoDb query return empty object I'm trying to perform a simple .find() query on my mongodbAtlas, but the result of this query is an empty object.
this is my server file:
require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");

global.broker = new ServiceBroker({
  nodeID: "auth",
});

const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));

const { PORT, URI } = process.env || 5000;

global.broker.createService(AUTH_SERVICE);

const start = async () => {
  const dba = await MongoClient.connect(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  global.db = dba.db("Auth");

  try {
    await dba.connect();
    console.log("DATABASE CONNESSO CON SUCCESSO");
  } catch (e) {
    console.error(e);
  }

  await global.broker.start();
  app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING  ON ${PORT}`));
};
start();

this is my routes file:
const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
  const data = global.db.collection("Users").find({}).toArray();
  res.send(data);
});

module.exports = router;

this is how my document is populated:
{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test@gmail.com","password":"1234"}

A: I think you are missing the "await" keyword after const data..... as API data fetching calls are asynchronous and required promise/ async-await to handle. Being async in nature, it moves forward to the next instruction and returns an empty array.
const express = require("express");
const router = express.Router();

router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
  res.send(data);
});

module.exports = router;


text:
Q: Why am I sometimes not allowed to delete a folder until I delete its contents by hand? (Windows) Sometimes, when I try to delete a folder in Windows, I get a message that I need permission from [my current account] to delete that folder. Which is weird, because I'm already logged in as that user. However, when I open the folder, select all contents, and delete them (without any sort of prompt), I can go back up and delete the original folder without the security prompt.
This happens most often in project folders created by Visual Studio (often, the .vs and .git folders cause this trouble) but it has happened with other folders as well. It also happens recursively: I open a problematic folder, delete all contents, get a message that a bunch of subfolders can't be deleted, open each subfolder, delete all contents, etc.
If I check the folder with Process Explorer, it can't find any attached processes to the folder or any of its contents.
It feels like this would be easy to automate, but why does this happen in the first place?

A: I have often wondered the same thing. Unix(linux) based systems do not exhibit this problem and my guess is there is an entwined kernel problem MS is unwilling to take on.
I have investigated this several times. I am trying to help you out, but by no means is my knowledge a definitive answer. I don't remember this problem until win7 and the fact that it persists makes me believe the problem is too complicated and deep in the MS kernel for them to want to fix it.

*

*The first possibility is other processes are in some way jammed or deadlocked. It might be as simple as the File Explorer accessing but not freeing the program when it wants the program's icon.

*Another possibility is that the MS caching program has some unknown problem or is confused, whereby some process or damen has told the file manager it is in use, or perhaps should be kept available.

*Or the ownership gets screwed up. Perhaps after accessing it, the file properties table shows the system is using or having control of it and no user has privileges to do something to it. This may be associated with a file lock issue.

*My best guess, and its a shot in the dark, is somehow the file and the memory manager get screwed up and the files information becomes un-editable - even by the system or kernel.
One clue that points to a kernel cache / memory / or file manager problem is that it disappears after a reboot (perhaps indicating a ownership or in-use file lock problem). Whatever the problem, it is a major Microsoft screw up (and they are aware of it) and their best and brightest programmers are unable to resolve it in cost and resource effective way.


text:
Q: Log in console after install Docker on RedHat (Azure) After install Docker 18.x on RedHat 7.5 (hosted at Azure), some process is writing the log below to console each 1 minute. How do I disable it, please? Thanx for all!

INFO ExtHandler Updated NIC state
[
    {
        "name": "lo",
        "link": " mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000\"
        "link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 promiscuity 0 addrgenmode eui64 numtxqueues 1 "
        "numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 "
    },
    {
        "name": "docker0",
        "link": " mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default \"
        "    link/ether 02:42:7d:f0:24:58 brd ff:ff:ff:ff:ff:ff promiscuity 0 \    bridge forward_delay 1500 hello_time "
        "200 max_age 2000 ageing_time 30000 stp_state 0 priority 32768 vlan_filtering 0 vlan_protocol 802.1Q bridge_id "
        "8000.2:42:7d:f0:24:58 designated_root 8000.2:42:7d:f0:24:58 root_port 0 root_path_cost 0 topology_change 0 "
        "topology_change_detected 0 hello_timer    0.00 tcn_timer    0.00 topology_change_timer    0.00 gc_timer   "
        "16.78 vlan_default_pvid 1 vlan_stats_enabled 0 group_fwd_mask 0 group_address 01:80:c2:00:00:00 mcast_snooping "
        "1 mcast_router 1 mcast_query_use_ifaddr 0 mcast_querier 0 mcast_hash_elasticity 4 mcast_hash_max 512 "
        "mcast_last_member_count 2 mcast_startup_query_count 2 mcast_last_member_interval 100 mcast_membership_interval "
        "26000 mcast_querier_interval 25500 mcast_query_interval 12500 mcast_query_response_interval 1000 mcast_startup_query_interval "
        "3125 mcast_stats_enabled 0 mcast_igmp_version2 mcast_mld_version 1 nf_call_iptables 0 nf_call_ip6tables 0 nf_call_arptables 0 "
        "addrgenmode eui64 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 "
    },
    {
        "name": "eth0",
        "link": " mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000\    "
        "link/ether 00:0d:3a:11:4e:57 brd ff:ff:ff:ff:ff:ff promiscuity 0 addrgenmode eui64 numtxqueues 64 numrxqueues
        ""64 gso_max_size 62780 gso_max_segs 65535 "
    }
]


text:
Q: Failed to convert a NumPy array to a Tensor (Unsupported object type int). while implementing wide and deep network I want to implement wide and deep neural network using keras, I am using keras official code implementation but I want to pass numpy array as a dataset  instead of  csv file.
Code:
def get_dataset_from_csv(csv_file_path, batch_size, shuffle=False):
dataset = tf.data.experimental.make_csv_dataset(
    csv_file_path,
    batch_size=batch_size,
    column_names=CSV_HEADER,
    column_defaults=COLUMN_DEFAULTS,
    label_name=TARGET_FEATURE_NAME,
    num_epochs=1,
    header=True,
    shuffle=shuffle,
)
return dataset.cache()

used below link for code implementation: https://keras.io/examples/structured_data/wide_deep_cross_networks/
Above function is used to generate cache dataset using tensorflow function "make_csv_dataset" but I want to pass numpy array as dataset directly.
what could be the solution?

A: Keras doesn't support int type so you need to cast them to float. Simple way is changing the type to float after you load your data as numpy array:
x = x.astype('float32')


text:
Q: API request shows correct response in Chrome DevTools but is actually null in Angular app My app is supposed to display Code Analysis logs. Those logs are in large(20k+ lines) html files. I'm reading them in ASP.NET Core app and pass them as string to API. C# read them nicely and passes them on, Chrome shows the correct response in DevTools, and yet Angular doesn't seem to notice this and logs null to the console aswell as when I try to display them.
I'm relatively new to Angular so I might be ommiting something obvious here. Here's my code - that's the Get method that reads and passes the file:
    [HttpGet, Route("analysis")]
    public string Analysis(string projectName, string definitionName)
    {
        string path = Path.Combine(@"\\glbuild2\CodeAnalysisLogs", projectName, definitionName, "CodeAnalysis.html");
        if (System.IO.File.Exists(path))
        {
            string temp = System.IO.File.ReadAllText(path);
            return temp;
        }
        else return "Error";
    }

And here's the method I use to make an API request(please note it does work, I use the same method with different uri but to the same server and it works there):
    this.http.get('http://localhost:54639/api/logs/analysis?projectName=' + this.currentDefinition.project.name + '&definitionName=' + this.currentDefinition.name).subscribe(data => {
      this.AnalysisLogs = data;
      console.log(data);
    })

Now the line logging to console always logs null, and the response in DevTools is the one I'm expecting: a string going


text:
Q: How to remove properties from Object Jasvscript? i was trying to delete properties which has value empty or null or undefined from object. I am able to delete properties of first level properties. But some scenario property might contain another object and that object might contain another object. So almost like LINKED LIST. But i am not sure how to find second level object property values.
For example
{
  prop1: "value1",
  prop2: {
       secLevlProp1: "value1",
       secLevlProp2: null,
       secLevlProp3: {
          secLev2Prop1: "value1",
          secLev2Prop2: "value2",
          secLev2Prop3: {
                 secLev3Prop1: "value1",
                 secLev3Prop2: "",
                 secLev3Prop3: "value3",
               }
       },
  }
  prop3: [
           { arrProp: "values", arrProp1: "" },
           { arrProp: "values2", arrProp1: "values4" },
  ],
  prop4: "undefined",
  prop5: "value1",
}

from this above object expected output
   {
      prop1: "value1",
      prop2: {
           secLevlProp1: "value1",
           secLevlProp3: {
              secLev2Prop1: "value1",
              secLev2Prop2: "value2",
              secLev2Prop3: {
                     secLev3Prop1: "value1",
                     secLev3Prop3: "value3",
                   }
           },
      }
      prop3: [
               { arrProp: "values" },
               { arrProp: "values2", arrProp1: "values4" },
      ],
      prop5: "value1",
    }

this is what i tried
        Object.keys(myObj).forEach(prop=> {
            if (myObj[prop] === '' || myObj[prop] === null || myObj[prop] === undefined) {
                delete myObj[prop];
            }
        });

this works fine on first level properties but how should i apply the above code on linked list concept on the above format object. Please someone help me on this.

A: You can do it recursively like so :
const deleteProperties = obj => {
    Object.keys(obj).forEach(prop => {
        if (obj[prop] === '' || obj[prop] === null || obj[prop] === undefined) {
            delete obj[prop];
        } else if (typeof obj[prop] === 'object') {
            deleteProperties(obj[prop]);
        }
    });
}

In your example, prop4 won't be removed since it's a string


text:
Q: Getting error while making drawer layout using custom list I am getting error while creating left drawer in custom list. I am getting error where inflater inflate in siliderAdapter.java.
Food Activity Class
public class Food extends ActionBarActivity {
    ImageView licon;
    ImageView menu_btn;
    Intent i;
    Intent intent;
    ListView lv;
    String[] foodIcon;
    String[] FoodText;
    String [] food_id;
    ProgressDialog pDialog;
    String[] userdata;
    public HashMap<String, String> catagories = new HashMap<String, String>();

    ArrayList<NavDrawerItem> mNavItems = new ArrayList<NavDrawerItem>();

    String[] menu;
    DrawerLayout dLayout;
    ListView dList;
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food);

        licon=(ImageView)findViewById(R.id.l_icon);
        menu_btn=(ImageView)findViewById(R.id.menu_btn);

        /*menu = new String[]{"Home","Android","Windows","Linux","Raspberry Pi","WordPress","Videos","Contact Us"};
        dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        dList = (ListView) findViewById(R.id.left_drawer);

        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);

        dList.setAdapter(adapter);
    //  dList.setSelector(android.R.color.holo_blue_dark);
*/

        String[]data={"History","Food","Location","Faranchise","Terms & Conditions","Log Out"};
        int[]icons={R.drawable.history,R.drawable.food,R.drawable.location,R.drawable.franchise,R.drawable.t_c,R.drawable.logout};

        //menu = new siliderAdapter(data,icons);
        dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        dList = (ListView) findViewById(R.id.navlist);
        dList.setAdapter(new siliderAdapter(this,data,icons));
        dList.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

                Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
                /*dLayout.closeDrawers();
                Bundle args = new Bundle();
                args.putString("Menu", menu[position]);
                Fragment detail = new DetailFragment();
                detail.setArguments(args);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();*/

            }

        });

        i=new Intent(this,Location.class);
        intent=new Intent(this,SilideMenu.class);

        if(this.getIntent().getExtras()!=null)
        {

        Bundle b=this.getIntent().getExtras();

        String msg=b.getString("msg");
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

         userdata=b.getStringArray("user_data");
//      if(userdata!=null){
//      user_data_bean ob = new user_data_bean();
//
//
//      ob.set_User_id(userdata[0]);
//      ob.set_user_name(userdata[1]);
//      ob.set_email_id(userdata[2]);
//      ob.set_phone_number(userdata[3]);
//      ob.set_address(userdata[4]);
//      ob.set_status(userdata[5]);
//      ob.set_message(userdata[5]);
//      }
        }
        new getFoodCategory().execute();

        lv=(ListView) findViewById(R.id.food_list);
        menu_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //startActivity(intent);
                drawer();
            }
        });

        licon.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(i);
            }
        });
    }// end of onCreate method

    public void drawer(){
        String[]data={"History","Food","Location","Faranchise","Terms & Conditions","Log Out"};
        int[]icons={R.drawable.history,R.drawable.food,R.drawable.location,R.drawable.franchise,R.drawable.t_c,R.drawable.logout};

        //menu = new siliderAdapter(data,icons);
        dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        dList = (ListView) findViewById(R.id.left_drawer);
        dList.setAdapter(new siliderAdapter(Food.this,data,icons));
       // adapter.setAdapter(new siliderAdapter(Food.this,data,icons));

     //   adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,(new siliderAdapter(data,icons)));

      //  dList.setAdapter(adapter);
    //  dList.setSelector(android.R.color.holo_blue_dark);

        dList.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

                Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
                /*dLayout.closeDrawers();
                Bundle args = new Bundle();
                args.putString("Menu", menu[position]);
                Fragment detail = new DetailFragment();
                detail.setArguments(args);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();*/

            }

        });
    }

    class getFoodCategory extends AsyncTask<String, String, String[]> {

        @Override
         protected void onPreExecute() {
             super.onPreExecute();
             // Showing progress dialog
             pDialog = new ProgressDialog(Food.this);
             pDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
             pDialog.setMessage("Please wait...");
             pDialog.setCancelable(false);
             pDialog.show();

         }
         protected void onPostExecute(String []result) {
             super.onPostExecute(result);

                 lv.setAdapter(new CustomAdapter(Food.this,FoodText,foodIcon,food_id,userdata));
                 pDialog.dismiss();
             }

        @Override
        protected String [] doInBackground(String... params) {
            // TODO Auto-generated method stub

            JSONArray Food_Text = null;

            ArrayList<HashMap<String, String>> jCatagory = new ArrayList<HashMap<String, String>>();

            getFoods cat=new getFoods();
            String url="http://";
            String jsonStr = cat.viewRecords(url, getFoods.GET, null);
            //Log.d("Records", jsonStr);
            String FoodPath = null;
            if (jsonStr!= null) {

             try {
                 JSONObject jsonObj = new JSONObject(jsonStr);
                 Food_Text = jsonObj.getJSONArray("products");

                 for(int i=0; i<Food_Text.length();i++) {

                     JSONObject c = Food_Text.getJSONObject(i);
                     String foodId = c.getString("food_id");
                   //  Log.d("Cat Id", catId);
                     String food_name = c.getString("name");
                     JSONArray files = c.getJSONArray("files");

                     for(int k = 0; k<files.length();k++){
                         JSONObject filesPart = files.getJSONObject(k);
                          FoodPath = filesPart.getString("path");
                     }

                     catagories.put("path"+i,FoodPath);
                     catagories.put("cat_name"+i, food_name);
                     catagories.put("foodId"+i, foodId);

                   }

                 //System.out.println("catagories Size="+catagories.size());
                 FoodText = new String [catagories.size()/3];
                 foodIcon = new String [catagories.size()/3];
                 food_id = new String[catagories.size()/3];
             }

             catch (JSONException e) {
                 Log.d("catch", "in the catch");
                 e.printStackTrace();
             }

            } else {
             Log.e("JSON Data", "Didn't receive any data from server!");
            }

             for(int k=0; k<catagories.size();k++){
              if(catagories.get("cat_name"+k)==null){
                //continue;
              }else{
              FoodText[k]=catagories.get("cat_name"+k);
              foodIcon[k]=catagories.get("path"+k);
              food_id[k]=catagories.get("foodId"+k);
     //         jokesCates[k]=catagories.get("cat_name"+k);
                //System.out.print("cat_name"+catagories.get("cat_name"+k)+"\n");
                //System.out.print("Path"+catagories.get("path"+k)+"\n");
               }
              }
            return null;
        // TODO Auto-generated method stubs

         }
    }

}//end of class

Silider adapter code goes here
import student.briyani.CustomAdapter.holder;

import com.squareup.picasso.Picasso;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class siliderAdapter extends BaseAdapter {

    String [] text;
    int[] imgIcon;
    Context context;
    private static LayoutInflater inflater=null;
    /*public siliderAdapter(Food food, String [] data, int [] icon){
        text=data;
        imgIcon=icon;
        inflater = ( LayoutInflater )context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }*/
    public siliderAdapter(Food cat, String[] data, int[] icons) {
        // TODO Auto-generated constructor stub
        text=data;
        imgIcon=icons;
         context=cat;
        inflater = ( LayoutInflater )context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return text.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public class holder{
         ImageView img;
         TextView txt;

    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final holder hldr=new holder();
        View rowView = null;
        //Bitmap bitmap = null;
          rowView = inflater.inflate(R.id.navlist, null);
          hldr.txt=(TextView) rowView.findViewById(R.id.siliderText);
          hldr.img=(ImageView) rowView.findViewById(R.id.icon);
          hldr.txt.setText(text[position]);
          hldr.img.setImageResource(imgIcon[position]);
           rowView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
        /*      String food_id=hldr.foodId.getText().toString();
                //Toast.makeText(context, "food_id="+food_id, Toast.LENGTH_LONG).show();
                Bundle b=new Bundle();
                b.putString("food_id", food_id);
                b.putStringArray("images", imgs);
                b.putStringArray("userData", userData);

                Intent Intent=new Intent(context, Menu.class);
                Intent.putExtras(b);
                context.startActivity(Intent);
        */
    Toast.makeText(context, "Hello",Toast.LENGTH_LONG).show();
    }
        });
         return rowView;
    }

}

Eror Message is
> 10-26 11:40:07.633: E/AndroidRuntime(1427): FATAL EXCEPTION: main
> 10-26 11:40:07.633: E/AndroidRuntime(1427):
> android.content.res.Resources$NotFoundException: Resource ID
> #0x7f090050 type #0x12 is not valid 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.content.res.Resources.loadXmlResourceParser(Resources.java:2115)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.content.res.Resources.getLayout(Resources.java:857) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.LayoutInflater.inflate(LayoutInflater.java:394) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.LayoutInflater.inflate(LayoutInflater.java:352) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> student.briyani.siliderAdapter.getView(siliderAdapter.java:68) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.AbsListView.obtainView(AbsListView.java:2033) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.ListView.makeAndAddView(ListView.java:1772) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.ListView.fillDown(ListView.java:672) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.ListView.fillFromTop(ListView.java:732) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.ListView.layoutChildren(ListView.java:1625) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.widget.AbsListView.onLayout(AbsListView.java:1863) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1617)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.onLayout(LinearLayout.java:1401) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.FrameLayout.onLayout(FrameLayout.java:431) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.FrameLayout.onLayout(FrameLayout.java:431) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.widget.FrameLayout.onLayout(FrameLayout.java:431) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.view.View.layout(View.java:11278) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewGroup.layout(ViewGroup.java:4224) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1489)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.os.Handler.dispatchMessage(Handler.java:99) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> android.os.Looper.loop(Looper.java:137) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> android.app.ActivityThread.main(ActivityThread.java:4424) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> java.lang.reflect.Method.invokeNative(Native Method) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> java.lang.reflect.Method.invoke(Method.java:511) 10-26 11:40:07.633:
> E/AndroidRuntime(1427):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
> 10-26 11:40:07.633: E/AndroidRuntime(1427):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 10-26
> 11:40:07.633: E/AndroidRuntime(1427):     at
> dalvik.system.NativeStart.main(Native Method)

A: public siliderAdapter(Food cat, String[] data, int[] icons) {

    text = data;
    imgIcon = icons;
    context = cat;
    inflater = (LayoutInflater)context.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

This line
context = cat;

You assign a Food variable (cat) to a variable of the type Context (context), which is a mistake.
Modify your constructor and pass Context as parameter.
public siliderAdapter(Context ctx, Food cat, String[] data, int[] icons) {

    text = data;
    imgIcon = icons;
    context = ctx;
    inflater = (LayoutInflater)context.
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


text:
Q: Using "sincos" in Java In a lot of situations I not only need the sine, but also the cosine of the same parameter.
For C, there is the sincos function in the common unix m math library. And actually, at least on i386, this should be a single assembly instruction, fsincos.

sincos, sincosf, sincosl - calculate sin and cos simultaneously

I guess these benefits exist because there is an obvious overlap in computing sine and cosine: sin(x)^2 + cos(x)^2 = 1. But AFAIK it does not pay off to try to shortcut this as cos = Math.sqrt(1 - sin*sin), as the sqrt function comes at a similar cost.
Is there any way to reap the same benefits in Java? I guess I'm going to pay a price for a double[] then; which maybe makes all the efforts moot because of the added garbage collection.
Or is the Hotspot compiler smart enough to recognize that I need both, and will compile this to a sincos command? Can I test whether it recognizes it, and can I help it recognizing this, e.g. by making sure the Math.sin and Math.cos commands are directly successive in my code? This would actually make the most sense from a Java language point of view: having the comiler optimize this to use the fsincos assembly call.
Collected from some assembler documentation:
Variations    8087         287        387      486     Pentium
fsin           -            -       122-771  257-354   16-126  NP
fsincos        -            -       194-809  292-365   17-137  NP
 Additional cycles required if operand > pi/4 (~3.141/4 = ~.785)
sqrt        180-186      180-186    122-129   83-87    70      NP

fsincos should need an extra pop, but that should come at 1 clock cycle. Assuming that the CPU also does not optimize this, sincos should be almost twice as fast as calling sin twice (second time to compute cosine; so i figure it will need to do an addition). sqrt could be faster in some situations, but sine can be faster.
Update: I've done some experiments in C, but they are inconclusive. Interestingly enough, sincos seems to be even slightly faster than sin (without cos), and the GCC compiler will use fsincos when you compute both sin and cos - so it does what I'd like Hotspot to do (or does Hotspot, too?). I could not yet prevent the compiler from outsmarting me by using fsincos except by not using cos. It will then fall back to a C sin, not fsin.

A: I have performed some microbenchmarks with caliper. 10000000 iterations over a (precomputed) array of random numbers in the range -4*pi .. 4*pi. I tried my best to get the fastest JNI solution I could come up going - it's a bit hard to predict whether you will actually get fsincos or some emulated sincos. Reported numbers are the best of 10 caliper trials (which in turn consist of 3-10 trials, the average of which is reported). So roughly it's 30-100 runs of the inner loop each.
I've benchmarked several variants:

*

*Math.sin only (reference)

*Math.cos only (reference)

*Math.sin + Math.cos

*sincos via JNI

*Math.sin + cos via Math.sqrt( (1+sin) * (1-sin) ) + sign reconstruction

*Math.cos + sin via Math.sqrt( (1+cos) * (1-cos) ) + sign reconstruction

(1+sin)*(1-sin)=1-sin*sin mathematically, but if sin is close to 1 it should be more precise? Runtime difference is minimal, you save one addition.
Sign reconstruction via x %= TWOPI; if (x<0) x+=TWOPI; and then checking the quadrant. If you have an idea how to do this with less CPU, I'd be happy to hear.
Numerical loss via sqrt seems to be okay, at least for common angles. On the range of 1e-10 from rough experiments.
Sin         1,30 ==============
Cos         1,29 ==============
Sin, Cos    2,52 ============================
JNI sincos  1,77 ===================
SinSqrt     1,49 ================
CosSqrt     1,51 ================

The sqrt(1-s*s) vs. sqrt((1+s)*(1-s)) makes about 0,01 difference. As you can see, the sqrt based approach wins hands down against any of the others (as we can't currently access sincos in pure Java). The JNI sincos is better than computing sin and cos, but the sqrt approach is still faster. cos itself seems to be consistently a tick (0,01) better than sin, but the case distinction to reconstruct the sign has an extra > test. I don't think my results support that either sin+sqrt or cos+sqrt is clearly preferrable, but they do save around 40% of the time compared to sin then cos.
If we would extend Java to have an intrinsic optimized sincos, then this would likely be even better. IMHO it is a common use case, e.g. in graphics. When used in AWT, Batik etc. numerous applications could benefit from it.
If I'd run this again, I would also add JNI sin and a noop to estimate the cost of JNI. Maybe also benchmark the sqrt trick via JNI. Just to make sure that we actually do want an intrinsic sincos in the long run.

A: Most sin and cos calculations are calls directly to the hardware. There isn't much of a faster way to calculate it than that. Specifically, in the range +- pi/4, the rates are extremely fast. If you use hardware acceleration in general, and try to limit the values to those specified, you should be fine. Source.

A: You can always profile.
Generally however, sqrt should come at the same speed as division, as the internal implementation of div and sqrt are very similar.
Sin and cosine, OTOH are calculated with polynomials of up to 10 degrees without any common coefficients and possibly a difficult modulo 2pi reduction -- that is the only common part shared in sincos (when not using CORDIC).
EDIT Revised profiling (with typo corrected) shows timing difference for
sin+cos:  1.580 1.580 1.840 (time for 200M iterations, 3 successive trials)
sincos:   1.080 0.900 0.920
sin+sqrt: 0.870 1.010 0.860

A: Looking at the Hotspot code, I am rather convinced that the Oracle Hotspot VM does not optimize sin(a) + cos(a) into fsincos: See assembler_x86.cpp, line 7482ff.
However, I would suspect that the increased number of machine cycles for using fsin and fcos separately is easily outshadowed by other operations such as running the GC. I would use the standard Java features and profile the application. Only if a profile run indicates that a significant time is spent in the sin/cos calls, I would venture out to do something about it.
In this case, I would create a JNI wrapper that uses a 2-element jdoublearray as out parameter. If you have only one thread that uses the sincos JNI operations, you could use a statically initialized double[2] array in your Java code that would be reused over and over again.

A: There is no fsincos available in regular Java. Also, a JNI version may be slower than a double call to java.lang.Math.sin() and cos().
I guess you are concerned about the speed of sin(x)/cos(x). So I give you a suggestion for fast trigonometric operations, in replacement to fsincos: Look Up Table. Below are my original post. I hope it helps you.
=====
I tried to achieve the best possible performance on trigonometric functions (sin and cos), using Look Up Tables (LUT).
What I have found:

*

*LUT can be 20-25 times faster then java.lang.Math.sin()/cos(). Possible as fast as native fsin / fcos. Maybe as fast as fsincos.

*But java.lang.Math.sin() and cos() are FASTER than any other way to calculate sin/cos, if you use angles between 0 and 45 degree;

*But notice that angles lower than 12 deg has sin(x) almost == x. It is even faster;

*Some implementations use float array to store sin and another one for  cos. This is unnecessary. Just remember that:
cos(x) == sin(x + PI/2)

*

*That is, if you have sin(x) table you have cos(x) table for free.

I did some tests with sin() for angles in range [0..45], using java.lang.Math.sin(); a naive look up table for 360 positions, a optimized LUT90 with table values for range[0..90], but expanded to work with [0..360]; and Look up table with interpolation.Note that after warn-up, java.lang.Math.sin() is faster than others:
Size test: 10000000
Angles range: [0.0...45.0]
Time in ms
Trial | Math.sin() | Lut sin() | LUT90.sin() | Lut sin2() [interpolation]
0    312,5879        25,2280        27,7313      36,4127
1    12,9468         19,5467        21,9396      34,2344
2    7,6811          16,7897        18,9646      32,5473
3    7,7565          16,7022        19,2343      32,8700
4    7,6634          16,9498        19,6307      32,8087

Sources available here GitHub
But, if you need high performance in range[-360..360], java.lang.Math lib is slower. A Look up table (LUT) is around 20 times faster. If high precision is required, you can use LUT with  interpolation, it is a bit slower but still faster than java.lang.Math. See my sin2() in Math2.java, on link above.
Below numbers are for angle high range:
Size test: 10000000
Angles range: [-360.0...360.0]
Time in ms
Trial|Math.sin() | Lut sin() | LUT90.sin() | Lut.sin2() [interpolation]
0    942,7756        35,1488        47,4198      42,9466
1    915,3628        28,9924        37,9051      41,5299
2    430,3372        24,8788        34,9149      39,3297
3    428,3750        24,8316        34,5718      39,5187


text:
Q: jquery.js call from HTML syntax error I have an HTML page generated by an objective-C application and I want to load and open it in a local directory (not in a web server). The javascripts jquery.js and jquery.plot.js are stored in the same directory before the page is loaded.
I made the HTML page by following closely the examples available on http://flot.googlecode.com/
The scripts are declared in the HTML page as follows :
<script src="jquery.js" language="javascript" type="text/javascript"></script>
<script src="jquery.flot.pack.js" language="javascript" type="text/javascript"></script>

When I open the page, the expected graph (generated by the scripts) doesn't show up and I have the following syntax error in the javascript console :
Uncaught SyntaxError: Unexpected token ILLEGAL

The script source in the javascript console is made of strange (chinese ?) ideograms which are obviously "unexpected token" if it is what the browser sees.
I have the same problem with Chrome, Firefox and Safari.
The problem is not systematic because sometimes, it works !.
I have made tests with files prepared manually and again it works sometimes only.
I have also copied the same file which didn't work in another directory where the jquery scripts were present and, surprise, it worked ! but not always...
I have exhausted all my ideas on this problem and your help will be very much appreciated

A: Did you copy the JavaScript from an external source?  I know I have had problems when copying from JSFiddle for example.  Try removing any whitespace and see if that will get rid of the illegal token error.

A: I just had this problem and it was because the server on which my javascript was being hosted wasn't configured to send the javascript file with the correct MIME type.  See this question.
Instead of fixing my server, I just opted to use a CDN path from cdnjs.com:
//cdnjs.cloudflare.com/ajax/libs/flot/0.7/jquery.flot.min.js


text:
Q: tkinter button in class can't call function Total noob, seriously and angrily struggling with Python...
What I'm trying to do SHOULD be simple:

*

*Make a button.

*Connect that button go a function.

*Click button --> run function.

The problem comes when we have to use CLASS (which, no matter how much I read, study - or even pay to take classes continues to make zero sense to me)...
I've tried every concieveable combination of putting this little convert() function IN the class, of adding self.convert or root.convert - and NONE of it works. And, I am clueless why - or what to try next.
Here's the code:
from tkinter import *
from tkinter.ttk import Frame, Button, Style

def convert():
    print("clicked")
    kg = entry_kg.get()
    print(kg)

class Example(Frame):

    def __init__(self):
        super().__init__()

    self.initUI()    # initiate the GUI
    # -------------------------------

    def initUI(self):

        self.master.title("Weight Converter")
        self.pack(fill=BOTH, expand=True)
        # -------------------------------------

        frame_kg = Frame(self)   # frame for Kilograms
        frame_kg.pack(fill=X)

        lbl_kg = Label(frame_kg, text="Kilograms", width=16)
        lbl_kg.pack(side=LEFT, padx=5, pady=5)

        entry_kg = Entry(frame_kg)
        entry_kg.pack(fill=X, padx=(5, 30), expand=True)
        # ------------------------------------------------

        frame_btn = Frame(self)    # frame for buttons
        frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)

        btn_convert=Button(frame_btn, text="Convert", command=convert)
        btn_convert.pack(side=LEFT, padx=5, pady=5)

        # -------------------------------------------

def main():

    root = Tk()
    root.geometry("300x200+300+200")
    app = Example()
    root.mainloop()

if __name__ == '__main__':
    main()

What am I doing wrong?
How to do it right?
The seemingly arbitrary and useless over-complication of a simple task is seriously maddening...

A: If you want your functions to be designed outside of the class, but want to call it from a button defined in the class, the solution is to create a method in your class which takes the input values and then passes them to the external function.
This is called decoupling. Your function is decoupled from the implementation of the UI, and it means that you are free to completely change the implementation of the UI without changing the function, and vice versa. It also means that you can reuse the same function in many different programs without modification.
The overall structure of your code should look something like this:
# this is the external function, which could be in the same
# file or imported from some other module
def convert(kg):
    pounds = kg * 2.2046
    return pounds

class Example(...):
    def initUI(self):
        ...
        self.entry_kg = Entry(...)
        btn_convert=Button(..., command=self.do_convert)
        ...

    def do_convert(self):
        kg = float(self.entry_kg.get())
        result = convert(kg)
        print("%d kg = %d lb" % (kg, result))

A: Here's a modified version of your code that works. The changes have been indicated with ALL CAPS line comments. I obviously misunderstood your question (which does say you could figure out how to make the convert() function part of the class. However, you mentioned you wanted the opposite of that, so I'm modified the code here accordingly.
Essentially the problem boils down to the convert() function needing to access a tkinter.Entry widget that's created somewhere else—inside your Example class in this case.
One way of doing that would be to save the widget in a global variable and access it through the variable name assigned to it. Many folks do that because it's easiest to thing to do, but as you should know, global variables are considered a bad practice and are generally something to be avoided.
There's a common way to avoid needing one with tkinter, which is sometimes called "The extra arguments trick". To use it all you need to do is create a short anonymous function with an argument that has a default value defined—which in this case will be the Entry widget you want passed to the now "wrapped" convert() function. This can be done using what's called a lambda expression. The revised code below and the comments in it show and describe how to do this:
from tkinter import *
from tkinter.ttk import Frame, Button, Style

def convert(entry_widget):  # ADDED WIDGET ARGUMENT
    """ Some function outside class. """
    print("clicked")
    kg = entry_widget.get()  # REFERENCE ENTRY WIDGET PASSED AS ARGUMENT
    print(kg)

class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()    # initiate the GUI

    def initUI(self):
        self.master.title("Weight Converter")
        self.pack(fill=BOTH, expand=True)

        frame_kg = Frame(self)   # frame for Kilograms
        frame_kg.pack(fill=X)

        lbl_kg = Label(frame_kg, text="Kilograms", width=16)
        lbl_kg.pack(side=LEFT, padx=5, pady=5)

        entry_kg = Entry(frame_kg)
        entry_kg.pack(fill=X, padx=(5, 30), expand=True)

        frame_btn = Frame(self)    # frame for buttons
        frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)

        btn_convert=Button(frame_btn, text="Convert",
                        # DEFINE ANONYMOUS FUNCTION WITH DEFAULT ARGUMENT SO IT'S
                        # AUTOMATICALLY PASSED TO THE TARGET FUNCTION.
                        command=lambda entry_obj=entry_kg: convert(entry_obj))
        btn_convert.pack(side=LEFT, padx=5, pady=5)

def main():
    root = Tk()
    root.geometry("300x200+300+200")
    app = Example()
    root.mainloop()

if __name__ == '__main__':
    main()

A: Your entry_kg is not known anywhere outside the scope of initUI method. That is why. You could convert it from a method variable to instance attribute to be within reach for class methods by replacing:
entry_kg = Entry(frame_kg)
entry_kg.pack(fill=X, padx=(5, 30), expand=True)

with:
self.entry_kg = Entry(frame_kg)
self.entry_kg.pack(fill=X, padx=(5, 30), expand=True)

Only then:
You can mention it in a class method like:
...
kg = self.entry_kg.get()

That way you if you make your convert a method under Example again:
def initUI(self):
...
def convert(self):           # is defined under the same scope as initUI
    print("clicked")
    kg = self.entry_kg.get() # notice that it now refers to self.e...
    print(kg)

also don't forget to replace command option as well:
btn_convert=Button(..., command=self.convert)

Or only then:
When outside the class scope, by using dot notation on the object that the class creates:
def main():

    root = Tk()
    root.geometry("300x200+300+200")
    app = Example()
    kg = app.entry_kg.get() # This would return an empty string, but it would still be valid
    root.mainloop()

to be used with global methods, such as the current state of convert you need to make app (the object it is an attribute of) global, or pass it explicitly to the method.


text:
Q: How can I slide up previous text and slide down present text with slider slid? I want to slide up previous slide's sidebar text, and slide down present slide's sidebar text with slider images slid. Here I want to slideup slide-content- when images slid in the slider. html and script are as following:

$('#myCarousel').carousel({
 interval: 5000
});

$('#carousel-text').html($('#slide-content-0').html());

//Handles the carousel thumbnails
$('[id^=carousel-selector-]').click( function(){
 var id_selector = $(this).attr("id");
 var id = id_selector.substr(id_selector.length -1);
 var id = parseInt(id);
 $('#myCarousel').carousel(id);
});

// When the carousel slides, auto update the text
$('#myCarousel').on('slid', function (e){
 $(this).html($('#slide-content-').html());
 var id = $('.item.active').data('slide-number');
 $('#carousel-text').html($('#slide-content-'+id).html());
});

            ‹
            ›

Slider One

Lorem Ipsum Dolor

October 24 2012 - Read more

Slider Two

Lorem Ipsum Dolor

October 24 2012 - Read more

Slider Three

Lorem Ipsum Dolor

October 24 2012 - Read more


text:
Q: ngif not working with $scope variable angular I'm very new to programming and have been struggling with this issue all day.
I am trying to get some text to display based on wether the result of the variable 'buttons.buttonState' is 0 or 1. When I use {{buttons.buttonState}} outside of the ngif it returns the result, so I know it does actually contain the variable.

{{buttons.buttonState}} this returns the value '1'

on

off

Any help would be greatly appreciated!

A: I think you are using angular 1, You should change *ngIf to ng-if.

{{buttons.buttonState}} this returns the value '1'

on

off

A: In angularjs *ngif is used as ng-if

on

off

A: With angularjs syntax it should be ng-if, Replace *ngIf with ng-if

on


text:
Q: php - inline font style for print statement? I know its possible to apply inline styles to echo statements but can this be done with print statements as well?
In my pagination I have links to previous and next records using the greater and less than symbols <> and a running count of the current record against the total number of records. e.g.
<
1/2

or
>
2/2

I have styled them in css but want to decrease the size of the count only. If I make changes to the css the font size for the previous and next links and count all change, I only want to target the count.

<?php if($nextlink != ""){ print ($nextlink."
".$next."/".$count); } ?>

I have tried :

<?php if($nextlink != ""){ print 'style=font:50px' ($nextlink."
".$next."/".$count); } ?>

But get syntax errors.

A: One approach would be to add a class rather than inline styles. However, you have forgotten to append the string correctly.
Here is what I would personally do: (Note I replaced print with echo, TBH, there would be no different)

   <?php
        if($nextlink != "")
            echo ''.($nextlink."
".$next."/".$count).'';

    ?>

If you still want to style it inline, you should simply do:

       <?php
            if($nextlink != "")
                echo ''.($nextlink."
".$next."/".$count).'';

        ?>