Q: How to simplify the JS code in this R shiny code? The below code I found at How to display a scaled up image in an popup window on mouse hover or on click event on an image displayed in a rhandsontable cell in RShiny? (but wrapped in Shiny) almost gets at what I'm trying to do with widgets in rhandsontable. But I don't know enough JS to modify it to do what I want.
I'd like to create a column with a question mark in each row of the table, and hovering over the question mark causes explanatory text to appear in a bubble. Sort of like what happens when running the below code, but the below code is more complex because it renders a miniature image in each column row, and hovering over the miniature images causes the image to bubble out large. I'd like to replace the miniature images with question marks, and when hovering over the question mark explanatory text pops up in a bubble, different text for each row. As shown in the below image:

Any recommendations for how to achieve this?
Code:
library(magrittr)
library(htmlwidgets)
library(rhandsontable)
library(shiny)

DF = data.frame(
  comments = c(
    "I would rate it ★★★★☆",
    "This is the book about JavaScript"
  ),
  cover = c(
    "http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL500_.jpg",
    "http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL500_.jpg"
  ),
  stringsAsFactors = FALSE
)

ui <- fluidPage(br(),rHandsontableOutput('my_table'))

server <- function(input, output, session) {

  output$my_table <- renderRHandsontable({

    rhandsontable::rhandsontable(DF, allowedTags = "<big>",
        callback = htmlwidgets::JS(
        "$(document).ready(function() {
        $('body').prepend('

');
        // onClick function for all plots (img's)
        $('img:not(.zoomImg)').click(function() {
          $('.zoomImg').attr('src', $(this).attr('src')).css({width: '100%'});
          $('.zoomDiv').css({opacity: '1', width: 'auto', border: '1px solid white', borderRadius: '5px', position: 'fixed', top: '50%', left: '50%', marginRight: '-50%', transform: 'translate(-50%, -50%)', boxShadow: '0px 0px 50px #888888', zIndex: '50', overflow: 'auto', maxHeight: '100%'});
        });
        // onClick function for zoomImg
        $('img.zoomImg').click(function() {
          $('.zoomDiv').css({opacity: '0', width: '0%'});
        });
      });"
      ),
      width = 800, height = 450, rowHeaders = FALSE) %>%
      hot_cols(colWidths = c(200, 80)) %>%
      hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
      hot_col(2, renderer = "
        function(instance, td, row, col, prop, value, cellProperties) {
          var escaped = Handsontable.helper.stringify(value),
            img;

          if (escaped.indexOf('http') === 0) {
            img = document.createElement('IMG');
            img.src = value; img.style.width = 'auto'; img.style.height = '80px';

            Handsontable.dom.addEvent(img, 'mousedown', function (e){
              e.preventDefault(); // prevent selection quirk
            });

            Handsontable.dom.empty(td);
            td.appendChild(img);
          }
          else {
            // render as text
            Handsontable.renderers.TextRenderer.apply(this, arguments);
          }
          return td;
        }")
    })
  }

shinyApp(ui, server)

A: Here's an option that doesn't totally do what you're asking, but should get you close if you add some css:

library(magrittr)
library(htmlwidgets)
library(rhandsontable)
library(shiny)

DF = data.frame(
  comments = c(
    "I would rate it ★★★★☆",
    "This is the book about JavaScript"
  ),
  cover = c(
    "https://as1.ftcdn.net/v2/jpg/03/35/13/14/1000_F_335131435_DrHIQjlOKlu3GCXtpFkIG1v0cGgM9vJC.jpg",
    "https://as1.ftcdn.net/v2/jpg/03/35/13/14/1000_F_335131435_DrHIQjlOKlu3GCXtpFkIG1v0cGgM9vJC.jpg"
  ),
  text = c(
    "descriptive text about img 1",
    "descriptive text about img 2"
  ),
  stringsAsFactors = FALSE
)

ui <- fluidPage(br(),rHandsontableOutput('my_table'))

server <- function(input, output, session) {

  output$my_table <- renderRHandsontable({

    rhandsontable::rhandsontable(DF, allowedTags = "<big>",
      width = 800, height = 450, rowHeaders = FALSE) %>%
      hot_cols(colWidths = c(200, 80)) %>%
      hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
      hot_col(2, renderer = "
        function(instance, td, row, col, prop, value, cellProperties) {
          var escaped = Handsontable.helper.stringify(value),
            img;

          if (escaped.indexOf('http') === 0) {
            img = document.createElement('IMG');
            img.src = value; img.style.width = 'auto'; img.style.height = '80px';

            Handsontable.dom.addEvent(img, 'mousedown', function (e){
              var exists = document.getElementById('test')
              if (exists === null){
              var textBlock = instance.params.data[[row]][[2]];
              var popup = document.createElement('div');
              popup.className = 'popup';
              popup.id = 'test';
              var cancel = document.createElement('div');
              cancel.className = 'cancel';
              cancel.innerHTML = 'close';
              cancel.onclick = function(e) {
                popup.parentNode.removeChild(popup)
              }
              var message = document.createElement('span');
              message.innerHTML = '' + textBlock + '';
              popup.appendChild(message);
              popup.appendChild(cancel);
              document.body.appendChild(popup);

              }

            });

            Handsontable.dom.empty(td);
            td.appendChild(img);

          }
          else {
            // render as text
            Handsontable.renderers.TextRenderer.apply(this, arguments);
          }
          return td;
        }") %>%
      hot_cols(colWidths = ifelse(names(DF) != "text", 150, 0.1))
  })
}

shinyApp(ui, server)


Q: Is there a way to have SQL server validate object references in Stored Procs? The following code executes fine in SQL Server
create proc IamBrokenAndDontKnowIt as
select * from tablewhichdoesnotexist

Of course if I try to run it, it fails with

Invalid object name 'tablewhichdoesnotexist'.

Is there any way to compile or verify that Stored Proc are valid?

A: You can use
SET FMTONLY ON
EXEC dbo.My_Proc
SET FMTONLY OFF

You'll need to capture the error(s) somehow, but it shouldn't take much to put together a quick utility application that takes advantage of this for finding invalid stored procedures.
I haven't used this extensively, so I don't know if there are any side-effects to look out for.

A: You used to get a warning message when you tried to create a stored procedure like that.  It would say:

Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object 'dbo.nonexistenttable'. The stored procedure will still be created.

For some reason I'm not getting it now, I'm not sure if it's been changed or if there's just some setting that turns the warning on or off.  Regardless, this should give you a hint as to what's happening here.
SQL Server does track dependencies, but only dependencies which actually exist.  Unfortunately, none of the dependency tricks like sp_depends or sp_MSdependencies will work here, because you're looking for missing dependencies.
Even if we could hypothetically come up with a way to check for these missing dependencies, it would still be trivial to concoct something to defeat the check:
CREATE PROCEDURE usp_Broken
AS

DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM NonExistentTable'
EXEC sp_executesql @sql

You could also try parsing for expressions like "FROM xxx", but it's easy to defeat that too:
CREATE PROCEDURE usp_Broken2
AS

SELECT *
FROM
    NonExistentTable

There really isn't any reliable way to examine a stored procedure and check for missing dependencies without actually running it.
You can use SET FMTONLY ON as Tom H mentions, but be aware that this changes the way that the procedure is "run".  It won't catch some things.  For example, there's nothing stopping you from writing a procedure like this:
CREATE PROCEDURE usp_Broken3
AS

DECLARE @TableName sysname

SELECT @TableName = Name
FROM SomeTable
WHERE ID = 1

DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM ' + @TableName
EXEC sp_executesql @sql

Let's assume you have a real table named SomeTable and a real row with ID = 1, but with a Name that doesn't refer to any table.  You won't get any errors from this if you wrap it inside a SET FMTONLY ON/OFF block.
That may be a contrived problem, but FMTONLY ON does other weird things like executing every branch of an IF/THEN/ELSE block, which can cause other unexpected errors, so you have to be very specific with your error-handling.
The only truly reliable way to test a procedure is to actually run it, like so:
BEGIN TRAN

BEGIN TRY
    EXEC usp_Broken
END TRY
BEGIN CATCH
    PRINT 'Error'
END CATCH

ROLLBACK

This script will run the procedure in a transaction, take some action on error (in the CATCH), and immediately roll back the transaction.  Of course, even this may have some side-effects, like changing the IDENTITY seed if it inserts into a table (successfully).  Just something to be aware of.
To be honest, I wouldn't touch this problem with a 50-foot pole.

A: No (but read on, see last line)
It's by design: Deferred Name Resolution
Erland Sommarskog raised an MS Connect for SET STRICT_CHECKS ON
The connect request has a workaround (not tried myself):

Use check execution plan. The only
  weakness is that you may need
  permissions to see the execution plan
  first

A: You could run sp_depends (see http://msdn.microsoft.com/en-us/library/ms189487.aspx) and use that information to query the information schema (http://msdn.microsoft.com/en-us/library/ms186778.aspx) to see if all objects exist. From what I read here (http://msdn.microsoft.com/en-us/library/aa214346(SQL.80).aspx) you only need to check referenced tables, which is doable.

A: You could check information_schema.tables to check whether a table exist or not and then execute the code
here is quickly slung function to check
 create function fnTableExist(@TableName varchar(64)) returns int as
    begin
        return (select count(*) from information_schema.tables where table_name=@tableName and Table_type='Base_Table')
    end

go

    if dbo.fnTableExist('eObjects') = 0
        print 'Table exist'
    else
        print 'no suchTable'

like wise you can check for existance of Stored procs / functions in
.INFORMATION_SCHEMA.ROUTINES.Routine_name  for th name of the Stored proc/function

A: In SQL 2005 or higher, you can test a stored procedure using transactions and try/catch:
BEGIN TRANSACTION

BEGIN TRY
  EXEC (@storedproc)
  ROLLBACK TRANSACTION
END TRY
BEGIN CATCH
  WHILE @@TRANCOUNT > 0
    ROLLBACK
END CATCH

The algorithm to test all stored procedures in a database is a bit more complicated, as you need to workaround SSMS restrictions if you have many SPs which return many result sets. See my blog for complete solution.

A: I've just discovered that VS2010 with database projects will do syntax and name reference checking. Seems like the best option.


Q: Cannot create "Analysis Services Multidimentional and Datamining" project in Visual Studio 2019 In Visual Studio 2019, I cannot create "Analysis Services Multidimensional and Datamining project" even "Microsoft Analysis Services Projects" extension v2.9.10 is installed and I am able to create "Analysis Services Tabular" project.
Any idea why?

A: I had the same problem.
In extension tab go to -Manage Extensions- -Installed- -Turn off Analysis services extension-
Reopen Visual studio, turn Analysis services extension on.
Reopen Visual studio.
It worked for me :)


Q: Using react hooks, how would you write an event listener dependent on state that does not need to be added and removed every time the state changes? The code below shows a working, but inefficient implementation of an Android BackHandler within React Native to have the app exit after two presses in two seconds. This is implemented using React hooks within the main functional component of the app.
However, due to dependency on a state variable recentlyPressedHardwareBack, the useEffect hook will cleanup then run each time the state changes, causing the BackHandler event listener to be detached and re-attached whenever the back button is pressed. How do you set up this event listener just once without constant creation and deletion, while allowing it to access a changing component state?
const [recentlyPressedHardwareBack, setRecentlyPressedHardwareBack] =
    useState(false);

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      () => {
        // Exit app if user pressed the button within last 2 seconds.
        if (recentlyPressedHardwareBack) {
          return false;
        }

        ToastAndroid.show(
          'Press back again to exit the app',
          ToastAndroid.SHORT,
        );

        setRecentlyPressedHardwareBack(true);

        // Toast shows for approx 2 seconds, so this is the valid period for exiting the app.
        setTimeout(() => {
          setRecentlyPressedHardwareBack(false);
        }, 2000);

        // Don't exit yet.
        return true;
      },
    );

    return () => backHandler.remove();
  }, [recentlyPressedHardwareBack]);

A: You could use useRef for this.
const recentlyPressedHardwareBackRef = useRef(false);
useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      () => {
        // Exit app if user pressed the button within last 2 seconds.
        if (recentlyPressedHardwareBackRef.current) {
          return false;
        }

        ToastAndroid.show(
          'Press back again to exit the app',
          ToastAndroid.SHORT,
        );

        recentlyPressedHardwareBackRef.current = true;

        // Toast shows for approx 2 seconds, so this is the valid period for exiting the app.
        setTimeout(() => {
          recentlyPressedHardwareBackRef.current = false;
        }, 2000);

        // Don't exit yet.
        return true;
      },
    );

    return () => backHandler.remove();
}, [])


Q: How to execute simultaneous PHP CLI scripts in Mac I have 50 php files that I would like to run simultaneously from the command line. Right now, I am running them in multiple CLI windows using the code:
php Script1.php
I would like to be able to call one single script file that would execute all 50 php files simultaneously. I have been reading about how to make the command line not wait for the output, but I can't seem to make it work.
I am new to both MAC and Scripting - maybe I don't need a script? Is there another mac based solultion that can do this without me having to open 50 separate terminal windows?

A: You can just add ampersand '&' to separate each command:
php script1.php & php script2.php & php script3.php ...

This ampersand symbol will tell the shell to run command on background.
To check the output, you can redirect it to a file:
php script1.php > script1.log.txt & php script2.php > script2.log.txt

And you can just do a tail on it to read the log:
tail -f script1.log.txt

A: If you script is nicely numbered from 1 to 50, you can try the following in a .command file:
i=1;
while [ $i -lt 51 ]
do
osascript -e 'tell app "Terminal"
    do script "php Script$i.php"
end tell' &
i=$[$i+1]
done

This should open 50 separate terminal windows each running script{$i}.php

A: You could also run them at the same time but not in the background.
php test1.php; php test2.php;

I don't know why you would want to "interact" with the script after its running.


Q: BASH: how to store subshell variables into an array? I have array1, array2 and a function.
I am trying in a for j=0 to ARRAY_SIZE loop to get the data from array2[j], pass it to a function and the returning output store it in array1[j].
Below is the part of the code that I am working on:
exec 3>&1
${ppart_block_fstype[$i]}=_ppart_block_fstype < <(
    for i in $(eval echo {0..$ARRAY_END})
    do
        if [[ ppart_block_alloc[$i] -eq "ALLOC" ]]
        then
            printf "%s\n" "${ppart_block_num[$i]}" >&3
        fi
    done)
exec 3>&-

_ppart_block_fstype is the function that I have previously defined and will return an output that I will store in array ppart_block_fstype.
The problem of above function is that is using some "heavy tools", hence is not really possible to invoke it at every loop cycle.
This! was a good starting point, but I am stuck on how to make $i visible out of the subshell, and I am also not sure if I am invoking < <( )* in the correct way.


Q: Issue on creating an application for facebook Currently i am creating an sample facebook application. The problem is its asking for my application url in two types. Canvas url and Secure canvas url i had hosted my application on this link Fb app url but the hosting is not providing me ssl i.e. the link with https Because of this problem i am unable to include the Secure canvas url
How can i overcome this issue. How can i solve this. Is there any way to submit the facebook application without secure canvas url or is there any free webhosting site which also provides ssl (https). Please suggest me

A: no you have to get the ssl certificate to secure url
check this What is SSL and what are Certificates? and Https connection without SSL certificate
this is Free SSL Certificate :by Comodo for 90 days but never tried by me

A: try heroku . Facebook provides you that option while you are registering your app.


Q: Java: How to parse string? Just started a programming class a few months ago, and I'm going over some review questions for a test. I'm not sure how to tackle this one. We have to format a few lines of text.
So something that looks like this: 2002/Bourne Identity/Action/1:58
Will have to look like this: 2002 - Bourne Identity Action 118 minutes
There are a few of these, and then we have to add up the total running time for each genre. Would I be right in using the split function here?
Thanks

A: I am assuming that the input data are 4 variables. For example
public String parse(Integer year, String title, String genere, Date duration)

So you just have to operate the values. For example
return year + " - " + title + " " + genere + " " + toMinutes(duration) + " minutes"

where toMinutes(duration) is a function which parse a date to minutes.


Q: If column 1 is a match, change value of column 3 using Awk I have to edit a big file where the columns for each record are not delimited by a character but have a fixed lenght. I would like to search a value in the first column and if found, change the value of the 3rd column.
I can't take the file out from where it is so I can only use the command line with awk, sed and maybe java 5. otherwise I would try other solutions.
bigfile.dat structure:
Column1Col2Column3Column4Col5

Example:
id12345TEXTVALUE01SOMCODETEXT
id23456TEXTVALUE02SOMCODETEXT
id34567TEXTVALUE02SOMCODETEXT
id45678TEXTVALUE01SOMCODETEXT
id56789TEXTVALUE03SOMCODETEXT

What I need: set VALUE04 for id45678
id12345TEXTVALUE01SOMCODETEXT
id23456TEXTVALUE02SOMCODETEXT
id34567TEXTVALUE02SOMCODETEXT
id45678TEXTVALUE04SOMCODETEXT
id56789TEXTVALUE03SOMCODETEXT

I don't know if this is possible. Here is some pseudo code that I thought maybe could work with awk:
if (match id = subtr(Column1))
print subtr(Column1+Col2) + "mychange" +substr(Column4+Col5)
else
print unchanged line

I'm not asking to do my work for me I just don't know I'm wasting my time with the tools I have or I just lack the knowledge.
Thanks.

A: This is actually quite easy to do with awk:
pax: awk <input.txt '/^id45678/{$0=substr($0,1,11)"VALUE04"substr($0,19)}1'
id12345TEXTVALUE01SOMCODETEXT
id23456TEXTVALUE02SOMCODETEXT
id34567TEXTVALUE02SOMCODETEXT
id45678TEXTVALUE04SOMCODETEXT
id56789TEXTVALUE03SOMCODETEXT

It just finds lines beginning with id45678 and modifies that part of the line that you want changed.
The 1 at the end is simply a command to print the line whether changed or not (it's a "trick" using a truth value 1 to select the (default) action of printing the line).

A: Using GNU awk's FIELDWIDTHS for fixed width fields:
$ awk '
BEGIN {
    FIELDWIDTHS="7 4 7 7 4"  3  # set the field widths
    OFS=""
}
$1=="id45678" {                 # when the first field has the given value
    $3="VALUE04"                # replace the third field
}1' file                        # output
Column1Col2Column3Column4Col5
id12345TEXTVALUE01SOMCODETEXT
id23456TEXTVALUE02SOMCODETEXT
id34567TEXTVALUE02SOMCODETEXT
id45678TEXTVALUE04SOMCODETEXT
id56789TEXTVALUE03SOMCODETEXT

A: With GNU sed:
sed -E 's/^(id45678....)......./\1VALUE04/' file

or shorter:
sed -E 's/^(id45678.{4}).{7}/\1VALUE04/' file

and with variables:
s="id45678"
r="VALUE04"
sed -E 's/^('"$s"'.{4}).{7}/\1'"$r"'/' file

Output:

id12345TEXTVALUE01SOMCODETEXT
id23456TEXTVALUE02SOMCODETEXT
id34567TEXTVALUE02SOMCODETEXT
id45678TEXTVALUE04SOMCODETEXT
id56789TEXTVALUE03SOMCODETEXT

If you want to edit your file "in place" use sed's option -i.


Q: Is there any difference between normal and static local variables in static methods? class A
{
    static void f(void)
    {
        int a;
        static int b;
    }
};

Is there any (formal or practical) difference between a and b?

A: Yes, consider the following:
#include <iostream>
using namespace std;

class A
{
    public:
    static void func()
    {
        static int a = 10;
        int b = 10;
        a++;
        b++;
        std::cout << a << " " << b << endl;
    }
};

int main() {
    A a, b;
    a.func();
    b.func();
    a.func();
    return 0;
}

a is shared across all instances of func, but b is local to each instance, so the output is:
11 11
12 11
13 11

http://ideone.com/kwlra3

A: Yes both are different. For every call a will be created whereas b will be created only once and it is same for all the objects of type A. By same I mean, all the objects share a single memory of b.


Q: Mule connector config needs dynamic attributes I have develop a new Connector. This connector requires to be configured with two parameters, lets say:

*

*default_trip_timeout_milis

*default_trip_threshold

Challenge is, I want read ${myValue_a} and ${myValue_a} from an API, using an HTTP call, not from a file or inline values.
Since this is a connector, I need to make this API call somewhere before connectors are initialized.
FlowVars aren't an option, since they are initialized with the Flows, and this is happening before in the Mule app life Cycle.
My idea is to create an Spring Bean implementing Initialisable, so it will be called before Connectors are init, and here, using any java based libs (Spring RestTemplate?) , call API, get values, and store them somewhere (context? objectStore?) , so the connector can access them.
Make sense? Any other ideas?
Thanks!

A: mmm you could make a class that will create the properties in the startup and in this class obtain the API properties via http request. Example below:
 public class PropertyInit implements InitializingBean,FactoryBean {

    private Properties props = new Properties();

    @Override
    public Object getObject() throws Exception {
        return props;
    }

    @Override
    public Class getObjectType() {
        return Properties.class;
    }
 }

Now you should be able to load this property class with:
  <context:property-placeholder properties-ref="propertyInit"/>

Hope you like this idea. I used this approach in a previous project.

A: I want to give you first a strong warning on doing this. If you go down this path then you risk breaking your application in very strange ways because if any other components depend on this component you are having dynamic components on startup, you will break them, and you should think if there are other ways to achieve this behaviour instead of using properties.
That said the way to do this would be to use a proxy pattern, which is a proxy for the component you recreate whenever its properties are changed. So you will need to create a class which extends Circuit Breaker, which encapsulates and instance of Circuit Breaker which is recreated whenever its properties change. These properties must not be used outside of the proxy class as other components may read these properties at startup and then not refresh, you must keep this in mind that anything which might directly or indirectly access these properties cannot do so in their initialisation phase or your application will break.
It's worth taking a look at SpringCloudConfig which allows for you to have a properties server and then all your applications can hot-reload those properties at runtime when they change. Not sure if you can take that path in Mule if SpringCloud is supported yet but it's a nice thing to know exists.


Q: background-image doesn't appear with span class

However the arrow doesn't show up. I double checked the path. It's correct. What wrong am I doing?
I even tried display:block;
No change.

A: You have to triple check you path :)

For a cleaner code, you can write your CSS code outside of style attribute, in a separate file.


Q: How to convert timezone inside bindings? I tried to calculate unfinished downtime duration. Start time is stored in GMT timezone and finish time is local datetime in my timezone (GMT+2 or GMT+3). I want to calculate difference in seconds.
Null datetime is 1900-01-01 00:00:00, so I have expression that means start time is after end time to find unfinished downtimes. Than I get current time and convert it into epoch seconds consigering timezone difference and subtract start time converted into epoch seconds.
In code it looks like
LoadingDowntimes
   (globalobjectid == $CurrentDowntimeGOId &&
   downtimeend.toEpochSecond(ZoneOffset.ofHours(0)) < downtimestart.toEpochSecond(ZoneOffset.ofHours(0)),
   $DowntimesTimeUnfinished : (LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours($CurrentZoneOffset.offset)) - downtimestart.toEpochSecond(ZoneOffset.ofHours(0))))

All parts of this code work corretly in another places, but in this place I have error message
Variables can not be used inside bindings.
Variable [$CurrentZoneOffset] is being used in binding '(LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours($CurrentZoneOffset.offset)) - StringToLocalDateTime(downtimestart).toEpochSecond(ZoneOffset.ofHours(0)))'

I don't know how to make it another way so I need a help with solving this problem.


Q: select sum() from multiple table with same column I have a table for product, sales_item and a stock with following structure
Product table:
+----+-----+-------------+
| id |name |description  |
+----+-----+-------------+
| 1  |Pr1  |prod1        |
+----+-----+-------------+
| 2  |Pr2  |prod2        |
+----+-----+-------------+
| .. |...  |.....        |
+----+-----+-------------+

sales_item_details table
+-----+----------+------------+-----+
| id  | sales_id | product_id | qty |
+-----+----------+------------+-----+
| 517 |      211 |          1 | 200 |
+-----+----------+------------+-----+
| 518 |      211 |          1 | 120 |
+-----+----------+------------+-----+

and production
+----+------------+-------+
| id | product_id | qty   |
+----+------------+-------+
|  1 |          1 |    20 |
|  2 |          2 |   200 |
|  3 |          1 |    20 |
|  4 |          3 |    30 |
|  5 |          9 |    30 |
|  6 |         65 |    10 |
|  7 |         65 |    50 |
|  8 |         71 |    10 |
|  9 |         71 |    10 |
| 10 |         71 |    10 |
+----+------------+-------+

And now I am creating multiple database with same table defination and need to maintain stock
production table and product table will be maintained from single database
only sales_item_details table will be different but product id will same
So how will be the query to get SUM(qty) of sales item details and view the inventory in stock
I have tried this:
SELECT
        `pr`.`id`,
        `pr`.`name`,
        sl.size,
        IFNULL(SUM(s.qty), 0) AS sales,
        IFNULL((SELECT SUM(qty) FROM production st WHERE st.product_id = `pr`.`product-id`), 0) AS stock_added
    FROM products pr
        LEFT JOIN (
            SELECT qty, product_id FROM db1.sales_item_details
            UNION ALL
            SELECT qty, product_id FROM db2.sales_item_details
        ) s ON pr.`id` = s.product_id
        LEFT JOIN size_list sl ON sl.id = `pr`.`product-size`
    GROUP BY s.product_id
    ORDER BY sales DESC

but getting the product which is sold
Any help will be appriciated

A: 1st I created a view holding all sales items grouped by product id in the main database:
CREATE OR REPLACE VIEW unit_sold_all  AS
    SELECT
        p.`product-id` AS product_id,
        (
            (SELECT IFNULL(SUM(s0.qty), 0) FROM db_1.sales_item_details s0 WHERE s0.product_id = p.`product-id`) +
            (SELECT IFNULL(SUM(s1.qty), 0) FROM db_2.sales_item_details s1 WHERE s1.product_id = p.`product-id`) +
            (SELECT IFNULL(SUM(s2.qty), 0) FROM db_3.sales_item_details s2 WHERE s2.product_id = p.`product-id`) +
            (SELECT IFNULL(SUM(s3.qty), 0) FROM db_4.sales_item_details s3 WHERE s3.product_id = p.`product-id`) +
            (SELECT IFNULL(SUM(s4.qty), 0) FROM db_5.sales_item_details s4 WHERE s4.product_id = p.`product-id`)
        ) as total_unit_sales
FROM products p

Then in another sql, I selected the sum of the sales.
PS: I answered this question myself because this might need by another person in the future.


Q: Jquery how to make div visible after valid mail is written I wanna make form, which will show its next part, after valid email adress is written in input. I have some code to validate, but i need some code, which will wait until email adress is in input.
<input style="border-radius: 4px;" name="editsubsemail" type="text" id="editsubsemail" size="40"/>

This is jquery code and i need to replace that .click (just placeholder) with something, that will check, if that "editsubsemail" is filled with email
var visibility_edit = false;
$("#changesubs-wraper").click(function(){
if( visibility_edit == false ){
    $('#change-info-wraper').show("slow");
    $('#delete-subs-wraper').show("slow");
    visibility_edit = true;
} else {
    $('#change-info-wraper').hide("slow");
    $('#delete-subs-wraper').hide("slow");
    visibility_edit = false;
}
});

A: Check out this seminar registration demo form on css-tricks. It looks like it could solve your problem with a little tweaking. Here is the source.

A: For: <input name='email' type='email' id='email'> and

This is some untested code:
$('#email').on( 'change', function() {
  if( email_regex_must_be_here ) {
    //this is a valid email
    $('#somediv').show();
  }
  else {
    $('#somediv').hide();
  }
} );

Harry's link might be better at helping you though.


Q: How can i show the count value as well as % on my highchart pie chart?

var json=
[
    {
        "a": "OOCBER",
        "b": "OOCL BERLIN",
        "c": "CHINA",
        "d": "GREAT BRITAIN",
        "e": "*PI",
        "f": "NGB",
        "g": "CN",
        "i": "GB",
        "j": "9PIO5090196",
        "k": "2PI5090420",
        "l": "WL15802C/D",
        "m": "NB1500682",
        "n": 9,
        "o": 6,
        "p": "2015-09-14",
        "q": "2015-09-14",
        "s": 4,
        "u": "40HC",
        "v": "TLU7564566",
        "w": "CN074909",
        "x": "LEIGH",
        "y": "NINGBO",
        "z": 395,
        "B": 68,
        "C": 7987.5,
        "D": "534",
        "E": "Chunghy",
        "F": "07405",
        "G": "PIF",
        "H": "FB",
        "I": "NIGBO",
        "J": "NGB",
        "K": "2015-09-12",
        "L": "2015-09-29T10:05",
        "M": "2015-09-29T10:05",
        "Y": "SOUTHAMPTON",
        "zp": "SOU",
        "N": "2015-10-21",
        "O": "2015-09-22T17:40",
        "P": "2015-09-22T17:40",
        "Q": "2015-10-21T12:54",
        "R": "2015-10-22T14:13",
        "S": "2015-10-27T10:30",
        "T": "2015-10-27T10:30",
        "U": "2015-10-27T10:30",
        "V": true,

    }, etc......

I am looking to display the actual count number as well as the % on my pie chart. As it stand it just shows the % but I want the actual count number to be displayed next to it. On my snippet look for *** Actual count here value ***. I tried point.y but that didn't give me the correct value. Please help.
$(function() {
  var ContainerCounts = {};
  var ContainerTypes = [];
  var totalCount = 0;

  //loop through the object
  $.each(json, function(key, val) {
    //get the container name
    var ContainerType = val["u"];

    //build array of unique container names
    if ($.inArray(ContainerType, ContainerTypes) == -1) {
      ContainerTypes.push(ContainerType);
    }

    //add or increment a count for the container name
    if (typeof ContainerCounts[ContainerType] == 'undefined') {
      ContainerCounts[ContainerType] = 1;
    } else {
      ContainerCounts[ContainerType] ++;
    }

    //increment the total count so we can calculate %
    totalCount++;
  });

  //console.log(ContainerTypes);

  var data = [];
  //loop through unique countries to build data for chart
  $.each(ContainerTypes, function(key, ContainerType) {
    data.push({
      name: ContainerType,
      y: Math.round((ContainerCounts[ContainerType] / totalCount) * 100)
    });
  });
  //console.log(data);

  function popchart_shipment_breakout() {
    $('#container_shipment_breakout').highcharts({
      chart: {
        type: 'pie',
        options3d: {
          enabled: false,
          alpha: 45,
          beta: 0
        }
      },
      title: {
        text: 'Break out of shipments'
      },
      tooltip: {
        pointFormat: '*** Actual count here value *** {point.percentage:.1f}%'
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          depth: 35,
          innerSize: 150,

          dataLabels: {
            enabled: true
          }
        }
      },
    });
    chart = $('#container_shipment_breakout').highcharts();
    chart.addSeries({
      data: data
    });
  }

  popchart_shipment_breakout();
});

A: Just use this.y instead of point.percentage
OR
Use below code to format the tooltip.
tooltip: {
        formatter: function () {
            return '' + this.y + '';
        }
    }


Q: Bottleneck of Web Applications I am developing a web application using django, postgreSQL, html5 and javascript. The application is javacript intensive and is both read/write intensive. What are some common bottlenecks? What are some things to keep in mind when designing a web application that scales well? What are some tips to improve performance?
Thanks!

A: Database database database. Make sure you can add more db servers without lots of pain.
Adding app servers is usually fairly straightforward, but DB replication/clustering can get tricky.

A: It depends. It depends on how your application is used. You cannot tell until you know how many users will do concurrent requests. Most of the time it will be your database, depending on how many requests per second it can manage.
So if you know your application patterns (read intensive or write intensive) you can design it for easier scaling. Would it be enough to just do replication?

A: Your problem from day 1 will be the time taken for the client to download the content from your server. CDN's, minification and combining assets should be a primary concern.
(Un)fortunatly, unless you go Google, you won't become big enough to require multiple application, database servers (no offence).

A: A couple suggestions:
1) Since you said read write intensive you need to decide how you will be structuring your database to be more read or write friendly. What will be happening most often. If it is reads then indexes are your friend. If it is writes then be careful of going index crazy.
2) On the client side be careful of writing to the live DOM too often. If you need to do do a lot of loads of say table rows, load them into a parent element in memory and then load that parent element into the DOM all at once.

A: You may take a look at http://ilian.i-n-i.org/tag/cache/ there are three articles about caching and how it will help your website.
As for the scales well... are you sure that your application needs it?
Do not get me wring, it is awesome to have multiple database servers, CDN, load balancers etc. but do you really need it? If you are starting a new project you should focus on providing a stable features more than optimizing it for a million hits per day cause you are probably not going to make them(at least in the beginning).
Start with caching, it is easy to implement and effective if it is correctly used. When your visitors get so much that you reach the bottle necks think for them then but not earlier.
The above does not mean that you should write the slowest code that is possible. It only means that the need for extreme scalability comes when you have working application and that if you waste 1 year and a ton gold to build it probably you will miss the moment.


Q: Convert AMPL Model to ORTools I am trying to convert my AMPL Model to ORTools. This is the model:
set NUTR;
set FOOD;

param cost {FOOD} > 0;
param f_min {FOOD} >= 0;
param f_max {j in FOOD} >= f_min[j];

param n_min {NUTR} >= 0;
param n_max {i in NUTR} >= n_min[i];

param amt {NUTR,FOOD} >= 0;

var Buy {j in FOOD} >= f_min[j], <= f_max[j];

minimize Total_Cost:  sum {j in FOOD} cost[j] * Buy[j];

subject to Diet {i in NUTR}:
   n_min[i] <= sum {j in FOOD} amt[i,j] * Buy[j] <= n_max[i];

This is my semi python code for ORTools. I don't know if Buy is correct and how to add the constraint:
Buy = {}
for f_ in FOOD:
    Buy[f_] = solver.IntVar(0, 1000, 'Buy[%s]' % (f_,))

##  Objective Function
Total_Cost = solver.Sum([cost[j_] * Buy[j_] for j_ in FOOD])

##  Constraints
for i in NUTR:
    for j in FOOD:
        print(amt[i,j] *Buy[j])
        #solver.Add( solver.Sum(amt[i,j] * Buy[j] <= n_max[i]  ))

solver.Minimize(Total_Cost)

A: wrong parenthesis
  solver.Add( solver.Sum(amt[i,j] * Buy[j]) <= n_max[i] )


Q: How to reference Column data in a rolling window calculation? Error ValueError: window must be an integer 0 or greater I am currently working on a large DF and need to reference the data in a column for a rolling window calculation. All rows have a separate rolling window value so i need to reference the column but i am getting the out put
    ValueError: window must be an integer 0 or greater

    import numpy as np
    import pandas as pd

    df = pd.DataFrame(np.random.randint(0,20,size=(20, 4)), columns=list('abcd'))

    df['op'] = (np.random.randint(0,20, size=20))

        a   b   c   d   op
    0   6   17  3   5   9
    1   8   3   13  7   2
    2   19  12  18  3   8
    3   8   8   5   4   17
    4   0   5   9   3   19
    5   0   5   19  9   11
    6   7   7   13  8   10
    7   7   5   12  0   4
    8   13  17  4   4   17
    9   7   0   16  9   7
    10  7   8   13  10  13
    11  18  3   1   11  16
    12  4   4   5   13  4
    13  9   8   14  19  9
    14  13  10  10  7   10
    15  9   16  11  16  3
    16  5   7   3   0   11
    17  13  14  10  1   16
    18  6   14  13  4   18
    19  1   9   8   0   19

trying to reference the value in df['op'] for a rolling average.
    df['SMA'] = df.a.rolling(window=df.op).mean()

produces Error ValueError: window must be an integer 0 or greater
As mentioned i am working on a large data frame so the above is example code.

A: Solution
    import numpy as np
    import pandas as pd

    df = pd.DataFrame(np.random.randint(0,20,size=(20, 4)),
    columns=list('abcd'))

    df['op'] = (np.random.randint(0,20, size=20))

    def lookback_window(row, values, lookback, method='mean', *args, **kwargs):
        loc = values.index.get_loc(row.name)
        lb = lookback.loc[row.name]
        return getattr(values.iloc[loc - lb: loc + 1], method)(*args, **kwargs)

    df['SMA'] = df.apply(lookback_window, values=df['a'], lookback=df['op'], axis=1)

    df

    a      b    c   d   op  SMA
    0   17  19  11  9   0   17.000000
    1   0   10  9   11  19  NaN
    2   13  8   11  2   16  NaN
    3   9   2   4   4   8   NaN
    4   11  10  0   17  18  NaN
    5   14  19  17  10  17  NaN
    6   6   12  17  1   4   10.600000
    7   10  1   3   18  2   10.000000
    8   7   6   12  3   19  NaN
    9   1   9   7   5   9   8.800000
    10  17  1   3   13  1   9.000000
    11  19  17  0   2   7   10.625000
    12  18  5   2   4   12  10.923077
    13  18  5   4   2   1   18.000000
    14  5   11  17  11  11  11.250000
    15  16  9   2   11  16  NaN
    16  15  17  1   8   14  11.933333
    17  15  2   0   3   6   15.142857
    18  18  3   18  3   10  13.545455
    19  7   0   12  15  3   13.750000


Q: text from With statement to geometry and geography WITH values(location, userid) as (
VALUES (st_geomfromewkt('0101000000000000C04141464000000000FE174440'),5))

SELECT st_distance(p.location,(SELECT location FROM values where v.userid = "blacklisterId")::geometry)
FROM values as v,live.partners as p
Inner JOIN backend.cars c ON (c."userId" = p."partnerId" AND c.active = true)
Inner JOIN backend."carCompatibleTariffs" cCT ON c."carId" = cCT."carId" and  1 = cCT."tariffId" AND cCT.active = true
LEFT JOIN backend."userBlacklist" bl on 5 = bl."blacklisterId" AND p."partnerId" = bl."blacklistedId"
WHERE bl."blacklistedId" ISNULL
--AND st_dwithin(p.location::geography,(SELECT FROM values where v.userid = "blacklisterId")::geography,1500)
--ORDER BY st_distance(p.location,(SELECT location FROM values where v.userid = "blacklisterId")::geometry) ASC;

How to take text values table as geometry or geography,I tried to make it with ST_GeographyFromText,ST_GeogmetryFromText and with st_makepoint((Select st_x),(Select st_y)) but it always return null,how can I solve this ?

A: Your problem might be somewhere else. Your geometry seems to be valid:
WITH values(location, userid) AS
(VALUES ('0101000000000000C04141464000000000FE174440',5),
        ('0101000000000000200A45464000000000D7174440',16))
SELECT ST_Distance(location::GEOMETRY,ST_GeomFromText('POINT(44 45)')) FROM values;

   st_distance
------------------
 4.83948955585514
 4.84387473202619
(2 Zeilen)

Here a few examples on different types of geometry literals:
ST_GeomFromText
db=# SELECT ST_GeomFromText('POINT(1 2)');
              st_geomfromtext
--------------------------------------------
 0101000000000000000000F03F0000000000000040
(1 Zeile)

ST_GeomFromGeoJSON:
db=# SELECT ST_GeomFromGeoJSON('{"type":"Point","coordinates":[1,2]}');
             st_geomfromgeojson
--------------------------------------------
 0101000000000000000000F03F0000000000000040
(1 Zeile)

ST_GeomFromEWKT:
db=# SELECT ST_GeomFromEWKT('SRID=4269;POINT(1 2)');
                  st_geomfromewkt
----------------------------------------------------
 0101000020AD100000000000000000F03F0000000000000040
(1 Zeile)

ST_GeomFromGML:
db=# SELECT ST_GeomFromGML('<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>');
               st_geomfromgml
--------------------------------------------
 0101000000000000000000F03F0000000000000040
(1 Zeile)

ST_GeomFromKML:
db=# SELECT ST_GeomFromKML('<Point><coordinates>1,2</coordinates></Point>');
                   st_geomfromkml
----------------------------------------------------
 0101000020E6100000000000000000F03F0000000000000040
(1 Zeile)

A: This could have been your intention:

WITH vvv(location, userid) as (
    VALUES (st_geomfromewkt('0101000000000000C04141464000000000FE174440'),5)
    )
SELECT st_distance(p.location, v.location::geometry) AS THE_DISTANCE
FROM vvv as v
JOIN live.partners as p
    ON p."partnerId" = v.userid
WHERE EXISTS (
    SELECT *
    FROM backend.cars c
    JOIN backend."carCompatibleTariffs" cCT
            ON c."carId" = cCT."carId"
            AND cCT."tariffId" = 1 AND cCT.active = true
    WHERE c."userId" = p."partnerId"
    AND c.active = true
    )
AND NOT EXISTS(
    SELECT * FROM backend."userBlacklist" bl
    WHERE p."partnerId" = bl."blacklistedId"
    AND 5 = bl."blacklisterId"
    )
    ;


Q: How do I deduplicate a list based on hourly intervals in Java? First of all, I have this object that I call MyObject;
public class MyObject{
    private google.protobuf.Timestamp timestamp;
    private String description;
}

Then I have this list:
List<MyObject> myList = new ArrayList<>();

Now let's imagine that myList contains 500 items. What I want, is to eliminate duplicates (identical descriptions) that occur within the same hour.
So two different items with identical descriptions should not both exist in the list within the same hour. If they do, we want to only keep one and delete the other.
Example:
If the list contains the following two items:
06-07-2022T01:30:00, "some random description" and 06-07-2022T01:35:00, "some random description"
Then we want to delete one of them because they have identical description and are within the same hour.
But if we have this:
06-07-2022T01:30:00, "some random description" and 06-07-2022T03:20:00, "some random description"
Then we don't want to delete any of them as they are not within the same hour.
How do I do that?

A: Based on the clarifications you've given in the comments I've used a LocalDateTime to simplify the sample entry and retrieve the hour, but I'm sure that google.protobuf.Timestamp can be converted to a proper date and extract its hour.
To keep only one object according to description, date and hour, I've added a helper method to your POJO to get a concatenation of these fields and then group by their result value in order to get a Map where to each key (description, date and hour) there is only one object associated. Lastly, I've collected the Map's values into a List.
List<MyObject> list = new ArrayList<>(List.of(
        new MyObject(LocalDateTime.parse("06-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
        new MyObject(LocalDateTime.parse("06-07-2022T01:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
        new MyObject(LocalDateTime.parse("06-07-2022T03:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"),
        new MyObject(LocalDateTime.parse("06-07-2022T04:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
        new MyObject(LocalDateTime.parse("06-07-2022T04:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
        new MyObject(LocalDateTime.parse("06-07-2022T06:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"),
        new MyObject(LocalDateTime.parse("08-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description")
));

List<MyObject> listRes = list.stream()
        .collect(Collectors.toMap(
                obj -> obj.getDescrDateHour(),
                Function.identity(),
                (obj1, obj2) -> obj1
        ))
        .values()
        .stream().
        collect(Collectors.toList());

POJO Class
class MyObject {
    private LocalDateTime timestamp;
    private String description;

    public MyObject(LocalDateTime timestamp, String description) {
        this.timestamp = timestamp;
        this.description = description;
    }

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public String getDescription() {
        return description;
    }

    public String getDescrDateHour() {
        return description + timestamp.toLocalDate().toString() + timestamp.getHour();
    }

    @Override
    public String toString() {
        return timestamp + " - " + description;
    }
}

Here is a link to test the code
https://www.jdoodle.com/iembed/v0/sZV
Output
Input:
2022-07-06T01:30 - some random description
2022-07-06T01:35 - some random description
2022-07-06T03:20 - some random description
2022-07-06T04:30 - some random description2
2022-07-06T04:35 - some random description2
2022-07-06T06:20 - some random description2
2022-07-08T01:30 - some random description

Output:
2022-07-06T04:30 - some random description2
2022-07-08T01:30 - some random description
2022-07-06T06:20 - some random description2
2022-07-06T03:20 - some random description
2022-07-06T01:30 - some random description

A: A quiet simple solution would be a HashMap. You use description as key and timestamp as value. So you always save only the last timestamp to given description and overwrite it automaticly.
If you want to hold your Object I would just sort the list by date, then fill in a HashMap and transform the HashMap to List again. It has not the best Performance, but its easy. You can Sort by Date with functional Java sorting a Collection in functional style

A: You could define an equality calculating class (or do it in the MyObject class, depending on what it actually represents) and use it to find unique values based on the equality definition. In this case equality would mean: same description and same timestamp with hourly precision.
Here's an example (might need some tweaking, just a concept presentation):

class UniqueDescriptionWithinHourIdentifier {

    // equals and hashCode could also be implemented in MyObject
    // if it's only purpose is data representation
    // but a separate class defines a more concrete abstraction

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHH");

    private Date timestamp;
    private String description;

    UniqueDescriptionWithinHourIdentifier(MyObject object) {
        timestamp = object.timestamp;
        description = object.description;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object == null || getClass() != object.getClass()) {
            return false;
        }
        var other = (UniqueDescriptionWithinHourIdentifier) object;
        return description.equals(other.description)
               // compare the timestamps however you want - format used for simplicity
               && DATE_FORMAT.format(timestamp)
                             .equals(DATE_FORMAT.format(other.timestamp));
    }

    @Override
    public int hashCode() {
        // cannot contain timestamp - a single hash bucket will contain multiple elements
        // with the same definition and the equals method will filter them out
        return Objects.hashCode(description);
    }
}

class MyObjectService {

    // here a new list without duplicates is calculated

    List<MyObject> withoutDuplicates(List<MyObject> objects) {
        return List.copyOf(objects.stream()
                                  .collect(toMap(UniqueDescriptionWithinHourIdentifier::new,
                                                 identity(),
                                                 (e1, e2) -> e1,
                                                 LinkedHashMap::new))
                                  .values());
    }

}

A: Add equals & hashcode method to your MyObject class with equals has some logic like below:
@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyObject other = (MyObject) obj;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(timestamp);
        int hour1=calendar.HOUR;
        int date1 = calendar.DATE;
        calendar.setTime(other.timestamp);
        int hour2 = calendar.HOUR;
        int date2  =calendar.DATE;
        return Objects.equals(hour1, hour2) && Objects.equals(date1, date2);
    }

Here, basically I am checking if 2 objects has same hour & date & if so, just ignore another object.
Once you do that, you can just use :
List<MyObject> myList = new ArrayList<>();
myList.stream().distinct().collect(Collectors.toList()); // returns you new distinct objects list.

Please note, you can use default implementation of hashCode generated via your editor for this case. distinct() method of stream is checking if you have equals & hashcode available for underlying streams class.
Note: you can extend equals to check day , date, month, year etc. for verifying exact date.


Q: Can i store a pointer to RAM in flash at compile time My problem explained:
On my microcontroller (Atmel AT90CAN128) i have about 2500 bytes of RAM left.
In those 2500 bytes i need to store 5 times 100 data sets (size could change in the future). The data sets have a predefined but varying length between 1 and 9 bytes. The total bytes that the pure data sets occupy is about 2000 bytes. I now need to be able to access the data sets in an array like fashion by passing a uint8 to a function and get a pointer to the data set in return.
But i only have about 500 bytes left, so an array with pointers to each data set (calculated at start of run time) is simply not possible.
My attempt:
i use one big uint8 array[2000] (in RAM) and the length of the data sets is stored in flash as const uint8[] = {1, 5, 9, ...};.
The position of the data set in the big array is the accumulated length of the sets before it. So i would have to iterate through the length array and add the values up and then use it as an offset to the pointer of the big data array.
At runtime this gives me bad performance. The position of the data sets within the big array IS KNOWN at compile time, I just dont know how to put this information into an array that the compiler can store into flash.
As the amount of data sets could change, i need a solution that automatically calculates the positions.
Goal:
something like that
uint8 index = 57;
 uint8 *pointer_to_data = pointer_array[57];
Is this even possible, as the compiler is a 1 pass comiler ?
(I am using Codevision, not avr gcc)
My solution
The pure C solution/answer is technically the right answer for my question but it just seems overly complicated (from my perspective). The idea with the build script seemed better but codevision is not very practical in that way.
So i ended up with a bit of a mix.
I wrote a javascript that writes the C code/definition of the variables for me. The raw-definitions are easy to edit and i just copy paste the whole thing into a html text file and open it in a browser and copy paste the content back into my C file.
In the beginning i was missing a crucial element and that is the position of the 'flash' keyword in the definition. The following is a simplified output of my javascript that compiles just the way i like it.
flash uint8 len[150] = {4, 4, 0, 2, ...};

uint8 data1[241] = {0}; //accumulated from above

uint8 * flash pointers_1[150] = {data1 +0, data1 +4, data1 +0, data1 +8, ...};

The ugly part (lots of manual labor without script) is adding up the length for each pointer as the compiler will only compile if the pointer is increased by a constant and not a value stored in a constant array.
The raw definitions that are fed to the javascript then look like this
var strings = [
"len[0] = 4;",
"len[1] = 4;",
"len[3] = 2;",
...

Within the javascript it is an array of strings, this way i could copy my old definitions into it and just add some quotes. I only need to define the ones that i want to use, index 2 is not defined and the script uses length 0 for it but does include it. The macro would have needed an entry with 0 i guess, which is bad for overview in my case.
It is not a one click solution but it is very readable and tidy which makes up for the copy-paste.

A: One common method of packing variable-length data sets to a single continuous array is using one element to describe the length of the next data sequence, followed by that many data items, with a zero length terminating the array.
In other words, if you have data "strings" 1, 2 3, 4 5 6, and 7 8 9 10, you can pack them into an array of 1+1+1+2+1+3+1+4+1 = 15 bytes as 1 1 2 2 3 3 4 5 6 4 7 8 9 10 0.
The functions to access said sequences are quite simple, too. In OP's case, each data item is an uint8:
uint8  dataset[] = { ..., 0 };

To loop over each set, you use two variables: one for the offset of current set, and another for the length:
uint16 offset = 0;

while (1) {
    const uint8  length = dataset[offset];
    if (!length) {
        offset = 0;
        break;
    } else
        ++offset;

    /* You have 'length' uint8's at dataset+offset. */

    /* Skip to next set. */
    offset += length;
}

To find a specific dataset, you do need to find it using a loop. For example:
uint8 *find_dataset(const uint16  index)
{
    uint16  offset = 0;
    uint16  count = 0;

    while (1) {
        const uint8  length = dataset[offset];
        if (length == 0)
            return NULL;
        else
        if (count == index)
            return dataset + offset;

        offset += 1 + length;
        count++;
    }
}

The above function will return a pointer to the length item of the index'th set (0 referring to the first set, 1 to the second set, and so on), or NULL if there is no such set.
It is not difficult to write functions to remove, append, prepend, and insert new sets. (When prepending and inserting, you do need to copy the rest of the elements in the dataset array forward (to higher indexes), by 1+length elements, first; this means that you cannot access the array in an interrupt context or from a second core, while the array is being modified.)

If the data is immutable (for example, generated whenever a new firmware is uploaded to the microcontroller), and you have sufficient flash/rom available, you can use a separate array for each set, an array of pointers to each set, and an array of sizes of each set:
static const uint8   dataset_0[] PROGMEM = { 1 };
static const uint8   dataset_1[] PROGMEM = { 2, 3 };
static const uint8   dataset_2[] PROGMEM = { 4, 5, 6 };
static const uint8   dataset_3[] PROGMEM = { 7, 8, 9, 10 };

#define  DATASETS  4

static const uint8  *dataset_ptr[DATASETS] PROGMEM = {
    dataset_0,
    dataset_1,
    dataset_2,
    dataset_3,
};

static const uint8   dataset_len[DATASETS] PROGMEM = {
    sizeof dataset_0,
    sizeof dataset_1,
    sizeof dataset_2,
    sizeof dataset_3,
};

When this data is generated at firmware compile time, it is common to put this into a separate header file, and simply include it from the main firmware .c source file (or, if the firmware is very complicated, from the specific .c source file that accesses the data sets). If the above is dataset.h, then the source file typically contains say
#include "dataset.h"

const uint8  dataset_length(const uint16  index)
{
    return (index < DATASETS) ? dataset_len[index] : 0;
}

const uint8 *dataset_pointer_P(const uint16  index)
{
    return (index < DATASETS) ? dataset_ptr[index] : NULL;
}

i.e., it includes the dataset, and then defines the functions that access the data. (Note that I deliberately made the data itself static, so they are only visible in the current compilation unit; but the dataset_length() and dataset_pointer(), the safe accessor functions, are accessible from other compilation units (C source files), too.)
When the build is controlled via a Makefile, this is trivial. Let's say the generated header file is dataset.h, and you have a shell script, say generate-dataset.sh, that generates the contents for that header. Then, the Makefile recipe is simply
dataset.h: generate-dataset.sh
    @$(RM) $@
    $(SHELL) -c "$^ > $@"

with the recipes for the compilation of the C source files that need it, containing it as a prerequisite:
main.o: main.c dataset.h
    $(CC) $(CFLAGS) -c main.c

Do note that the indentation in Makefiles always uses Tabs, but this forum does not reproduce them in code snippets. (You can always run sed -e 's|^  *|\t|g' -i Makefile to fix copy-pasted Makefiles, though.)
OP mentioned that they are using Codevision, that does not use Makefiles (but a menu-driven configuration system). If Codevision does not provide a pre-build hook (to run an executable or script before compiling the source files), then OP can write a script or program run on the host machine, perhaps named pre-build, that regenerates all generated header files, and run it by hand before every build.

In the hybrid case, where you know the length of each data set at compile time, and it is immutable (constant), but the sets themselves vary at run time, you need to use a helper script to generate a rather large C header (or source) file. (It will have 1500 lines or more, and nobody should have to maintain that by hand.)
The idea is that you first declare each data set, but do not initialize them. This makes the C compiler reserve RAM for each:
static uint8  dataset_0_0[3];
static uint8  dataset_0_1[2];
static uint8  dataset_0_2[9];
static uint8  dataset_0_3[4];
/*                      : :  */
static uint8  dataset_0_97[1];
static uint8  dataset_0_98[5];
static uint8  dataset_0_99[7];
static uint8  dataset_1_0[6];
static uint8  dataset_1_1[8];
/*                      : :  */
static uint8  dataset_1_98[2];
static uint8  dataset_1_99[3];
static uint8  dataset_2_0[5];
/*                    : : :  */
static uint8  dataset_4_99[9];

Next, declare an array that specifies the length of each set. Make this constant and PROGMEM, since it is immutable and goes into flash/rom:
static const uint8  dataset_len[5][100] PROGMEM = {
    sizeof dataset_0_0, sizeof dataset_0_1, sizeof dataset_0_2,
    /* ... */
    sizeof dataset_4_97, sizeof dataset_4_98, sizeof dataset_4_99
};

Instead of the sizeof statements, you can also have your script output the lengths of each set as a decimal value.
Finally, create an array of pointers to the datasets. This array itself will be immutable (const and PROGMEM), but the targets, the datasets defined first above, are mutable:
static uint8 *const dataset_ptr[5][100] PROGMEM = {
    dataset_0_0, dataset_0_1, dataset_0_2, dataset_0_3,
    /* ... */
    dataset_4_96, dataset_4_97, dataset_4_98, dataset_4_99
};

On AT90CAN128, the flash memory is at addresses 0x0 .. 0x1FFFF (131072 bytes total). Internal SRAM is at addresses 0x0100 .. 0x10FF (4096 bytes total). Like other AVRs, it uses Harvard architecture, where code resides in a separate address space -- in Flash. It has separate instructions for reading bytes from flash (LPM, ELPM).
Because a 16-bit pointer can only reach half the flash, it is rather important that the dataset_len and dataset_ptr arrays are "near", in the lower 64k. Your compiler should take care of this, though.
To generate correct code for accessing the arrays from flash (progmem), at least AVR-GCC needs some helper code:
#include <avr/pgmspace.h>

uint8 subset_len(const uint8 group, const uint8 set)
{
    return pgm_read_byte_near(&(dataset_len[group][set]));
}

uint8 *subset_ptr(const uint8 group, const uint8 set)
{
    return (uint8 *)pgm_read_word_near(&(dataset_ptr[group][set]));
}

The assembly code, annotated with the cycle counts, avr-gcc-4.9.2 generates for at90can128 from above, is
subset_len:
    ldi  r25, 0                     ; 1 cycle
    movw r30, r24                   ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    add  r30, r24                   ; 1 cycle
    adc  r31, r25                   ; 1 cycle
    add  r30, r22                   ; 1 cycle
    adc  r31, __zero_reg__          ; 1 cycle
    subi r30, lo8(-(dataset_len))   ; 1 cycle
    sbci r31, hi8(-(dataset_len))   ; 1 cycle
    lpm  r24, Z                     ; 3 cycles
    ret

subset_ptr:
    ldi  r25, 0                     ; 1 cycle
    movw r30, r24                   ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    add  r30, r24                   ; 1 cycle
    adc  r31, r25                   ; 1 cycle
    add  r30, r22                   ; 1 cycle
    adc  r31, __zero_reg__          ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    subi r30, lo8(-(dataset_ptr))   ; 1 cycle
    sbci r31, hi8(-(dataset_ptr))   ; 1 cycle
    lpm  r24, Z+                    ; 3 cycles
    lpm  r25, Z                     ; 3 cycles
    ret

Of course, declaring subset_len and subset_ptr as static inline would indicate to the compiler you want them inlined, which increases the code size a bit, but might shave off a couple of cycles per invocation.
Note that I have verified the above (except using unsigned char instead of uint8) for at90can128 using avr-gcc 4.9.2.

A: First, you should put the predefined length array in flash using PROGMEM, if you haven't already.
You could write a script, using the predefined length array as input, to generate a .c (or cpp) file that contains the PROGMEM array definition. Here is an example in python:
# Assume the array that defines the data length is in a file named DataLengthArray.c
# and the array is of the format
# const uint16 dataLengthArray[] PROGMEM = {
#      2, 4, 5, 1, 2,
#      4 ... };

START_OF_ARRAY = "const uint16 dataLengthArray[] PROGMEM = {"
outFile = open('PointerArray.c', 'w')
with open("DataLengthArray.c") as f:
    fc = f.read().replace('\n', '')
    dataLengthArray=fc[fc.find(START_OF_ARRAY)+len(START_OF_ARRAY):]
    dataLengthArray=dataLengthArray[:dataLengthArray.find("}")]
    offsets = [int(s) for s in dataLengthArray.split(",")]
    outFile.write("extern uint8 array[2000];\n")
    outFile.write("uint8* pointer_array[] PROGMEM = {\n")
    sum = 0
    for offset in offsets:
        outFile.write("array + {}, ".format(sum))
        sum=sum+offset
    outFile.write("};")

Which would output PointerArray.c:
extern uint8 array[2000];
uint8* pointer_array[] = {
array + 0, array + 2, array + 6, array + 11, array + 12, array + 14, };

You could run the script as a Pre-build event, if your IDE supports it. Otherwise you will have to remember to run the script every time you update the offsets.

A: You mention that the data set lengths are pre-defined, but not how they are defined - so I'm going to make the assumption of how the lengths are written into code is up for grabs..
If you define your flash array in terms of offsets instead of lengths, you should immediately get a run-time benefit.
With lengths in flash, I expect you have something like this:
const uint8_t lengths[] = {1, 5, 9, ...};

uint8_t get_data_set_length(uint16_t index)
{
    return lengths[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t offset = 0;
    uint16_t i = 0;
    for ( i = 0; i < index; ++i )
    {
        offset += lengths[index];
    }
    return &(array[offset]);
}

With offsets in flash, the const array has gone from uint8_t to uint16_t, which doubles the flash usage, plus an additional element to be speed up calculating the length of the last element.
const uint16_t offsets[] = {0, 1, 6, 15, ..., /* last offset + last length */ };

uint8_t get_data_set_length(uint16_t index)
{
    return offsets[index+1] - offsets[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t offset = offsets[index];
    return &(array[offset]);
}

If you can't afford that extra flash memory, ou could also combine the two by having the lengths for all elements and offsets for a fraction of the indices, e.g every 16 element in the example below, trading off run-time cost vs flash memory cost.
uint8_t get_data_set_length(uint16_t index)
{
    return lengths[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t i;
    uint16_t offset = offsets[index / 16];
    for ( i = index & 0xFFF0u; i < index; ++i )
    {
        offset += lengths[index];
    }
    return &(array[offset]);
}

To simplify the encoding, you can consider using x-macros, e.g.
#define DATA_SET_X_MACRO(data_set_expansion) \
  data_set_expansion( A, 1 ) \
  data_set_expansion( B, 5 ) \
  data_set_expansion( C, 9 )

uint8_t array[2000];
#define count_struct(tag,len) uint8_t tag;
#define offset_struct(tag,len) uint8_t tag[len];
#define offset_array(tag,len) (uint16_t)(offsetof(data_set_offset_struct,tag)),
#define length_array(tag,len) len,
#define pointer_array(tag,len) (&(array[offsetof(data_set_offset_struct,tag)])),

typedef struct
{
    DATA_SET_X_MACRO(count_struct)
}   data_set_count_struct;

typedef struct
{
    DATA_SET_X_MACRO(offset_struct)
}   data_set_offset_struct;

const uint16_t offsets[] =
{
    DATA_SET_X_MACRO(offset_array)
};

const uint16_t lengths[] =
{
    DATA_SET_X_MACRO(length_array)
};

uint8_t * const pointers[] =
{
    DATA_SET_X_MACRO(pointer_array)
};

The preprocessor turns that into:
typedef struct
{
    uint8_t A;
    uint8_t B;
    uint8_t C;
}   data_set_count_struct;

typedef struct
{
    uint8_t A[1];
    uint8_t B[5];
    uint8_t C[9];
}   data_set_offset_struct;

typedef struct
{
    uint8_t A[1];
    uint8_t B[5];
    uint8_t C[9];
}   data_set_offset_struct;

const uint16_t offsets[] = { 0,1,6, };

const uint16_t lengths[] = { 1,5,9, };

uint8_t * const pointers[] =
{
    array+0,
    array+1,
    array+6,
};

This just shows an example of what the x-macro can expand to. A short main() can show these in action:
int main()
{
    printf("There are %d individual data sets\n", (int)sizeof(data_set_count_struct) );
    printf("The total size of the data sets is %d\n", (int)sizeof(data_set_offset_struct) );
    printf("The data array base address is  %x\n", array );
    int i;
    for ( i = 0; i < sizeof(data_set_count_struct); ++i )
    {
        printf( "elem %d: %d bytes at offset %d, or address %x\n", i, lengths[i], offsets[i], pointers[i]);
    }

    return 0;
}

With sample output
There are 3 individual data sets
The total size of the data sets is 15
The data array base address is  601060
elem 0: 1 bytes at offset 0, or address 601060
elem 1: 5 bytes at offset 1, or address 601061
elem 2: 9 bytes at offset 6, or address 601066

The above require you to give a 'tag' - a valid C identifier for each data set, but if you have 500 of these, pairing each length with a descriptor is probably not a bad thing. With that amount of data, I would also recommend using an include file for the x-macro, rather than a #define, in particular if the data set definitions can be exported somewhere else.
The benefit of this approach is that you have the data sets defined in one place, and everything is generated from this one definition. If you re-order the definition, or add to it, the arrays will be generated at compile-time. It is also purely using the compiler toolchain, in particular the pre-processor, but there's no need for writing external scripts or hooking in pre-build scripts.

A: You said that you want to store the address of each data set but it seems like it would be much simpler if you store the offset of each data set.  Storing the offsets instead of the addresses means that you don't need to know the address of big array at compile time.
Right now you have an array of constants containing the length of each data set.
const uint8_t data_set_lengths[] = { 1, 5, 9...};

Just change that to be an array of constants containing the offset of each data set in the big array.
const uint8_t data_set_offsets[] = { 0, 1, 6, 15, ...};

You should be able to calculate these offsets at design time given that you already know the lengths.  You said yourself, just accumulate the lengths to get the offsets.
With the offsets precalculated the code won't have the bad performance of accumulating at run time.  And you can find the address of any data set at run time simply by adding the data set's offset to the address of the big array.  And the address of big array doesn't need to be settled until link time.


Q: Power Query Assistance: How to return the range of three consecutive fields across a row with highest value out of all fields New to Power Query.  Have pieced together what I've needed until now.
I need to return the sum of the three consecutive cells with highest value out of a range of cells.  See the screenshot I provided as an example.  This wouldn't necessarily include the MAX value of a specific cell in the given range.
I can do this all day long in a spreadsheet with MAX function and overlapping arrays.  I can't seem to figure it out with Power Query although I am pretty certain List.Max will be involved somehow.
Help is appreciated.

March 23rd Edit:
I've revised and tried both code suggestions but either the code runs on for a very long period for the first suggestion (I killed it after one hour) or the 2nd suggestion errors out unable to find column 'Material 1' (what I renamed the 'Part Number' field in my screenshot).
I failed to mention that my data table has over 20k rows.  I'm having trouble interpreting the M code suggestions you both provided, but are they looping thru each row one-by-one?  Perhaps this is what is causing the lag.  Maybe I would just be better off using VBA to prep the table in advance of Power Query by entering/filling a formula in a new column finding MAX(B1:N^1+C1:N^2+D1:N^3)?  Seems like it might actually be faster in this case?
My version of both code suggestions:
1st Method:
let
Source = Excel.CurrentWorkbook(){[Name="tblSource"]}[Content],
#"Promoted Headers" = Table.PromoteHeaders(Source),
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Material 1", type text}, {"Sold Month 1", Int64.Type}, {"Sold Month 2", Int64.Type}, {"Sold Month 3", Int64.Type}, {"Sold Month 4", Int64.Type}, {"Sold Month 5", Int64.Type}, {"Sold Month 6", Int64.Type}, {"Sold Month 7", Int64.Type}, {"Sold Month 8", Int64.Type}, {"Sold Month 9", Int64.Type}, {"Sold Month 10", Int64.Type}, {"Sold Month 11", Int64.Type}, {"Sold Month 12", Int64.Type}}),

#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type",{"Material 1"}, "Attribute", "Value"),
#"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
#"Reordered Columns" = Table.ReorderColumns(#"Added Index",{"Index", "Material 1", "Attribute", "Value"}),
#"Added Custom" = Table.AddColumn(#"Reordered Columns" ,"Sum",(i)=>
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]) [Value])+
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]+1) [Value])+
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]+2) [Value])
    , type number),
#"Grouped Rows" = Table.Group(#"Reordered Columns", {"Material 1"}, {{"Max", each List.Max([Sum]), type number}}),
// Merge the max into the original table
#"Merged Queries" = Table.NestedJoin(#"Grouped Rows", {"Material 1"}, #"Grouped Rows",{"Material 1"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"Max"}, {"Max2"})
in #"Expanded Table1"`

2nd Method:
let
Source = Excel.CurrentWorkbook(){[Name="tblSource"]}[Content],
#"Promoted Headers" = Table.PromoteHeaders(Source),
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Material 1", type text}, {"Sold Month 1", Int64.Type}, {"Sold Month 2", Int64.Type}, {"Sold Month 3", Int64.Type}, {"Sold Month 4", Int64.Type}, {"Sold Month 5", Int64.Type}, {"Sold Month 6", Int64.Type}, {"Sold Month 7", Int64.Type}, {"Sold Month 8", Int64.Type}, {"Sold Month 9", Int64.Type}, {"Sold Month 10", Int64.Type}, {"Sold Month 11", Int64.Type}, {"Sold Month 12", Int64.Type}}),
i = {"i"}, k = {"Material 1"},
base = Table.UnpivotOtherColumns(#"Changed Type", k, "Col", "Val"),
f = (n)=>let x = Table.Group(base, k, {"t", each Table.AddIndexColumn(_, "i", n)})
         in Table.Combine(x[t]),
a = f(0),
b = f(1),
c = f(2),
join = Table.NestedJoin(Table.NestedJoin(a,i&k,b,i&k,"a"),i&k,c,i&k,"b"),
add = Table.AddColumn(join, "sum", each List.Sum({[Val],[a][Val]{0}?,[b][Val]{0}?})),
group = Table.Group(add, k, {"max", each List.Max([sum])}),
final = Table.Join(Source, k, group, k)

in final

A: Sample code below
Main trick is unpivot, then using custom column and index to add the current, next, and next+1 row if they are the same Part Number
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Part Number", type text}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type" , {"Part Number"}, "Attribute", "Value"),
#"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
#"Added Custom" = Table.AddColumn(#"Added Index" ,"Sum",(i)=>
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]) [Value])+
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+1) [Value])+
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+2) [Value])
    , type number),
#"Grouped Rows" = Table.Group(#"Added Custom", {"Part Number"}, {{"Max", each List.Max([Sum]), type number}}),

// Merge the max into the original table
#"Merged Queries" = Table.NestedJoin(#"Changed Type",{"Part Number"}, #"Grouped Rows",{"Part Number"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"Max"}, {"Max"})
in #"Expanded Table1"

A: Slightly different way:
let
    Source = Excel.CurrentWorkbook(){[Name="Table"]}[Content],
    i = {"i"}, k = {"Part Number"},
    base = Table.UnpivotOtherColumns(Source, k, "Col", "Val"),
    f = (n)=>let x = Table.Group(base, k, {"t", each Table.AddIndexColumn(_, "i", n)})
             in Table.Combine(x[t]),
    a = f(0),
    b = f(1),
    c = f(2),
    join = Table.NestedJoin(Table.NestedJoin(a,i&k,b,i&k,"a"),i&k,c,i&k,"b"),
    add = Table.AddColumn(join, "sum", each List.Sum({[Val],[a][Val]{0}?,[b][Val]{0}?})),
    group = Table.Group(add, k, {"max", each List.Max([sum])}),
    final = Table.Join(Source, k, group, k)
in
    final


Q: How to display Bootstrap Autocloseable alert message on asp.net button click? How to display Bootstrap Autocloseable alert message on asp.net button click?
Code as follows:

    <asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="btn btn-block org"
        Style="margin-top: 0px" OnClick="btnLogin_Click showalertmsg();" ValidationGroup="Login" />

closeable code using javascript

I called function name"showalertmsg" on asp button click it gives error?
error gives as follows while compiling
Compiler Error Message: CS1026: ) expected

A: Issues in the asp.net button
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="btn btn-block org"
        Style="margin-top: 0px" OnClick="btnLogin_Click" ValidationGroup="Login" OnClientClick="showalertmsg(); return false;" />

A: you can't call javascript fuction like this
OnClick="btnLogin_Click showalertmsg();"

But
use OnClientClick="showalertmsg();"
and also call return false at the end to stop postback
function showalertmsg(message, alerttype) {

        $('#alert_placeholder').append('
×' + message + '
')

        setTimeout(function () {
            $("#alertdiv").remove();

        }, 5000);

return false;
    }


Q: How conv2D function change the input layer In my ResNet32 network coded using Tensorflow, the input size is 32 x 32 x 3 and the output of the
layer is 32 x 32 x 32. Why 32 channel is used ?
tf.contrib.layers.conv2d(
    inputs,
    **num_outputs**,  /// how to determine the number of channel to be used in my layer?
    kernel_size,
    stride=1,
    padding='SAME',
    data_format=None,
    rate=1,
    activation_fn=tf.nn.relu,
    normalizer_fn=None,
    normalizer_params=None,
    weights_initializer=initializers.xavier_initializer(),
    weights_regularizer=None,
    biases_initializer=tf.zeros_initializer(),
    biases_regularizer=None,
    reuse=None,
    variables_collections=None,
    outputs_collections=None,
    trainable=True,
    scope=None
)

Thank's in advance,

A: The 3 in input is the number to represent that the input image is RGB (color image), also known as color channels, and if it were a black and white image then it would have been 1 (monochrome image).
The 32 in output of this represents the number of neurons\number of features\number of channels you are using, so basically you are representing the image in 3 colors with 32 channels.
This helps in learning more complex and different set of features of the image. For example, it can make the network learn better edges.

A: By assigning stride=2 you can reduce the spatial size of input tensor so that the height and width of output tensor becomes half of that input tensor. That means, if your input tensor shape is (batch, 32, 32, 3) (3 is for RGB channel) to a Convolution layer having 32 kernels/filters with stride=2 then the shape of output tensor will be (batch, 16, 16, 32). Alternatively, Pooling is also widely used to reduce the output tensor size.
The ability of learning hierarchical representation by stacking conv layer is considered as the key to success of CNN. In CNN, as we go deeper the spatial size of the tensor reduces whereas the number of channel increases that helps to handle the variations in appearance of complex target object . This reduction of spatial size drastically decreases the required number of arithmetic operations and computation time with the motive of extracting prominent features contributing towards final output/decision. However, finding this optimal number of filter/kernel/output channel is time consuming and, therefore, people follow the proven earlier architectures e.g. VGG.


Q: Failed to resolve libraries when changing from jcenter() to mavenCentral() So I am working on an old project and Android Studio warned me to change from jcenter() to mavenCentral() as jcenter() is not beeing updated.
So this was my initial project build.gradle:
buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'com.google.gms:google-services:4.3.13
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And I have changed it to the following one:
buildscript {
    repositories {
        google()
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'com.google.gms:google-services:4.3.13
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

With the initial build.gradle using jcenter() everything was working fine, but using mavenCentral it fails to resolve these 2 github libraries:
"Failed to resolve: com.loopeer.lib:shadow:0.0.3"
"Failed to resolve: com.vatsal.imagezoomer:image-zoomer:1.0.2"
I don´t know why with jcenter() I don´t have any problem and using mavenCentral() yes, could there be any solution or maybe they can be only working with jcenter()?
The curious thing is that for example I have searched for information of one of this libraries and supposedly it should work with mavenCentral -> "ImageZoomer is available in the MavenCentral, so getting it as simple as adding it as a dependency" (This is what it is said in this github library)


Q: Python pylab chart plot and loops I'm just learning Python and I'm wondering if someone could help me get the chart to render properly in the following code, i.e. plot the sequence of data points.
I have put print statements so I can see if the calculations are correct which they are.
Thanks
from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

ff = float(25)
for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    plot(dd,tt1)
    print(dd)
    print(tt1)
title("Something")
xlabel("x label")
ylabel("y label")
show()

A: Since you are plotting one point at a time, you need either a scatter plot or a plot with markers
for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    scatter(dd, tt1) # Way number 1
    # plot(dd,tt1, 'o') # Way number 2

EDIT (answering your second question in the comments below): Save the results in a list and plot outside the for loop
result = []
dd_range = range (0, 1200, 100)
for dd in dd_range:
    tt1 = some_function(ff, dd)
    result.append(tt1)
plt.plot(dd_range, result, '-o')

A: You can vectorize your function and work with NumPy arrays to avoid the for-loop and better inform matplotlib of what you want to plot
import numpy as np
from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

vectorized_some_function = np.vectorize(some_function)

ff = float(25)
dd = np.linspace(0, 1100, 12)
tt = vectorized_some_function(ff, dd)
plot(dd, tt)
title("Something")
xlabel("x label")
ylabel("y label")
show()


Q: How to generate flexible number of tabs in php? Hello guys I really need your help.
I am very new php or programming in general. So maybe my question is already solved but I wasn't able to adjust the code in correct way or see the correct solution. I have the following problem: I need a procedure that can handle flexible numbers of tabs. For example if I have 5 keywords, there should be 5 tabs generated. For 3 keywords 3 tabs and so on...
I know how to handle tabs their number is known and doesn't change (like for example always three tabs with 'home', 'news' and 'registration'). But in my case, number of tabs change in time.
I tried this code:
My php part:
<?php

/* How it was handled before I tried to make it dynamically:
<button class="tablink" onclick="openPage('Home', this, 'red')" id="defaultOpen">Home</button>
<button class="tablink" onclick="openPage('News', this, 'green')">News</button>
<button class="tablink" onclick="openPage('Contact', this, 'blue')">Contact</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

Home

 home...

News

 news...

Contact

 contact...

About

 about...

My try making the number of tabs dynamically:
*/

$current_tab_number = 0; //Number of tabs generated
$end_number=3; //this should be the number of tabs at the end

while($current_tab_number < $end_number){
    $current_tab_number = current_tab_number + 1;
?>
    <button class="tablink" onclick="openPage('$current_tab_number', this, 'red')">Name</button>

Name

 Some text...

<?php
}

This is my javascript:

As you can see, I only changed the php part. But since I'm a beginner, code doesen't work as expected and I have really no clue, how to adjust in correct way.
In addition it would be fantatstic, if tabs could be named flexible,too. Like 'tab 1', 'tab 2',...
I really hope, someone could help me.
So far, have a great day!

A: You need to know a name for each tab and how many to create, so create an array with the names you want, that tells you how many are needed and the name that should be used in the javascript call.
/*
My try making the number of tabs dynamically:
*/

$tabs = ['Home', 'News', 'Contact', 'About'];

foreach ($tabs as $tab){
?>
    <button class="tablink" onclick="openPage('<?php echo $tab;?>', this, 'red')>Name</button>
    <div id="<?php echo $tab;?>" class="tabcontent">

Name

 Some text...

<?php
} // endforeach

A: Key Issue
The reason your code doesn't work is because you've missed a $ symbol from the line:
$current_tab_number = current_tab_number + 1;

So, effectively, your while loop becomes infinite as you don't increment the $current_tab_number variable.
Replace that line with:
$current_tab_number = current_tab_number + 1;
// OR
$current_tab_number++;

Which then becomes:
while($current_tab_number < $end_number){
    $current_tab_number++;
    // Print tabs here
}

Alternatively you could use a for loop like:
for($i = 0; $i < $end_number; $i++){
    // print tabs here
}

Additionally
Using variables outside of PHP tags
This line:
<button class="tablink" onclick="openPage('$current_tab_number', this, 'red')">Name</button>

Will literally print the string $current_tab_number what it should be is:
<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>

Same here:

<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

We could easily get around this by just using echo to print the html instead. For example:
echo <<<EOT

    <button class="tablink" onclick="openPage('{$current_tab_number}', this, 'red')">Name</button>

Name

 Some text...

EOT;

This method doesn't add data to the divs
The output of this code is expected to be:
<button class="tablink" onclick="openPage('Home', this, 'red')" id="defaultOpen">Home</button>
<button class="tablink" onclick="openPage('News', this, 'green')">News</button>

Home

 home...

News

 news...

But will actually be:
<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>
<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

Name

 Some text...

<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>
<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

Name

 Some text...

To add data to the output we need to source it from somewhere, for example:
$tab_list = [
    1 => [
        "name"    => "Home",
        "content" => "Some text for content..."
    ],
    2 => [
        "name"    => "About",
        "content" => "Some text for about..."
    ]
];

foreach($tab_list as $tab_number => $tab){
    echo "
    <button class=\"tablink\" onclick=\"openPage('{$tab_number}', this, 'red')\">Name</button>

{$tab["name"]}

{$tab["content"]}

    ";
}

A: You can iterate over the tab names and concatenate the string to generate the html code for tabs. For example:
$tab_names = ['home', 'about', 'contact'];
$resulting_html_code = "";
foreach ($tab_names as $tab){
    $resulting_html_code .= "{$resulting_html_code}
{$tab}
";
}


Q: Can I write in a user input in Python? I would like to add a "default value" to an input().
Something like this:
>>> x = input("Enter a number: ", value="0")
Enter a number: 0

So that the user can edit it, like the value attribute in html <input>
I tried using pyautogui:
import pyautogui

def input_value():
    x = input("Enter a number: ")
    pyautogui.hotkey("0")return x

But naturally it doesn't work because pyautogui.hotkey() is called after input().
Is there any way to do this?

A: Take a look at pyinputplus for enhanced input() functionality. If the online documentation isn't enough, you can also read Automate the Boring Stuff with Python for a good guide on using the module
https://pypi.org/project/PyInputPlus/
All input functions have the following parameters:
default (str, None): A default value to use should the user time out or exceed the number of tries to enter valid input.


Q: system.webServer/security/authorization in web.config how to migrate to aspcore I'm using a asp.net webapp which uses system.webServer in web.config and have a list of user accounts as roles.
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" roles="MOON\USER1" />
        <add accessType="Allow" roles="MARS\USER2" />
      </authorization>
    </security>
</system.webServer>

and to achieve this authorization in asp.net core i tried to use different approaches and none seems working. What is the right and best way in asp.net core to implement authorization of web app to load for restricted users.

A: I don't know if you managed to find the solution to your issue but the first problem in that config file is that the auth rules are matched in order. All your requests are matching the deny first and you never get to evaluate the access for USER1 and USER2.


Q: StandardOutput.ReadToEnd() always NULL I have a problem with this function. It is supposed to output an install command to a textbox but install.StandardOutput.ReadToEnd() is always null.
I get the error: Expression cannot be evaluated because there is a native frame at the top of the call stack
Can you help me out with this?
Process install = new Process();
install.StartInfo.FileName = "cmd.exe";
install.StartInfo.UseShellExecute = false;
install.StartInfo.Arguments = "/all";
install.StartInfo.CreateNoWindow = true;
install.StartInfo.RedirectStandardInput = true;
install.StartInfo.RedirectStandardOutput = true;
install.Start();

if (CB_MultiADB.Checked == true)
{
    install.StandardInput.WriteLine("FOR /F \"skip=1\" %%x IN ('adb devices') DO start cmd.exe @cmd /k" + InstallOption + InstallPfad + "\"");
}
else
{
    install.StandardInput.WriteLine("adb install" + InstallOption + InstallPfad + "\"");

    InstallAusgabe = install.StandardOutput.ReadToEnd();
    string Index = "adb install";
    int Indexnr = InstallAusgabe.IndexOf(Index);
    string SubInstall = InstallAusgabe.Substring(Indexnr, 100);
    TB_Ausgabe.Text = SubInstall;
}


Q: Register a Facebook user for an existing web app I have a Flex application that I would like to embed in a Facebook canvas. The app already runs on my website and is accessible there once the user has created an account. I am trying to work out the flow of integrating with Facebook:

*

*User accesses my app in Facebook;

*The app.facebook.com/myApp page loads;

*The Facebook SDk in myApp checks if the user is already logged into Facebook, and if not asks them to do so;

*Once I know the user is logged into Facebook myApp will redirect to my server which will check if the Facebook response.username already has an account.

*

*If the user does not have an account then I create one for them, log them in and redirect them back to the app page with a parameter hasAccount=true so that I know they do have an account. I then show them the app;

*If the user does have an account then I redirect them with hasAccount=true and show them the app.

Can anyone comment on that control-flow, is that normal or have I made it overly complicated?


Q: TFS Sub-area name change I would like to know if its possible to edit the name of a sub-area in TFS. I know I can create new areas and delete but I can't seem to find a way to rename. There might be implications around this that would keep someone from performing this task.

A: In TFS 2012, you should be able to go the same screen you create the areas and double click (or right click on select edit) on the area you want to rename. At that point, you should be able to modify the name accordingly.


Q: How to abort only the current git cherry-pick and not previous ones? I have cherry picked multiple commits by doing git cherry-pick -x <SHA> and one of them failed (due to conflicts). I haven't pushed anything to the branch yet and I just want to abort the last cherry pick alone (the failed one) and keep everything else. Should I simply do git push to my branch and checkout all the files to discard the changes? Is there a command to abort just this?
git status shows something like this:
# On branch bugs-br # You are currently cherry-picking.
#   (fix conflicts and run "git commit")
#
# Changes to be committed:
#
#       modified:  oper/svc/oper.cc
#
# Unmerged paths:
#   (use "git add <file>..." to mark resolution)
#
#       both modified:    oper/svc_thread.cc

A: The command git cherry-pick --abort will only abort the last cherry pick you started. Previous complete cherry-pick operations are already committed, so they will not be affected.
So that's all you need to do at this point.


Q: VBA: Replace text from txt for each line and save as Could somebody help me with the following? I tried making it on my own, but all I could do is open a txt and replace a static word with static word.
VBA script:
Open and Read first line of ThisVbaPath.WordsToUse.txt
Open and Find USER_INPUT in ThisVbaPath.BaseDoc.docx (or txt)
Replace all occurrence of USER_INPUT with first line from WordsToUse.txt
Save BaseDoc.docx as BaseDoc&First_Line.docx
Close all
Go next line and do same, but don't ask for user input, use previous one
If error go next
When done show if there were any errors (unlikely I guess)
I would use it about weekly for 150-ish lines.
Thanks!

A: I think something like this should work?
Sub test()

  Dim text, textReplace, findMe As String

  findMe = InputBox("What Text To Find?")
  Open "C:\Excel Scripts\test.txt" For Input As #1
  Open "C:\Excel Scripts\test2.txt" For Input As #2
  Open "C:\Excel Scripts\output.txt" For Output As #3

  While Not EOF(1)
    Line Input #1, text
      While Not EOF(2)
        Line Input #2, textReplace
        Write #3, Replace(text, findMe, textReplace)
      Wend
  Wend

  Close #1
  Close #2
  Close #3

End Sub

A: Sub TextFile_FindReplace()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

FilePath = Application.ActiveWorkbook.Path & "\NEWTEST.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)

FileContent = Replace(FileContent, "FOO", "BAR")

Print #TextFile, FileContent
Close TextFile
End Sub


Q: Display an overlay when submitting a form I want to display an overlay when the user is submitting a form. I'm using $('form').submit(function { [...] }) to achieve this.
The problem is that I'm using client-side validation. The immediate solution is of course to manually validate the form: if ($('form').validate().valid()) { .. }
The ultimate solution would be to hook onto some event which is invoked when the POST is made.  (To support any other plugins that might prevent the form from submitting and when the validation plugin is not used.)

A: Assuming you're using jQuery validate, you can use the submitHandler property to run code when the validation passes, for example:
$("#myForm").validate({
    submitHandler: function(form) {
        // display overlay

        form.submit();
    }
});

Further reading

A: Try to return false; on validation errors while submiting.


Q: mysql utf8 turkish characters not correct recognized In mysql utf8 coded turkish data i can't search "İ" and "ı". when i search its giving result contains "Y" or "y". Because in latin1 "İ" displaying as "Ý" and "ı" as "ý".
in latin1 data i was used latin1_general_ci for correct result. but there is not alternative collation for utf8. its already utf8_general_ci.
is there any other people have some problems or do you have a solution.
thanks.
i have tried stackoverflow search engine to for this problem. if its have mysql and utf8 then my work true. try search "alİ" and "ali". both search give another result. but both same in turkish. the "İ" is capital i and capital "I" is "ı" in turkish.
there is a solution but not fully.
i you use utf8_turkish_ci then the result give "İ" but also "Y".

A: the problem is temporary solved. i you use all collations uf8_turkish_ci you can get correct result. but i am wondering why i have to use turkish_ci.
try collate all columns utf8_turkish_ci, tables utf8_turkish_ci, and database too.
good luck