text:
Q: Tomcat Concurrent execution exception in eclipse Getting following error
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/TxDataExchange]]
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/TxDataExchange]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Caused by: java.lang.NoClassDefFoundError: javax/jms/Message
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:270)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:139)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:415)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:892)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:386)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5380)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Caused by: java.lang.ClassNotFoundException: javax.jms.Message
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
... 20 more

Mar 13, 2015 9:00:32 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:816)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more

Mar 13, 2015 9:00:32 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:739)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more

This error comes only when i deploy my application via eclipse in tomcat,when i deploy application directly to the tomcat it works fine. I tried removing unwanted dependencies from my class-path still its not working.I searched all over the web but couldn't find any solution.I do have javax.servlet-api-3.0.1.jar included in my class-path.I tried removing the jar from class-path I got the error in the class where i used classes from this jar.so i can't remove this jar as well.The servlet mapping is correct.Please help.


text:
Q: Discord.js | Chat transcript (txt) gets saved I ran into a problem with a discord.js ticket transcript command. When I use the transcript command, a .txt file gets created and sent into the channel, this works just fine. The issue is that the file gets saved locally, which isn't what I want.
The code for creating the txt + sending:
fs.writeFileSync(`${message.channel.name}.txt`, content.join('\n'), err => { if (err) throw err });

doneEmbed(message, lang.ticket.transcript.replace('{name}', `${message.channel.name}.txt`));
return message.channel.send(new MessageAttachment(`${message.channel.name}.txt`, `${message.channel.name}.txt`));

doneEmbed is just a pre-created embed to make the code cleaner, in case you're confused:
//Emoji file
const e = require('../../data/config/emojis.json');

//Embed
module.exports.doneEmbed = function doneEmbed(message, desc) {
    let embed = new MessageEmbed()
        .setDescription(e.done + desc)
        .setColor(c.done)
    message.channel.send(embed);
}

File structure, where the transcript gets saved ( | exstare.txt &  | test.txt):

Thanks in advance!

A: Your application need to save the file before sending it as attachment. Thats why its required to save the file.
But there is an simple sollution for this problem. If you dont want the file stored forever in your project folder, just delete the file after you've sent the file as attachment with your Discord bot. Take a look on this website for some examples how to delete a file with FileSystem: https://www.tutorialkart.com/nodejs/delete-a-file-in-nodejs-using-node-fs

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make AnimatedSwitcher animate if parent widget is rebuilt in Flutter? I am trying to implement a selectable ListTile. When ListTile is selected it's leading icon changes and its background color changes. I am trying to use AnimatedSwitcher to animate the transition when icons are changed. And it works (as long as I don't change background color of the list tile).
Changing the background color of the ListTile causes the animation to not work anymore. And I think I know why that is. When background color of the ListTile is changed, entire ListTile gets rebuilt. Which causes AnimatedSwitcher to also be rebuilt instead of transitioning between icons. Is there a way I can implement what I am trying to do. Here is my full code.
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool change = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
          body: Center(
            child: SomeStatelessWidget(
                AnimatedSwitcher(
                  duration: Duration(seconds: 2),
                  child: change
                      ? CircleAvatar(
                          key: UniqueKey(),
                          child: Icon(Icons.check),
                        )
                      : CircleAvatar(
                          key: UniqueKey(),
                          child: Text("A"),
                        ),
                  transitionBuilder: (child, animation) {
                    return RotationTransition(
                      turns: animation,
                      child: child,
                    );
                  },
                ),
                change),
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.swap_horiz),
            onPressed: () {
              setState(() {
                change = !change;
              });
            },
          ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
        ));
  }
}

class SomeStatelessWidget extends StatelessWidget {
  final Widget child;
  final bool changed;

  SomeStatelessWidget(this.child, this.changed);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8.0),
      decoration: changed
          ? BoxDecoration(
              color: Theme.of(context).selectedRowColor,
              borderRadius: BorderRadius.all(Radius.circular(8.0)),
              shape: BoxShape.rectangle)
          : null,
      child: ListTile(
        leading: child,
        title: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text("This is an example"),
        ),
      ),
    );
  }
}


text:
Q: Why does this JS return false for a non-integer? Here is the code function from - the great jQuery cycle plugin
function calculateTimeout(currElement, nextElement, opts, isForward) {
var index = opts.currSlide;
return index % 2 ? 2000 : false;
}

I get what it does and its working fine the the last line I am curious about.

*

*"return" obviously kills the function and returns what ever output it has

*index is an variable set in the above line (is also an integer)

*"% 2" then divides the index var by 2

*Then the "? 2000 : false" is the short hand for if else and if the statement is true / false will return either 2000 or false.

So 3 will return true and 3.5 will return false for example.
So my question is why in this context does an integer return true but a non-integer return false?  I might have thought than any number would return true and 0 would return false?
Guessing it due to type casting but where is that set?
Thanks


text:
Q: Mutating the DOM with elements including different indexable variables Hope my title isn't misleading!
In my quest discovering the power of loops, I would like to sort this:
I need to build these elements:

    <input type="checkbox" id="checkbox-1" value="a">
    A

    <input type="checkbox" id="checkbox-2" value="b">
    B

    <input type="checkbox" id="checkbox-3" value="c">
    C

I did this so far but don't know how to proceed to get the alphabet letters (both lower and uppercase) in the element.
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];

  let html = "";
  for (let i = 1; i <= 12; i++) {
    html += `

                <input type = "checkbox" id = "checkbox-${i}" value = "?">
                ??`;
    html += "
";
  }
  $("#here").html(html);

Is there a good way, or just hardcoding in the HTML file will be easier? (it's 12 inputs in total).
Thanks for the help in advance!!

A: You can iterate through your alphabet array, and use alphabet[i] to access the desired letter. Then you can put it in both the value attribute, and into your label.
If you need a lower case version, you use .toLowerCase()
 for (let i = 0; i < alphabet.length; i++) {
    html += `

                <input type = "checkbox" id = "checkbox-${i}" value = "${alphabet[i].toLowerCase()}">
                ${alphabet[i]}
`;
  }

A: Repl Example
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];

let html = "";
for (let i = 0; i < alphabet.length; i++) {
  let checkboxID = 'checkbox-'.concat(String(i).toLowerCase())
  let checkboxValue = alphabet[i]
  html += `

      <input type="checkbox" id="${checkboxID}" value="${checkboxValue}">
      ${checkboxValue}

`;
}

or use Array.reduce...
const html = alphabet.reduce((_html, letter, letterIndex) => {
  let checkboxID = 'checkbox-'.concat(String(letterIndex).toLowerCase())
  let checkboxValue = letter
  return _html += `

      <input type="checkbox" id="${checkboxID}" value="${checkboxValue}">
      ${checkboxValue}

  `
}, '')


text:
Q: PhpStorm Git folder modified color My PhpStorm is coloring changed files when a project is under Git, I want to color the folder also so I can notice that there is a file changed under that colored folder.
Thanks.

A: You will have to enable the following option: Settings (Preferences on Mac) | Version Control | Show directories with changed descendants
UPDATE 2021-12-27:
Nowadays (PhpStorm 2021.3) this option has a bit different name Highlight directories that contain modified files in the Project tree and lives at Settings/Preferences | Version Control | Confirmation settings screen.


text:
Q: fetch data from one table and insert then into another table Mysql, Sidekiq, Ruby We have to fetch around 5 millions of records from one table and insert them into another table with same table structure.
We are using Sidekiq and redis to put the records to be inserted in the queue and insert from the queue.
Here is my code :
User_controller :
def reinsert_users
   @active_users = ExportUser.all
   RecreateUserWorker.perform_async(@active_users)
end

recreateuser_worker.rb :
class RecreateUserWorker
  include Sidekiq::Worker

  def perform(users)
    begin
      @user = User.new("true")
      @user.recreate(users)
    rescue
      raise
    end
  end

end

'''''
User.rb :

def recreate(users)
    users.each do |user|
      @user = ExportUsersV2.new(user)  # new table to insert
      @user.save
    end
end

This is the error i get :
WARN: {"class"=>"RecreateUserWorker", "args"=>["#<ExportUser::ActiveRecord_Relation:0xa3781b0>"], "retry"=>true, "queue"=>"default", "jid"=>"25fe4378de1bb967ff4d1e5e", "enqueued_at"=>1438605202.8414373, "error_message"=>"undefined method `each' for \"#<ExportUser::ActiveRecord_Relation:0xa3781b0>\":String", "error_class"=>"NoMethodError", "failed_at"=>1438605202.8470101, "retry_count"=>0}

What am I missing here??

A: You are passing in a complex Ruby object, which is not allowed.
https://github.com/mperham/sidekiq/wiki/Best-Practices#1-make-your-job-parameters-small-and-simple

A: I think it is better to insert users in bulks using direct mysql queries.
You can use gem https://github.com/tauqeer-ahmad/bulk_uploadable/tree/master or any other gem for this.
I think this may resolve this issue.


text:
Q: How to .SaveAs non-unique sent email to Windows folder I have VBA code whose main functions are:

*

*Load a form

*Allow a user to choose a stock email response

*Open a word document with the full response text

*Create a reply using the text

*Search the email and create a collection of strings containing corporate file numbers

*Add the file numbers to an Excel list

*Send the response

Now I want to save one copy of the sent item in a Windows folder, for each file number. I've been trying to wait until the item is sent and moved to Sent Items. The problem is that after calling the send method, the mailitem doesn't send or move to Sent Items until after the code finishes so I end up in an infinite loop.
All the options I found involve using a class module and WithEvents. That would work if I wanted to copy every sent item to the folder. I can't think of any criteria that would differentiate the emails created by this macro from normal emails. I could go into the Excel list of files, but that would bog everybody's machine down on every send.
Is there a way to just have the email send find out when it has been sent and moved to sent items? My code to send, wait for it to go to sent items, and to save the emails is below. Note I have two global variables: cReply (Outlook.MailItem – the reply) and fNums (Collection – the file numbers).
I'm coding in Outlook 2016, but hope to move the module to Outlook 2010 at work.
Sub Send()
    Dim badChar As String
    badChar = "\/:*?™""® <>|.&@#_+`©~;-+=^$!,'" & Chr(34)
    Dim x As Integer
    Dim fName As String
    Dim inSentItems As Boolean
    Dim olApp As Outlook.Application
    Dim olNS As Outlook.NameSpace
    Dim olFldr As Outlook.MAPIFolder
    Dim cSent As Outlook.MailItem
    Dim sentMoment As Date
    fName = cReply.Subject
    For x = 1 To Len(badChar)
        fName = Replace(fName, Mid(badChar, x, 1), "-")
    Next x
    Set olApp = GetObject(, "Outlook.Application")
    Set olNS = olApp.GetNamespace("MAPI")
    Set olFldr = olNS.GetDefaultFolder(olFolderSentMail)
    inSentItems = True
    x = olFldr.Items.Count
    sentMoment = Now
    cReply.Send
    Do While olFldr.Items.Count <> x + 1
        If Now - sentMoment > TimeValue("0:00:10") Then
            inSentItems = False
            Exit Do
        End If
        DoEvents
    Loop
    If inSentItems Then
        Set cSent = olFldr.Items(olFldr.Items.Count)
        For x = 1 To fNums.Count
            cSent.SaveAs sentFldrPth & fNums.Item(x) & " - " & fName & ".msg", olMSG
        Next x
        'cSent.Delete
    End If
    Set olApp = Nothing
    Set olNS = Nothing
    Set olFldr = Nothing
End Sub

A: You could use SaveSentMessageFolder to save to another folder.
https://msdn.microsoft.com/en-us/library/office/ff868473.aspx
Monitor this other folder with ItemAdd code. You could move the mail to the Sent Items folder once done.


text:
Q: Plot lines on an Excel chart I need to plot a line between two points on an excel spreadsheet. In my ideal world, it'd become a thin box with colors and text, but at this stage, I'll take what I can get.
Data:
min max value
1   2   28
2   3   64
3   5   87
4   7   99

In the end, there would be lines from {1,28} to {2,28}, {2,64} to {3,64}, {3,87} to {5,87} and {4,99} to {7,99}.
Flipping the axes in Excel, apparently, doesn't leave the original axes intact - it goes to numbering the data.

A: If you rearrange the data as shown in the animated gif below and then make separate plots for each min/max pair, you get the lines drawn just as you described.  I show adding just the last min/max pair, and added labels for the sake of a legend. This seems to do what you described, but if not let me know.


text:
Q: "seek" without preposition sounds weird I am writing the following sentence (I made it shorter for this question):

To achieve a better bound, we seek graphs with the following property.

I read that using the phrase "seek for" is not recommended or even incorrect. Is my sentence OK?
Thank you

A: Your sentence is OK.
Seek takes a direct object.
Seek for is understandable, but I don't think a native speaker would ever say it.


text:
Q: Is it possible to egrep these symmetrical expressions over {0,1} The goal is to use solely egrep to match expressions where n occurrences of 0 are followed by exactly n occurrences of 1 and where no 0 follows a 1.
e.g.
01
000111
000000111111

but not:
001
011
00011

etc.
Intuitively, this doesn't seem achievable due to the matchable expressions not being of fixed length. But perhaps I'm missing a feature of egrep that could be useful with this?

A: Quick overview of some CS concepts:

*

*Automata accept strings that belong to a "language", generated by a "grammar."

*Regular expressions (in theory) are equivalent to (deterministic or non-deterministic) finite automata (DFA/NFA). So, given a regex like 0*1*, there are DFA and NFA that can accept strings matching that regex.

*Finite automata are strictly less powerful than pushdown automata (PDA). The class of languages that PDA accept are generated by context-free grammars (CFG).

*The strings you're looking at - 0n1n - are generated by the CFG: S -> 0S1 | ε (loosely, given a starting string, you can generate a string with 0 and 1 to either side of the original string, or nothing - so it lets you generate 01, 0011, etc.).

While grep (extended or otherwise) has features that go beyond the "regular expressions" mentioned above, such as back-references, I don't believe any of those extend it to being as powerful as a PDA.
It can be proven that S -> 0S1 | ε is not regular by using the pumping lemma, but I don't have proof of grep's features making it able (or unable) to accept CFGs. However, the Wikipedia article on Regular Expressions has this to say (bold mine):

Many features found in virtually all modern regular expression
  libraries provide an expressive power that far exceeds the regular
  languages. For example, many implementations allow grouping
  subexpressions with parentheses and recalling the value they match in
  the same expression (backreferences). This means that, among other
  things, a pattern can match strings of repeated words like "papa" or
  "WikiWiki", called squares in formal language theory. The pattern for
  these strings is (.+)\1.
The language of squares is not regular, nor is it context-free, due to
  the pumping lemma. However, pattern matching with an unbounded number
  of backreferences, as supported by numerous modern tools, is still
  context sensitive. [33]
[33]: Cezar Câmpeanu and Kai Salomaa, and Sheng Yu (Dec 2003). "A Formal Study of Practical Regular Expressions". International Journal of Foundations of Computer Science. 14 (6): 1007–1018. doi:10.1142/S012905410300214X. Theorem 3 (p.9)

So, I'd say it's safe to say grep can't match 0n1n by itself.


text:
Q: Compiler Error for unknown reasons (C++) I get a compiler error (C2061) in MSVS C++ 2010 IDE, when I try to compile. I simply got no clue as to why it occurs, as I can see no apparant error.
#pragma once
#ifndef _CCOMPONENT_H
#define _CCOMPONENT_H

#include "CGame.h"

class CComponent
{
public:
    CComponent(CGame &game);
    ~CComponent();

protected:
    virtual void Draw();
    virtual void Update();
    virtual void Init();
    void Dispose();
};

#endif // _CCOMPONENT_H

Compiler Error:
 ccomponent.h(10): error C2061: syntax error : identifier 'CGame'

Contents of CGame.h
/**************************************************
*
*
****************************************************/
#pragma once
#ifndef _CGAME_H
#define _CGAME_H

#include <cstdio>
#include <list>
//#include <Box2D/Box2D.h>
#include <allegro5\allegro5.h>
#include "SharedDef.h"

#include "CComponent.h"
#include "CTestPlayer.h"

using namespace std;

class CComponent;
class CTestPlayer;

const int MAX_COMPONENTS = 255;

class CGame
{
public:
    // CONSTRUCTORS
    CGame();
    ~CGame();

    // ACCESSORS
    ALLEGRO_DISPLAY *GetGameDisplay();
    ALLEGRO_EVENT_QUEUE *GetGameEventQueue();

    list<CComponent> GetComponents() { return *m_Components; }
    void AddComponent(CComponent component);

    bool IsRun();
    void StartTimer();
    void StopTimer();

    virtual bool ShouldDraw();
    virtual bool ShouldUpdate();
    virtual void Update(void);
    virtual void Draw(void);
    virtual void Dispose();

protected:
    virtual void RegisterEventSources();
    virtual void Initialize();

private:
    bool InitializeAllegro();

private:
    ALLEGRO_DISPLAY *m_Display;
    ALLEGRO_EVENT_QUEUE *m_EventQueue;
    ALLEGRO_TIMER *m_Timer;
    ALLEGRO_EVENT m_Event;

    list<CComponent> *m_Components;
    //CComponent *m_Components[MAX_COMPONENTS];

    bool m_bIsRunning;
    bool m_bShouldDraw;
};

#endif // _CGAME_H

and, "class CGame" is declared and defined in "CGame.h", so I really cannot see why....

A: Your headers try to #include each other - you can't do that. Remove the #include of the game header from the component header and use a forward declaration of CGame instead.
 CComponent(class CGame &game);

On a design point, problems like this usually mean you have got something wrong. I think it unlikely that components should  know about the game they are part of.

A: It looks like CGame.h is being compiled first.  So imagine the steps

*

*CGame.h starts being compiled

*CComponent.h gets included

*CComponent.h starts compiling due to being included

*CGame.h is included, but is skipped due to #pragma once (already started in step 1)

*Error: CGame is undefined symbol

Solution: Get rid of includes, replace with forward declarations.  You forward declare CComponent in CGame.h, do the opposite in CComponent.h (forward declare CGame)


text:
Q: How to use different database engines in Django for testing and production I'm quite newbie in Django. I have an application in project which is developed with test driven development. In production we use MySQL as database engine, but if I run test with MySQL:
./manage test myapp

Then it absorbs too much time (2-4 mins) to create database, althought tests are quite fast (about a second).
If I use SQLite then tests requires only a few seconds, which is perfect for me. But the problem is that I often need the admin interface with my local database on MySQL.
How to make django to run tests on sqlite and launch runserver with mysql?
Now I use these settings in settings/local.py, but I should comment/uncomment lines to change database depending on what activity I do at the moment.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # Use for testing
        'NAME': 'databasename.db3',
        # 'ENGINE': 'django.db.backends.mysql',  # Use if need admin on localserver
        # 'NAME': 'databasename',
        'USER': 'myuser',                      # Not used with sqlite3.
        'PASSWORD': 'somepassword',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        'TEST_CHARSET': "utf8",         #option to make tesing database with utf8
        'TEST_COLLATION': "utf8_general_ci",
    }
}

A: You don't need to do any hacks. "--settings" - this is what you're looking for.
python manage.py test APP --settings settings.local
python manage.py test APP --settings settings.production

A: One option would be to check sys.argv for the test argument in settings.py:
if 'test' in sys.argv:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    DATABASES['default']['NAME'] = 'databasename.db3'

Though, as a side note: strictly speaking, it is not really a good idea to have different database backends for testing and for development/stage/production. You may encounter database-specific "special" cases, that can cost you a lot of time and headache.

A: Whenever possible it's always a good idea to use the same setup in production and test. It makes for better testing. I great way to deal with tests running slowly is to use django-nose. It lets you reuse previously created test databases. This can super speed up test runs. Check out enabling database reuse in the docs. An example is as follows:
REUSE_DB=1 ./manage.py test

A: Usually i use the following schema:
Create a two settings files for different modes
touch settings/production.py
touch settings/testing.py

On production mode
ln -s settings/production.py settings/__init__.py

On testing mode
ln -s settings/testing.py settings/__init__.py


text:
Q: Get data from the phone jack audio line-in instead of phone microphone I am searching the answer from google and android website.
Because the iPhone can do that. But I can't find the Android has the API to do.
http://forum.arduino.cc/index.php/topic,19648.0.html
Because the microphone pin and GND pin maybe change in the different android phone.
So, I try to use the line-in (right) to get the data.
I checked the Hijack project, it used the microphone pin to get data, and used iPhone.
Does android phone can do the same function?
Thank you for your answer.


text:
Q: how to write the algorithm for exploding a hierarchy in spherical manner(all parts of assembly should looks like exploded by bomb) I am writing an algorithm for exploding the parts in spherical manner, Please see the Image
I am developing a behavior name "Explode", in which I am taking explode center point from the end user If user does not specify anything default it is bounding box center of assembly given. I have to explode all parts of assembly such that it looks like a spherical distribution of the part, I also know the radius of explosion(input by the user)
My implementation was to find the vector from explode center to each part and explode as per the distance ratio of that part to the part containing maximum distance to the center which is not the correct way of doing it.
My output is:-

Desired output should be like:-

I am not able to think any proper algorithm to explode the part in spherical manner.Can someone help me please?
Thanks in advace


text:
Q: Hive: insert data from a program but not a data file? I want to load data from output of a program but not a existed data file. here's what I want:
CREATE TABLE MyTable (
    X STRING);

INSERT OVERWRITE MyTable
    BY PROGRAM "python MyProgram.py";  -- #!/usr/bin/python
                                       -- print 'hello'
                                       -- print 'world'

SELECT X FROM MyTable;                 -- I will get 2 records:
                                       --   hello
                                       --   world

but it seems hive doesn't provide such INSERT ... BY PROGRAM method. is there an alternative way to do that?

A: What I have used in the past is the Hadoop HDFS Rest Api (http://hadoop.apache.org/docs/r1.0.4/webhdfs.html). I run my program (.py) from the shell and then it pushes the data into HDFS/Hive via the Api. If your Hive table is already set up then you can overwrite the existing Hive file.
Another approach I have used is a program (.py, .sh etc) creates the data into a temp file and then you can add that file using a Hive command and delete the temp file afterward.
Edit:
In response to your comment saying you don't have access to the shell, you could perhaps try to utilize the custom Map/Reduce functionality in Hive (https://cwiki.apache.org/confluence/display/Hive/Tutorial scroll to the bottom to 'Custom Map/Reduce Scripts') and pass into the map-reduce some dummy data that is to be ignored and write your .py script in the form of a reduce and just get it to emit your required data instead.


text:
Q: xml output in readable format I have the below query that returns everything in one line of the xml, is there a way to have the outpup in readable format?  Like the sample below.
SELECT XMLELEMENT("rss",
            XMLATTRIBUTES('http://www.georss.org/georss' AS "xmlns:georss"),
                    XMLELEMENT("channel",
                                 XMLAGG(XMLELEMENT("item",
                                                   XMLFOREST(title AS "title",
                                                              description AS "description",
                                                              point AS "georss:point"))))).EXTRACT('/*')
    FROM (SELECT trim(s.sitedesc) AS title,
          'Employee Count: ' || s.sitefte || '
 Bldg Gross SF: ' || s.bldgarea || '
' || CASE WHEN s.leasestat = '0' THEN 'Owned' WHEN s.leasestat = '1' THEN 'Leased, end date: ' || trim(l.edate) END || '
'||'More Details'||'
' AS description,
          trim(s.latitude) || ' ' || trim(s.longitude) AS point
          FROM ls s
            LEFT OUTER JOIN c0 l ON l.sitecode = s.sitecode
          WHERE s.sold <> 1
            AND s.longitude != ' '
        )
;

returns
<rss xmlns:georss="http://www.georss.org/georss"><channel><item><title>TITLE</title><description>DESCRIPTION<description><georss:point>LAT LON</georss:point></item> ... </channel></rss>

But to make it easier to read would like the output closer to this:
<rss xmlns:georss="http://www.georss.org/georss">
<channel>
    <item>
        <title>TITLE</title>
        <description>DESCRIPTION</description>
        <georss:point>LAT LON</georss:point>
    </item>
...
</channel>
</rss>

A: You can add the returns with a little shell script, like this:
#!/bin/sh
# Usage: ./addreturns.sh foobar.xml.

file=$1

cat $file | perl -pe 's|(<\/.*?>)|\1\n|g' | perl -pe 's|><|>\n<|g' > /tmp/newlines.xml; mv /tmp/newlines.xml $file


text:
Q: mysqli_query(), mysqli_select_db() expects at least 2 parameters I get the following errors on the below php, this is used to get chart information from the mysql database. Appreciate the help

Warning: mysqli_query() expects at least 2 parameters, 1 given in
  C:\wamp\www\test\getuser.php on line 5
      Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\wamp\www\test\getuser.php on line 6
      Call to undefined function mysqli_fetch() in C:\wamp\www\dada\getuser.php on line 18

PHP,
<?php
header("Content-type=text/json;charset=UTF-8");

$aVar = mysqli_connect('localhost', 'root', '123');
mysqli_query("set names utf-8");
mysqli_select_db("test");
$resultset = mysqli_query($aVar,"SELECT name, age FROM echartsuser");

$data = array();

class User{
public $username;
public $age;
}

while($row = mysqli_fetch_assoc($resultset);
$user = new User();
$user->username = $row['name'];
$user->age = $row['age'];
$data[] = $user;
}
mysqli_close();

echo json_encode($data);

?>

A: mysqli_query("set names utf-8");

In the above line you have pass the connection object.
mysqli_query($aVar,"set names utf-8");

Use the above line.
Same in the line number 6 you have to pass the object of connection:
mysqli_select_db($aVar, "test");


text:
Q: Use featureimage in gatsby I want to display featuredImages within my blog-posts.
My frontmatter looks like this:
---
title: My pst with a feature image
date: "2021-05-16T09:45:00.000Z"
description: "Some cool post with a feature image"
tags: [demo]
featuredImage: "feature.png"
---

The index.md and the feature.png are siblings in the same directory. I'm using this query:
query BlogPostBySlugDev($id: String!) {
  markdownRemark(id: {eq: $id}) {
    id
    frontmatter {
      title
      date(formatString: "D. MMMM YYYY", locale: "de-DE")
      dateIso: date(formatString: "YYYY-MM-DD", locale: "en-US")
      description
      tags
      featuredImage {
        childImageSharp {
          gatsbyImageData(width: 400)
        }
      }
    }
  }
}

and I'm getting this result in the GraphiQL:
{
  "data": {
    "markdownRemark": {
      "id": "f73a3644-493c-5cc4-8a5d-f749db898954",
      "frontmatter": {
        "title": "My pst with a feature image",
        "date": "16. Mai 2021",
        "dateIso": "2021-05-16",
        "description": "Some cool post with a feature image",
        "tags": [
          "demo"
        ],
        "featuredImage": {
          "childImageSharp": null
        }
      }
    }
  },
  "extensions": {}
}

This is not what I expected. I would have expected to get my image-data here ... likewise I'm getting this message on the console (running gatsby in development mode):
warn You can't use childImageSharp together with undefined.undefined — use publicURL instead. The childImageSharp portion of the query in this file will return null:
undefined

I'm using these packages:
    "gatsby": "^3.1.1",
    "gatsby-plugin-feed": "^3.1.0",
    "gatsby-plugin-gatsby-cloud": "^2.1.0",
    "gatsby-plugin-google-analytics": "^3.1.0",
    "gatsby-plugin-image": "^1.1.1",
    "gatsby-plugin-manifest": "^3.1.0",
    "gatsby-plugin-offline": "^4.1.0",
    "gatsby-plugin-pnpm": "^1.2.5",
    "gatsby-plugin-react-helmet": "^4.1.0",
    "gatsby-plugin-sharp": "^3.1.1",
    "gatsby-plugin-typescript": "^3.1.0",
    "gatsby-remark-copy-linked-files": "^3.1.0",
    "gatsby-remark-images": "^4.1.0",
    "gatsby-remark-prismjs": "^4.1.0",
    "gatsby-remark-responsive-iframe": "^3.1.0",
    "gatsby-remark-smartypants": "^3.1.0",
    "gatsby-source-filesystem": "^3.1.0",
    "gatsby-transformer-remark": "^3.1.0",
    "gatsby-transformer-sharp": "^3.1.0",

I also extended the Frontmatter type in my gatsby-node.js, so that featureImage would be recognized as a file:
    type Frontmatter {
      title: String
      description: String
      date: Date @dateformat
      tags: [String!]
      featuredImage: File
    }

And finally I setup the gatsby-source-filesystem plugin to resolve two paths (as I have posts and pages):
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/blog`,
        name: `blog`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    }

What might I be missing?

A: You said:

The index.md and the feature.png are siblings in the same directory.

But your gatsby-source-filesystem shows two different folders:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/content/blog`,
    name: `blog`,
  },
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images`,
  },
}

It seems that Gatsby is not able to create the proper nodes for your image because it's not able to find it in your filesystem.
I would suggest following your gatsby-source-filesystem approach, so, one folder for the posts (markdowns) and one folder for the images. Both folders can be siblings of course but then, your markdown structure should look like:
---
title: My pst with a feature image
date: "2021-05-16T09:45:00.000Z"
description: "Some cool post with a feature image"
tags: [demo]
featuredImage: "../feature.png"
---


text:
Q: .NET Core - How to pass file from View to Controller as its parameter? I have to create API to read data from JSON file and save it into database. So I did it and it works fine when I send file using Postman. But I also need to be able to do the same operation using form in my view and I cannot figure out solution for it.
ImportController.cs
[Produces("application/json")]
[Route("api/Import")]
public class ImportController : ControllerBase
{

    private readonly DbContext dbContext;

    public ImportController(DbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpPost]
    [Route("ImportData")]
    public IActionResult ImportData(IFormFile file)
    {

        var content = string.Empty;

        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            content = reader.ReadToEnd();
        }

        List<UserImportModel> userObjects = null;
        try
        {
            userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content);
        }
        catch
        {
            return BadRequest();
        }

        foreach (var user in userObjects)
        {

            UserModel us = new UserModel
            {
                Username = user.Username,
                Password = user.Password,
                Created = DateTime.UtcNow
            };

            dbContext.User.Add(us);
            dbContext.SaveChanges();
        }

        return Ok();
    }

Form in my view
    <form method="post" enctype="multipart/form-data" action="../api/Import/ImportData">
         <input type="file" name="file" id="file">
         <input type="submit" value="Upload file" name="submit">
    </form>

When I enter Developer Tools in my browser and click submit, following data is displayed as POST parameters:
-----------------------------209091002211274
Content-Disposition: form-data; name="file"; filename="test.json"
Content-Type: application/json

[{"Username":"user1","Password":"123456"},{"Username":"user2","Password":"654321"}]
-----------------------------209091002211274
Content-Disposition: form-data; name="submit"

Upload file
-----------------------------209091002211274--

It leads me to believe that file and its data is send, is that right?

A: I think it is because it is an array [ ]  of objects rather than a JSON collection { }


text:
Q: Openshift: How to alert/publish a message if deployment/build fails In our deployment process it is crucial that we are informed, when a deployment fails. The deployment is rolling, but an information through slack would be nice anyway. Would it be possible through lifecycles or what other possibilities do exist?

A: The deployment status is logging out as events logs from OpenShift usually.
Do you use OpenShift logging component EFK stack ? Then additionally consider to install EventRouter, it collects OpenShift events logs as eventrouter pod's logs.
You can pick up the deployment event messages from the logs and trigger the alert by custom script or monitoring system's log tailing feature and so on.
Refer Specifying Logging Ansible Variables
 for ansible variable details.
openshift_logging_install_eventrouter
openshift_logging_eventrouter_nodeselector
openshift_logging_eventrouter_namespace
...

A: You can pass customParams to the deployment process and do a curl if openshift-deploy fails.
"strategy": {
  "type": "Rolling",
  "timeoutSeconds": 180,
  "customParams": {
    "command": [
      "/bin/sh",
      "-c",
      "set -e && if ! openshift-deploy; then curl -i -X POST -d '{\"text\": \"Deployment of ${application} failed!\"}' ${webhook} && exit 1; else echo \"Deployment complete\"; fi"
    ]
}


text:
Q: Range projection of the multiplication of a positive element and a projection in a von Neumann algebra
When verifying the statement marked red, I met with some troubles.
If we let $T=(A_{+})^{\frac{1}{2}}\chi_{(\lambda,\infty)}(A)$, we have $T=\chi_{(\lambda,\infty)}(A)(T^*T)^{\frac{1}{2}}$,and thus $\chi_{(\lambda,\infty)}(A)\chi_{(\lambda,\infty)}(A)^*=R_{T}$.
1.Why does the following equality hold?
$$\chi_{(\lambda,\infty)}(A)=\{(A_{+})^{\frac{1}{2}}\zeta|\zeta=\chi_{(\lambda,\infty)}(A)\zeta\}$$
The left side is an operator, while the right side is a set of vectors.
2.Let $0\neq \zeta'=E\zeta'$ and $\eta'=V\zeta'$, how to conclude that $\zeta'=(A_{+})^{\frac{1}{2}}\zeta$ for some $0\neq \zeta=\chi_{(\lambda,\infty)}(A)\zeta$?


text:
Q: Rollup : Why am I getting "Uncaught ReferenceError: exports is not defined" when trying to inject umd.js in jsp file? I have a js library that was bundled with rollup js. I tested the lib in a SPA it work great. But when I tried to use it in a spring project by the include of the umd file in jsp pages. I got an error that exports is not defined.

I tried to change version of the js but the error still persists.
<c:url value="./target/js/script_generated.umd.js" var="kj">
  <c:param name="version" value="es6" />
</c:url>
<script type="text/javascript" src="${kj}"></script>

Any idea please how I can inject this lib in the jsp?


text:
Q: Ubuntu 19.04 Screen Sharing Issues I just did a fresh install of Ubuntu 19.04 on a new computer today. I need to be able to use VNC (Remmina) to remotly connect to this new computer regularly.
I logged on, ran
sudo apt install vino

and then rebooted and then used my ubuntu 18.10 laptop to try to connect and get a dialog stating:
TLS handshake failed: An illegal TLS extension was received..

I then confirmed all the settings, and then even went and ran this on the server
sudo gsettings set org.gnome.Vino require-encryption false

But I still got the same error
Remmina's log window gives me this additional info
[VNC]VNC server supports protocol version 3.7 (viewer 3.8)
[VNC]We have 2 security types to read
[VNC]0) Received security type 18
[VNC]Selecting security type 18 (0/2 in the list)
[VNC]1) Received security type 2
[VNC]Selected Security Scheme 18
[VNC]TLS session initialized.
[VNC]TLS anonymous credential created.
[VNC]TLS handshake blocking.
[VNC]TLS handshake failed: An illegal TLS extension was received..

I can not for the life of me figure out how to connect to this machine, I primarily use this machine remotly so this is kind of important if anyone knows of a fix. I might try a fresh install even but have a feeling it wouldnt matter as this was litterally the first thing i did


text:
Q: GPG : find secret keys expiration date I'm new with GPG but reading GPG documentation the only thing that do not seems clear to me is if when a couple of keys were generated, there's a way to find if the private one has an expiration date.
Please consider that I'm working with not default keyring because secring/pubring are stored into docker container / Openshift.
Thanks in advance.


text:
Q: Extend prepare() to Database class I'm using:
> $db = new Database(); // my own Database class

> $result = $db -> query(sql);

> $row = $result -> fetch_array(MYSQLI_BOTH);

... and it does so fine and without any issues. But often times the sql is changed a bit based on user input (or can be altered by user input), which I've learned is extremely susceptible to sql injection. Yikes.
So I've been reading up on prepared statements, and I'm ready to switch to something more like this:
> $db = new Database();

> $stmt = $db -> prepare(sql);

> if ($stmt->execute(array($_GET['name'])) {

> > while ($row = $stmt->fetch()) {

> > > print_r($row);

> > }

> }

... which I've grabbed from example #3. I've altered my code to fit what I want but I'm getting Call to undefined method Database::prepare(), which I realize means I don't have the prepare() method available in the class. How can I extend this functionality? And if you don't mind, a little explanation might be helpful. :)
Edit: Here are the contents of my current Database class.
class Database {

private $link;
private $host = "#####";
private $username = "#####";
private $password = "####";
private $db = "####";

public function __construct(){
    $this->link = new mysqli($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    return true;
}

public function query($query) {
    $result = mysqli_query($this->link, $query);
    if (!$result) die('Invalid query: ' . mysql_error());
    return $result;
}

public function __destruct() {
    mysqli_close($this->link)
        OR die("There was a problem disconnecting from the database.");
}

}

A: Return the mysqli link from your construct or you could write a get method for returning the link.
public function __construct(){
    $this->link = new mysqli($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    return $this->link;
}

And try this:
 $db = new Database();
 $name = $_GET['name']; // try validating the user input here
 if( $stmt = $db->prepare($sql) ){
       $stmt->bind_param("s", $name);
       $stmt->execute();
       while ($row = $stmt->fetch()) {
           print_r($row);
       }
 }

A: Make Database extend mysqli
class Database extends mysqli
{

    private $link;
    private $host = "#####";
    private $username = "#####";
    private $password = "####";
    private $db = "####";

    public function __construct()
    {
        parent::__construct($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    }

    public function __destruct()
    {
        mysqli_close($this->link)
        OR die("There was a problem disconnecting from the database.");
    }

}

Then you can call $db as if it's a mysqli object
$db = new Database();
$db->query($sql);

BUT you should just use the mysqli object directly if you're not really adding any functionality to the class...


text:
Q: Storing complex computed data between orientation change In the onCreate() of my MainActivity, my app does an intensive operation to generate some data set (runs in a separate thread, but takes some 2 - 3 seconds to complete normally). Now my problem is that, when orientation changes, the app again does this complex computation again.
Since I haven't done anything like this before, I was wondering if there is a way around this. My first thought was to store the computed data in a static variable, so that the data is persisted between different instances of MainActivity. I am guessing this is not the best approach.
My data set consists of a Map and an ArrayList and not a simple data type, if it helps.
I have looked at the onSaveInstanceState(), but it only provides to store values like int, String, etc.

A: In addition to what @Raghunandan suggested you can read the official docs on Recreating an Activity .
It says:
Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout.
It also introduces the concept of
onSaveInstanceState()(To save additional data about the activity state, you must override this method) and
onRestoreInstanceState() method (The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle)).
You can also see the sample implementation of these methods here Saving Android Activity state using Save Instance State thread, which will help you to save and restore the state.
Update
You may also try using:
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

The docs for android:configChanges say;
It lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Source: How to save state during orientation change in Android if the state is made of my classes?
Hope this helps.


text:
Q: Java Swing - JFrame GUI Elements made invisble on resize and open I have a secondary JFrame for a settings panel, however, whenever it is opened or resized all elements inside it (a lot of textfields, sliders and so forth) go invisible.
I can get the GUI elements visible by clicking and dragging over them, so to me it sounds like a rendering order error / missing redraw call. But, the call is very much there (in setVisible()), it just doesn't help.
Also the window is toggled from a button on a main window.
Here's an excerpt of the parts I'm quite sure is messing with me currently:
public class SettingsWindow{
    public SettingsWindow(int xW, int yH){
    frame = new JDialog();
    frame.setTitle("Generator Settings");
    frame.setBounds(0,0,xW,yH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.addWindowListener(new WindowListener() {

            ...
        @Override
        public void windowClosing(WindowEvent e) {
            SettingsWindow.this.onClose();
        }
            ...
    });
    frame.addComponentListener(new ComponentAdapter()
    {
        public void componentResized(ComponentEvent evt) {
            setVisible(true);
        }
    });
    localConfig = new Config(); //Config auto-loads in parameters from a file
    addComponents(frame);

}

private void addComponents(JDialog frame) {
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0,0,frame.getWidth(),frame.getHeight());
    scrollPane.createVerticalScrollBar();

    int heightOffset = frame.getHeight()/14;
    int i = 0;
    for(JComponent jc : localConfig.getModComp((int) (frame.getWidth() * 0.95), heightOffset)){   //config.getModComp() gets all the buttons and sliders needed, each in the size specified
        jc.setLocation(0,i * heightOffset);
        scrollPane.add(jc);
        i++;
    }

    scrollPane.setVisible(true);
    frame.add(scrollPane);
}

private void onClose() {
    setVisible(false);
}
public void toggle(){
    frame.setVisible(!isVisible);
    isVisible = !isVisible;        //class atribute
}
public void setVisible(boolean state){
    isVisible = state;         //class attribute
    frame.setVisible(state);
    for(Component jc : frame.getContentPane().getComponents()){
        jc.setVisible(state);
        jc.revalidate();
        jc.repaint();
    }
}

}
I've tried a lot of things, but none has worked so far. This was meant to be a quick, 10 min adventure into some generative patterns and stuff, but uh. I guess that didn't happen.
Any suggestions are much appreciated.
Here's how it looks when I've dragged over all of the invisible components to make them appear:

PS: None of the GUI components are special / anonymous sub-classes. All stock with a couple of ActionListeners on some of them.

A: scrollPane.add(jc);

Don't add components directly to the scroll pane. Instead, a single component is added to the "viewport" of the scroll pane.
So typically you would create a JPanel (using appropriate layout managers) and add the components to the panel and then create the scroll pane using this panel:
JPanel panel = new JPanel(...);
panel.add( component1 );
panel.add( component2 );
JScrollPane scrollPane = new JScrollPane( panel );
...
dialog.add( scrollPane );


text:
Q: Understanding perspective transform in 3D Core Animation I'm trying to create a view consisting of several 3D cube's viewed from a center perspective of the containing view.
When I set a cube view as a direct subview of the container view and then set the perspective as follows;
var perspective = CATransform3DIdentity
perspective.m34 = -1.0/250
containerView.layer.sublayerTransform = perspective

The 3d perspective transform works as expected. However, if I first add the cube view to a innerContainerView and then add that to the parent container view the perspective is lost. I created a playground to illustrate my problem.
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 667.0, height: 375.0))
containerView.backgroundColor = UIColor.grayColor()
XCPlaygroundPage.currentPage.liveView = containerView

let green = UIColor.greenColor()
let blue = UIColor.blueColor()
let red = UIColor.redColor()
let purple = UIColor.purpleColor()
let yellow = UIColor.yellowColor()
let orange = UIColor.orangeColor()

var perspective = CATransform3DIdentity
perspective.m34 = -1.0/250
containerView.layer.sublayerTransform = perspective

let cubeView1 = CubeView(frontColor: green, backColor: blue, topColor: red, rightColor: purple, bottomColor: yellow, leftColor: orange)
cubeView1.frame = CGRectMake(50, 50, 100, 100)
let innerContainerView = UIView(frame: CGRectMake(0, 100, 200, 200))
innerContainerView.backgroundColor = UIColor.lightGrayColor()
containerView.addSubview(innerContainerView)
innerContainerView.addSubview(cubeView1)

let cubeView2 = CubeView(frontColor: green, backColor: blue, topColor: red, rightColor: purple, bottomColor: yellow, leftColor: orange)
cubeView2.frame = CGRectMake(400, 200, 100, 100)
containerView.addSubview(cubeView2)

I'm trying to create the same perspective shown in the right cube in the left cube. So why is it when I add the an intermediate view I lose the perspective?

A: CoreAnimaton rendering model always flattens rendering operations on to the parent layer. The one exception to this rule is CATransformLayer which doesn't do any flattening and just passes the transforms through. Creating a UIView with CATransformLayer as the  layerClass and using that as innerContainerView should solve the issue.


text:
Q: getSelectedItem() on GWT MenuBar I'm new to GWT so please help me. I'm having a problem in my GWT MenuBar on how to getSelectedItem().
Here's my code:
public class Menu extends Composite implements Command {
    private MenuBar menu            = new MenuBar();
    private MenuBar priceMgt        = new MenuBar( true );
    private MenuBar salesReport     = new MenuBar( true );
    // and a lot more menubars

    private String[] itemPriceMgt = {
        "Manage Price List", "Print Product Pricing", "Price Proof List"
    };

    private String[] itemSalesReport = {
        "Sales Transaction List", "Cashier Report", "Media Tender Report",
        "Sales Report by Employee", "Sales Warranty Tracking", "Sales Report by Product",
        "Sales Summary by Branch", "Sales Summary by Product", "Sales Summary by Period",
        "Product Movement Analysis", "Sales Comparison",
        "Sales Book", "Download eSales"
    };

    public Menu() {
        loadMenu();
    }

    private void loadMenu() {
        addSubMenuItem( priceMgt, itemPriceMgt );
        addSubMenuItem( salesReport, itemSalesReport );

        menu.addItem( "Home", false, this );
        menu.addItem( "Price Management", priceMgt );
        menu.addItem( "Sales Report", salesReport );
        menu.addItem( "Logout", false, this );

        initWidget( menu );
    }

    private void addSubMenuItem( MenuBar menubar, String[] list ) {
        for( int i = 0; i < list.length; i++ ) {
            menubar.addItem( list[i], this );
        }
    }

    public void execute() {
        // load the selected module
        // by getting the selected item
        // i can't use menu.getSelectedItem() - it's protected.
        // when i extend this class to MenuBar, adding Item says ambiguous
        // method addItem(String,Command) for MenuBar
        // how can I get the items being selected/clicked?
    }
}

Others may say it's a not useful post but I really don't know how to figure it out. please help me. Thanks in advance.

A: Here is a version that might work for you.  The trick is that a specific Command needs to be associated with each MenuItem, not one command for all of them:
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.MenuBar;

public class Menu extends Composite {
    private MenuBar menu = new MenuBar();
    private MenuBar priceMgt = new MenuBar(true);
    private MenuBar salesReport = new MenuBar(true);
    // and a lot more menubars

    private String[] itemPriceMgt = { "Manage Price List",
            "Print Product Pricing", "Price Proof List" };

    private String[] itemSalesReport = { "Sales Transaction List",
            "Cashier Report", "Media Tender Report",
            "Sales Report by Employee", "Sales Warranty Tracking",
            "Sales Report by Product", "Sales Summary by Branch",
            "Sales Summary by Product", "Sales Summary by Period",
            "Product Movement Analysis", "Sales Comparison", "Sales Book",
            "Download eSales" };

    public Menu() {
        loadMenu();
    }

    private void loadMenu() {
        addSubMenuItem(priceMgt, itemPriceMgt);
        addSubMenuItem(salesReport, itemSalesReport);

        menu.addItem("Home", false, new Command() {
            @Override
            public void execute() {
                // TODO execute a Home command
            }
        });
        menu.addItem("Price Management", new Command() {
            @Override
            public void execute() {
                // TODO execute a Price Management command
            }
        });
        menu.addItem("Sales Report", new Command() {
            @Override
            public void execute() {
                // TODO execute a Sales Report command
            }
        });
        menu.addItem("Logout", false, new Command() {
            @Override
            public void execute() {
                // TODO execute a Logout command
            }
        });

        initWidget(menu);
    }

    class SubMenuItemCommand {
        private String commandName = null;

        public SubMenuItemCommand(String commandName) {
            this.commandName = commandName;
        }

        public Command subMenuItemCommand = new Command() {
            @Override
            public void execute() {
                if (commandName.equals("Manage Price List")) {
                    // TODO execute the Manage Price List command
                } else if (commandName.equals("Print Product Pricing")) {
                    // TODO execute the Print Product Pricing command
                }
                // and so on
            }
        };
    }

    private void addSubMenuItem(MenuBar menubar, String[] list) {
        for (int i = 0; i < list.length; i++) {
            menubar.addItem(list[i],
                    new SubMenuItemCommand(list[i]).subMenuItemCommand);
        }
    }
}

I've re-worked your code to use that approach, but have tried to keep as close to your original design as possible.  Other people might suggest just rewriting the whole thing, but I think you'll be able to understand better how this works if we tack closely to your design.
An ugly part of this design is the SubMenuItemCommand class.  I create a separate object for each submenu item, which is fine, but each object provides a unique Command with a whole bunch of code in it that executes exactly one path in it, ever.  Lots of wasted bytecode there.  But like I said, I wanted to stick close to your design.  Once you get comfortable with it, you'll probably rewrite it yourself.
Another approach for the submenu is to create a Map of Strings to Commands, then pull the right Command from the Map to associate to each MenuItem named for that String.

A: Instead of having this class implement Command and having all of your menu items use this as their argument when they are added with .addItem(), make a different Command object for each of your menu items. Then, code the specific logic for each menu item into the separate command objects.
i.e.:
 menu.addItem( "Home", false, new Command() {
      @Override
      public void execute() {
           // handle "Home" case here
      }
 );

If you really want to handle every menu item from the same piece of code, then you could make a Factory that takes the name of the menu item and produces a Command object that can reference it.


text:
Q: Error installing rgdal library in R : I am struggling with terra installation. To be complete, I tried every hints I have found in google, but nothing change this error message. I need rgdal as 'terra' dependency if I understand well, but I receive the same message when I try to install terra or rgdal. I have tried to uninstall, reinstall, install via pip, via conda, but nothing works. I am quite desperate.
gdal is installed via brew:
gdal-config --version gives 3.5.0
Logs in R :
> install.packages("terra")
Installation du package dans '/home/col1/R/x86_64-pc-linux-gnu-library/4.2'
(car 'lib' n'est pas spécifié)
essai de l'URL 'https://cloud.r-project.org/src/contrib/terra_1.5-34.tar.gz'
Content type 'application/x-gzip' length 667829 bytes (652 KB)
==================================================
downloaded 652 KB

* installing *source* package 'terra' ...
** package 'terra' correctement décompressé et sommes MD5 vérifiées
** using staged installation
configure: CC: gcc
configure: CXX: g++ -std=gnu++11
checking for gdal-config... /home/linuxbrew/.linuxbrew/bin/gdal-config
checking gdal-config usability... yes
configure: GDAL: 3.5.0
checking GDAL version >= 2.0.1... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking gdal.h usability... yes
checking gdal.h presence... yes
checking for gdal.h... yes
checking GDAL: linking with --libs only... no
checking GDAL: linking with --libs and --dep-libs... no
/home/linuxbrew/.linuxbrew/bin/ld: /home/linuxbrew/.linuxbrew/Cellar/gdal/3.5.0_1/lib/libgdal.so: undefined reference to `opj_decoder_set_strict_mode'
/home/linuxbrew/.linuxbrew/bin/ld: /home/linuxbrew/.linuxbrew/Cellar/gdal/3.5.0_1/lib/libgdal.so: undefined reference to `std::__throw_bad_array_new_length()@GLIBCXX_3.4.29'
/home/linuxbrew/.linuxbrew/bin/ld: /home/linuxbrew/.linuxbrew/Cellar/gdal/3.5.0_1/lib/libgdal.so: undefined reference to `opj_encoder_set_extra_options'
collect2: error: ld returned 1 exit status
/home/linuxbrew/.linuxbrew/bin/ld: /home/linuxbrew/.linuxbrew/Cellar/gdal/3.5.0_1/lib/libgdal.so: undefined reference to `std::__throw_bad_array_new_length()@GLIBCXX_3.4.29'
collect2: error: ld returned 1 exit status
configure: Install failure: compilation and/or linkage problems.
configure: error: GDALAllRegister not found in libgdal.
ERROR: configuration failed for package 'terra'
* removing '/home/col1/R/x86_64-pc-linux-gnu-library/4.2/terra'
Warning in install.packages :
  l'installation du package 'terra' a eu un statut de sortie non nul
Les packages source téléchargés sont dans
    '/tmp/RtmpaCYwto/downloaded_packages'

If anyone have a clue, I would really appreciate,


text:
Q: Initialize control in control This is my custom control class:
// Extended ComboBox where ill change some property.
public class ExtComboBox : ComboBox
{
    ...
}

// ExtButton is a control that i am going to drop on Form from ToolBox.
public partial class ExtButton : Button
{
    public ExtComboBox ComboBoxInsideButton { get; set; }

    public ExtButton()
    {
        InitializeComponent();

        ComboBoxInsideButton = new ExtComboBox();
        ComboBoxInsideButton.Text = "hi!";

        Controls.Add(ComboBoxInsideButton);
    }
}

Basically when i add this control to form there will be ComboBox on top off Button.
Don't ask my why i need this :D
Now if i need to change ComboBox text i simply use:
extButton1.ComboBoxInsideButton.Text = "aaa";

All work fine.. but :) when i am trying to change some ComboBox properties in Design mode (Window Properties -> Expand ComboBoxInsideButton -> Change Text to "bbb")
after rebuilding or running project ComboBox properties will be reseted (ExtButton.Designer.cs)
Question 1: How to initialize  subcontrol with some default properties value, so when ill drop control on Form all setting will be added?
and
Question 2: How to change properties of subcontrol on design time.
EDIT:
Answer here: Designer does not generate code for a property of a subcontrol. Why?
Adding [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] solves the problem.

A: I wrote a mini-tut on how to create custom UserControls and accessing their members here.  Pretty much, it looks like you are going to want add properties to your ExtComboBox that expose the ComboBox properties you'd like to change.  Then, in ExtButton, you will be able to use the . to change these values at runtime.
Also, instead of doing:
public ExtComboBox ComboBoxInsideButton { get; set; }
...
ComboBoxInsideButton = new ExtComboBox();

do
public ExtComboBox comboBoxInsideButton = null;
...
comboBoxInsideButton = new ExtComboBox();

Be sure to understand the difference between private and public also.  I'm not sure if you want your ExtComboBox to be public if you're placing it on another control.
Hope this helps.


text:
Q: Set Controls with arbitrary positions on CTabItem I am new to SWT, and I need to set the controls positions arbitrary on CTabItem.
I've used the following code, but it seems that it had no positioning effect, it just add the component to (0, 0)
Label userName = new Label(folder, SWT.NONE);
userName.setText("username");
userName.setBounds(10, 200, 200, 50);
item.setControl(userName);

A: You will need to set a LayoutManager to folder, e.g.:
folder.setLayout(new GridLayout());

If you wish to give the control a certain dimensions, consider giving it LayoutData, e.g.:
GridData gd = new GridData();
gd.height = 50;
userName.setLayoutData(gd);

I'm not sure what item is in your example, but it doesn't seem to be necessary.


text:
Q: How to fix a drupal (https) website with blocked mixed content My Drupal e-commerce site is working on https.I want to embed below code to a page.
<iframe src="http://files.podsnack.com/......"(not exact code)

But src is on http, due to this not able to load the iframe in the page. I am getting below error.
Blocked loading mixed active content "http://files.podsnack.com/iframe/embed.html?hash=avcsgijp&t=1402616221"
carouFredSel: No element found for "#clients-scroller".
plugins... > eval (line 1)

Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings.  It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

Note: src will not work on https.

Please advise.

A: I'm afraid you cannot load an iframe via http on a https page securely, thus getting the errors. Browsers are beginning to just completely block this now, where as older browsers would just give a warning.
The only way to get it to load is using https for the iframe, or accessing the page via http instead of https.
See this blog post about Firefox introducing the block: https://blog.mozilla.org/tanvi/2013/04/10/mixed-content-blocking-enabled-in-firefox-23/
and here's a page about IE blocking mixed content: http://support.microsoft.com/kb/2625928
and here's a page about Chrome blocking mixed content or warning about it: https://support.google.com/chrome/answer/1342714?hl=en
And see this post for a general explanation of the problem: https://developer.mozilla.org/en-US/docs/Security/MixedContent/How_to_fix_website_with_mixed_content


text:
Q: PHP development without xampp I have machine on which I lack admin privileges. I was not able to install xampp server on it. So I tried portable version of xampp. But I was getting error while starting Apache server and MySQL. The log file is not getting created.
Also many tutorials online use NetBeans which is also I am not able to install due lack of admin privileges.
I have postgres and apache tomcat working on my machine, which I used for Java Spring development. I also have eclipse installed on my machine. So I was thinking if I can manually configure eclipse, postgres, tomcat to develop php without installing xampp or netbeans.
Is it possible? If yes how do I do it? Is there any tutorial / link / webpage explaining the same?

A: If you can install jetbrains PhpStorm it has a built in server but due to lack of privileges i think it is not posiible though, so here are two links i have for you, hope you will able to find an answer..
https://www.eclipse.org/articles/article.php?file=Article-EclipseDbWebapps/index.html
https://www.enterprisedb.com/postgres-tutorials/how-connect-postgres-database-using-eclipse-and-netbeans

A: if you use php framework like laravel, cakephp etc.
Those have own development server to run application.
and for the database you can use sqlite database.
that not require xampp server


text:
Q: How to hide the login button on my personal blog I decided to implement a blog system on Google AppEngine. But:

*

*I don't want to add a login button on my blog.

*I don't want to provide a url to type in manually to login.

But I still want to do admin things ONLINE and only for myself, e.g. posting, editing, deleting and etc.
Any clever ways to implement this?

A: You can add a component to the web page template that is only rendered if you are an admin.
For example, in your HTML template if you have something like this it'll only render the content if admin_bool is True. So you can put a form etc inside there and only you'll see it.
    {% if admin_bool %}
        # only show this if you are an admin
    {% endif %}

So if you happen to be using the GAE users service you can do this:
    from google.appengine.api import users

    user = users.get_current_user()
    if user:
        print "Welcome, %s!" % user.nickname()
    if users.is_current_user_admin():
        admin_bool = True

and pass admin_bool to your template and it'll render only if the current user is an admin.
https://developers.google.com/appengine/docs/python/users/adminusers
http://webapp-improved.appspot.com/tutorials/gettingstarted/usingusers.html#tutorials-gettingstarted-usingusers
http://webapp-improved.appspot.com/tutorials/gettingstarted/templates.html#tutorials-gettingstarted-templates

A: I don't see any reason of not providing a secret URL that simply is not shown anywhere and then simply having for your admin pages the administrator required in your app.yaml, like this:
- url: /admin/.*
  script: admin.app
  login: admin

But if you really really want to not provide anything you can still do that. Don't forget that you are allowed to deploy up to 10 different versions for the same application on Google App Engine with unique URLs that can be accessed like this:
http://version-name.application-name.appspot.com

So you can create a totally different application to administrate your site and another application to present it. Deploy them both on the same app and having the right one as a default version.

A: Provide a different page or URL that shows the login button for the admin features of the blog. For example, a blog can be hosted on wordpress.com, where the admin can login, but accessed by a different URL that does not expose the login button.

A: You could use a keyboard shortcut. Or an invisible button. Maybe a gesture.


text:
Q: Display link to Careers Profile in Accounts tab Would it be possible to display a link to my Careers profile in the Accounts tab.
I realise not everybody may want this so maybe it could be enabled/disabled via the Prefs tab.

A: In the "About Me" section of your profile exists an area where you can write anything about yourself that you want to share with the world.  This is the one area where you are encouraged to promote yourself.
Thus, this feature more or less exists on a per user basis.  If you want your Career profile to be visible, you could post it there.  For users who don't want this information listed, they can easily omit it.


text:
Q: Drag from Tree to div I am trying to implement a drag and drop senario from an extJs TreePanel into a div in the body of the page. I have been following an example by Saki here.
So far I have the below code:
var contentAreas = new Array();
var tree = new Ext.tree.TreePanel({
                title : 'Widgets',
                useArrows: true,
                autoScroll: true,
                animate: true,
                enableDrag: true,
                border: false,
                layout:'fit',
                ddGroup:'t2div',
                loader:new Ext.tree.TreeLoader(),
                root:new Ext.tree.AsyncTreeNode({
                    expanded:true,
                    leaf:false,
                    text:'Tree Root',
                    children:children
                }),
                listeners:{
                    startdrag:function() {
                         $('.content-area').css("outline", "5px solid #FFE767");
                    },
                    enddrag:function() {
                        $('.content-area').css("outline", "0");
                    }
                }
            });

            var areaDivs = Ext.select('.content-area', true);
            Ext.each(areaDivs, function(el) {
                var dd = new Ext.dd.DropTarget(el, {
                    ddGroup:'t2div',
                    notifyDrop:function(ddt, e, node) {
                        alert('Drop');
                        return true;
                    }
                });
                contentAreas[contentAreas.length] = dd;
            });

The drag begins and the div highlights but when I get over the div it does not show as a valid drop target and the drop fails.
This is my first foray into extJS. I'm  JQuery through and through and I am struggling at the moment.
Any help would be appreciated.
Ian
Edit
Furthermore if I create a panel with a drop target in it, this works fine. What is the difference between creating an element and selecting an existing element from the dom. This is obviously where I am going wrong but I'm none the wiser. I have to be able to select existing dom elements and make them into drop targets so the code below is not an option.
Here is the drop target that works
var target = new Ext.Panel({
                renderTo: document.body
                ,layout:'fit'
                ,id:'target'
                ,bodyStyle:'font-size:13px'
                ,title:'Drop Target'
                ,html:'
'
                      +'Drop a node here. I\'m the DropTarget.
'

                // setup drop target after we're rendered
                ,afterRender:function() {
                    Ext.Panel.prototype.afterRender.apply(this, arguments);
                    this.dropTarget = this.body.child('div.drop-target');
                    var dd = new Ext.dd.DropTarget(this.dropTarget, {
                        // must be same as for tree
                         ddGroup:'t2div'

                        // what to do when user drops a node here
                        ,notifyDrop:function(dd, e, node) {
                            alert('drop');
                            return true;
                        } // eo function notifyDrop
                    });
                }
            });

A: See if adding true as the second param here makes any difference:
var areaDivs = Ext.select('.content-area', true);

As a cosmetic note, the param name e conventionally indicates an event object (as in the second arg of notifyDrop).  For an element, el is more typical.  Doesn't matter functionally, but looks weird to someone used to Ext code to see e passed into the DropTarget constructor.

A: If you are having problem duplicating a working example such as that, copy the entire thing, then modify it to your needs line-by-line - you can't go wrong.

A: As i know you can't set DropZone to any Ext element, just to Ext component. So this might be you problem. Try to use DropTarget instead of DropZone.


text:
Q: Как найти сумму двумерного массива? Есть обобщенный метод в котором параметр принимает двумерный массив.
Вопрос, как найти сумму?
Код моих попыток ниже:
static <T extends Number> T function(T array[][]) {
    Integer summ;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            summ = summ + array[i][j]; // error
        }
    }
    return summ; // error
}

A: Можно сделать перегрузку. Это единственное верное решение вашей задачи! Так как summ может быть и Float, и Double, и Integer. То есть мы не можем явно проинициализировать значение этой переменной
static Long function(Long array[][]) {
    Long summ = 0L;

    for (Long[] anArray : array) {
        summ += Stream
                .of(anArray)
                .mapToLong(s -> s)
                .sum();
    }
    return summ;
}

static Double function(Double array[][]) {
    Double summ = 0.0;

    for (Double[] anArray : array) {
        summ += Stream
                .of(anArray)
                .mapToDouble(s -> s)
                .sum();
    }
    return summ;
}

static Integer function(Integer array[][]) {
    Integer summ = 0;

    for (Integer[] anArray : array) {
        summ += Stream
                .of(anArray)
                .mapToInt(s -> s)
                .sum();
    }
    return summ;
}

Пример:
Integer[][] s = new Integer[][]{{1, 4, 5}, {2, 2, 9}};
System.out.println(function(s));

Double[][] s = new Double[][]{{1.4, 4.8, 5.9}, {2.4, 2.9, 9.3}};
System.out.println(function(s));

A: Обновление
Принятый ответ мне не нравится из-за необходимости дублировать код. Есть и такой вариант через наследование. Преимущество в том, что если понадобится написать generic для других операций, либо добавить метод, который, например, считает сумму трёх чисел - не нужно будет опять писать переопределения, можно будет переиспользовать уже написанные калькуляторы. Похожий подход используется для IComparer
public abstract class Calculator<T>
{
    public abstract T Add(T a, T b);
    public abstract T DefaultValue();
}

public class IntegerCalculator extends Calculator<Integer>
{
    @Override
    public Integer Add(Integer a, Integer b)
    {
        return a + b;
    }

    @Override
    public Integer DefaultValue() {
        return 0;
    }
}

public class HelloWorld{

     public static void main(String []args){
        Integer nums[] = { 1,2,3 };
        System.out.println(summArr(nums, new IntegerCalculator()));
     }

     public static <T> T summArr(T[] numbers, Calculator<T> calc) {
        T summ = calc.DefaultValue();
        for(T num: numbers) {
            summ = calc.Add(num, summ);
        }
        return summ;
     }
}

Оригинальный ответ

*

*Integer summ - объявляет переменную, но не задаёт ей значение. Чему равно summ + 5 ? Никто не знает, т.к. для summ не было задано начальное значение. Возможно в Java по умолчанию, это ноль, но лучше написать самому.

*Двумерный массив - это массив массивов.
Integer arr1[] - arr1[0] - это число, равное 1
arr1: [1,2,3,4]
Integer arr2[][] - arr2[0] - это массив, который состоит из чисел [1,2,3,4].
arr2: [[1,2,3,4],[5,6,7,8]].
Таким образом в коде две ошибки: не проиницилизорованно начальное значение summ и во-втором цикле используется arr.length, тогда, как нам нужна длина вложенного массива arr[i].length.
static <T extends Number> T function (T array[][]){
        T summ = 0;
        for(int i = 0; i < array.length; i++){
            for(int j = 0; j < array[i].length; j++){
                summ = summ + array[i][j]; // error
            }
        }
        return summ; // error
    }

A: Обобщённый метод поможет из двухмерного массива сделать одномерный. Далее для каждого типа массива: Integer[][], Long[][], Double[][] - делаем перегрузку метода, суммирующего его элементы:
public static void main(String[] args) {
    Integer[][] arr1 = {{1, 2}, {3, 4}};
    Long[][] arr2 = {{1L, 2L}, {3L, 4L}};
    Double[][] arr3 = {{1.1, 2.2}, {3.3, 4.4}};

    System.out.println(summingArray(arr1)); // 10
    System.out.println(summingArray(arr2)); // 10
    System.out.println(summingArray(arr3)); // 11.0
}

static int summingArray(Integer[][] arr) {
    return Arrays.stream(flattenArray(arr, Integer[]::new))
            .mapToInt(Integer::intValue).sum();
}

static long summingArray(Long[][] arr) {
    return Arrays.stream(flattenArray(arr, Long[]::new))
            .mapToLong(Long::longValue).sum();
}

static double summingArray(Double[][] arr) {
    return Arrays.stream(flattenArray(arr, Double[]::new))
            .mapToDouble(Double::doubleValue).sum();
}

static <T extends Number> T[] flattenArray(T[][] arr, IntFunction<T[]> function) {
    return Arrays.stream(arr).flatMap(Arrays::stream).toArray(function);
}


text:
Q: Non-separable vectors in tensor product of vector spaces Is it possible to find all the non-separable vectors in a tensor product of $n$ Hilbert spaces? How many are there? Do they live in a specific subspace?
To be more precise, if we have two complex Hilbert spaces $H_1$ and $H_2$ of the same dimension $d$ and we form their tensor product $H=H_1\otimes H_2$, $H$ is itself a vector space, of dimension $2d$ (is that correct?), however in $H$ some vectors can be written as the tensor product of a vector in $H_1$ and a vector in $H_2$ while others cannot.
To illustrate what is meant by "separable/non-separable", let's take $H_1$ and $H_2$ of dimension 2. If the pair ($u_1, u_2$) form a basis of $H_1$ and the pair ($v_1,v_2$) a basis of $H_2$, the general form of the (tensor) product of a vector in $H_1$ and a vector in $H_2$ is, with $(\alpha_1, \alpha_2, \beta_1, \beta_2) \in \mathbb{C}^4$: $$(\alpha_1 u_1 + \alpha_2 u_2)\otimes(\beta_1 v_1 + \beta_2 v_2) = \alpha_1 \beta_1 u_1\otimes v_1 + \alpha_1 \beta_2 u_1\otimes v_2 + \alpha_2\beta_1 u_2\otimes v_1 + \alpha_2\beta_2 u_2\otimes v_2,$$
Now if we consider the following vector in $H$: $$w=u_1\otimes v_1+u_2\otimes v_2,$$
we see that we cannot write it as a (tensor) product of a vector in $H_1$ and a vector in $H_2$, as it leads to contradiction when trying to find values for $\alpha_1, \beta_1, \alpha_2, \beta_2$. We call $w$ "non-separable".


text:
Q: Why high parry chance spells are not working? I made a custom spell that modifies the player's parry chance to 100%. Ingame I got every damage from the mob, none of them was parry. Why is this ? I remember some years ago with TrinityCore I tried to use some of the blizzlike parry increase spell and didn't worked, so I don't really know what is happening here. I would really apprepriate some help.
Thank you !


text:
Q: How to trigger Stencil component function/method from outside Vue instance Is there any possibility to trigger Stencil compontent function from parent Vue instance?
I would like to, for example, run callChild() method in Vue instance, that will trigger doSomething() in Stencil component.
Main, html file with vue code file, which contains stencil component:

      <test-component :rules="[required, passwordRule]" :placeholder="placeholder" :label="label" :value="value" @valueChange="e => onValueChange"></test-component>
      {{value}}
      <button @click="foo()">Test</button>

Stencil component code:
import { h, Component, Element, Event, EventEmitter, State, Watch, Prop, Method } from '@stencil/core';

@Component({
  tag: 'test-component',
  styleUrl: 'test-component.css',
  //shadow: true,
})
export class FormInputBase {
  @Element() el: HTMLElement;
  @Prop() type: string = 'text';
  @Prop() label: string;
  @Prop() rules: Array<Function>;
  @Prop() placeholder: string;
  @Prop({ mutable: true }) value: string;
  @Prop() hidedetails: boolean;
  @Event() valueChange: EventEmitter;

  @State() errorDetails: any;
  @State() showError: boolean = false;

  @Watch('value')
  watchHandler(newValue: string, oldValue: string) {
    console.log('The new value of activated is: ', newValue, 'Old val: ', oldValue);
    console.log(this.required(newValue));
    if (this.required(newValue) != true) {
      this.errorDetails = this.required(newValue);
      this.showError = true;
    } else {
      this.showError = false;
    }

    console.log(this.rules);
  }

  required = v => !!v || 'This field is required';

  @Method()
  async testClick(val) {
    await console.log(val);
  }

  @Method()
  doSomething() {
    //do something
  }

  handleChange(event) {
    const val = event.target.value;
    console.log(val);
    this.value = val;
    this.valueChange.emit(val);
  }
  render() {
    if (this.hidedetails) {
      return (

            {this.label}

              <input placeholder={this.placeholder} value={this.value} onInput={event => this.handleChange(event)}></input>

      );
    } else {
      return (

            {this.label}

              <input placeholder={this.placeholder} value={this.value} onInput={event => this.handleChange(event)}></input>

{this.errorDetails}

              <button onClick={this.testClick}>Kilknij mnie!</button>

      );
    }
  }
}

A: Ok - the answer is simple. You need to use ref. Just add ref tag to element in html:
<test-component ref="form" :rules="[required, passwordRule]" :placeholder="placeholder" :label="label" :value="value" @valueChange="e => onValueChange"></test-component>

And then Vue method should look like:
foo() {
          this.$refs.form.bar();
        },

Where bar() is exactly name of method in Your Stencil component.


text:
Q: Roots of polynomial using sigmma notation (code improvement) and some maths related question Comes from exploring roots of polynomials and using the recurrence relationship of $S_n = \sum \alpha^n$ notation. Like this:
$$
S_2 = \left( \sum \alpha \right)^2 - 2 \sum \alpha \beta
$$
where $\alpha,\beta,\gamma, \delta$ are the roots of the polynomials where necessary.
We can even get

with a few lines of algebra.
Now for higher orders, I get the following:

Using the code to double check:
mysum[n_, m_ : 6] := Times @@@ Subsets[Take[Alphabet[], m], {n}]
Block[
    {m, t0, t1, t2, t3, t4, t5},
    m = 18;
    t0 = (mysum[1, m] // Total)^4;
    t1 = mysum[1, m]^4 // Total;
    t2 = 4*Total[mysum[2, m]]*Total[mysum[1, m]^2];
    t3 = 6*Total[mysum[2, m]^2];
    t4 = 8*Total[mysum[3, m]]*Total[mysum[1, m]];
    t5 = 8*Total[mysum[4, m]];

    t0 - (t1 + t2 + t3 + t4 - t5) // Expand
]

for order 4 and
Block[
    {m, t0, t1, t2, t3, t4, t5, t6, t7},

    m = 6;

    t0 = Total[mysum[1, m]]^5;
    t1 = 1*mysum[1, m]^5 // Total;
    t2 = 5*Total[mysum[2, m]]*Total[mysum[1, m]^3];
    t3 = 10*Total[mysum[2, m]^2]*Total[mysum[1, m]];
    t4 = 15*Flatten[
        {
        (#1^3*#2*#3) & @@@ mysum[3, m],
        (#1*#2^3*#3) & @@@ mysum[3, m],
        (#1*#2*#3^3) & @@@ mysum[3, m]
        }
        ] // Total;
    t5 = 20*Flatten[
            {
            (#1^2*#2^2*#3^1) & @@@ mysum[3, m],
            (#1^2*#2^1*#3^2) & @@@ mysum[3, m],
            (#1^1*#2^2*#3^2) & @@@ mysum[3, m]
            }
            ] // Total;
    t6 = 60*Flatten[
            {
            (#1^2*#2*#3*#4) & @@@ mysum[4, m],
            (#1*#2^2*#3*#4) & @@@ mysum[4, m],
            (#1*#2*#3^2*#4) & @@@ mysum[4, m],
            (#1*#2*#3*#4^2) & @@@ mysum[4, m]
            }
            ] // Total;
    t7 = 120*Total[mysum[5, m]];

    t0 - (t1 + t2 + t3 + t4 + t5 + t6 + t7) // Expand
]

for order 5. I check by by changing m in the code and look at the result to see if it is 0.
To my surprise, I was looking for something with the coefficient to be binomial expansion ?
Is there an easier pattern to this?
How could I improve the code to desmonstrate with higher powers like 6,7,8,ect...
Any specific name for this mathematics?
PS: I know in computation, we really just use recurrence formula in $S_n$ instead of using the $\sum$,

but I want to just explore this...

A: Thanks to @Daniel Lichtblau for his comments. After a bit reseach and I found that ?SymmetricReduction is the command I need.
Something like
SymmetricReduction[(a + b)^3 - (a^3 + b^3), {a, b}]
SymmetricReduction[(a + b + c)^3 - (a^3 + b^3 + c^3), {a, b, c}]
SymmetricReduction[(a + b + c + d)^3 - (a^3 + b^3 + c^3 + d^3), {a, b, c, d}]

would give me exactly what I want.
mysum[x_, y_] :=
    Times @@@ Subsets[Take[{a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t}, y], {x}
]

mygo[npars_, order_] := SymmetricReduction[
    Total[mysum[1, npars]]^order - Total[mysum[1, npars]^order],
    Take[
        {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t},
        npars
    ],
    Take[{s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12}, npars]

] // First;

TableForm[Table[mygo[x, 2], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 3], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 4], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 5], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 6], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 7], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 8], {x, 2, 9}], TableAlignments -> Left]
TableForm[Table[mygo[x, 9], {x, 2, 9}], TableAlignments -> Left]

The above will give me the summation terms in terms of sX.

I can easily check my findings using this
mycheck[npars_, order_] := If[
        npars < order, 0,
        SymmetricPolynomial[order,
            Take[{a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t}, npars]
        ]
    ];

mycheck[2, 1]
mycheck[2, 2]
mycheck[2, 3]

myFinalCheck[npars_, power_, res_] := Module[
    {t0, rules},

    rules = Thread[{s1, s2, s3, s4, s5, s6, s7, s8, s9} ->  Table[mycheck[npars, x], {x, 1, 9}]];

    (* Print[rules//Column]; *)

    Total[mysum[1, npars]]^power - (
        Total[mysum[1, npars]^power]
        +
        Total[{res /. rules}]
    ) // Expand

];

myFinalCheck[2, 3, 3 s1*s2 - 3 s3]
myFinalCheck[3, 3, 3 s1*s2 - 3 s3]
myFinalCheck[4, 3, 3 s1*s2 - 3 s3]
myFinalCheck[5, 3, 3 s1*s2 - 3 s3]
myFinalCheck[6, 3, 3 s1*s2 - 3 s3]

myFinalCheck[#, 7,
    7 s1^5*s2 - 14 s1^3*s2^2 + 7 s1*s2^3 - 7 s1^4*s3 + 21 s1^2*s2*s3 -
    7 s2^2*s3 - 7 s1*s3^2 + 7 s1^3*s4 - 14*s1*s2*s4 + 7 s3*s4 -
    7 s1^2*s5 + 7 s2*s5 + 7 s1*s6 - 7 s7
] & /@ Range[10]

myFinalCheck[#, 8,
    8*s1^6*s2 - 20*s1^4*s2^2 + 16*s1^2*s2^3 - 2*s2^4 - 8*s1^5*s3 +
    32*s1^3*s2*s3 - 24*s1*s2^2*s3 - 12*s1^2*s3^2 + 8*s2*s3^2 +
    8*s1^4*s4 - 24*s1^2*s2*s4 + 8*s2^2*s4 + 16*s1*s3*s4 - 4*s4^2 -
    8*s1^3*s5 + 16*s1*s2*s5 - 8*s3*s5 + 8*s1^2*s6 - 8*s2*s6 -
    8*s1*s7 + 8*s8
] & /@ Range[10]

myFinalCheck[#, 9,
    9*s1^7*s2 - 27*s1^5*s2^2 + 30*s1^3*s2^3 - 9*s1*s2^4 - 9*s1^6*s3 +
    45*s1^4*s2*s3 - 54*s1^2*s2^2*s3 + 9*s2^3*s3 - 18*s1^3*s3^2 +
    27*s1*s2*s3^2 - 3*s3^3 + 9*s1^5*s4 - 36*s1^3*s2*s4 +
    27*s1*s2^2*s4 + 27*s1^2*s3*s4 - 18*s2*s3*s4 - 9*s1*s4^2 -
    9*s1^4*s5 + 27*s1^2*s2*s5 - 9*s2^2*s5 - 18*s1*s3*s5 + 9*s4*s5 +
    9*s1^3*s6 - 18*s1*s2*s6 + 9*s3*s6 - 9*s1^2*s7 + 9*s2*s7 +
    9*s1*s8 - 9*s9
] & /@ Range[10]


text:
Q: C# Serialization and maintainability I really like the ease and flexibility of using XmlSerializer to persist configuration data for my application.  However, I can see potential maintainability issues.
From looking at my class definitions, it is not obvious that the reason certain fields are exposed as properties is for serialization purposes.  Somebody could come along and remove a property (leaving the private field alone) and inadvertently cause issues due to important information no longer being serialized to XML.
I could add comments to explain this, but I'd rather the code spoke for itself.
There exists the [Serializable] attribute (which hints that the class is to be serialized), but this isn't actually required for the XmlSerializer and is therefore unnecessary.
I could write some custom serialization code but then I lose the simplicity of using XmlSerializer.
Is there a way of decorating my code to make it clear which classes and which properties are candidates for XML serialization?


text:
Q: Making One Step Forecast Predictions I'm making a LSTM model and I'm training it on a TSLA data set I found on kaggle. So my question is when I call model.predict does this prediction give me the price of the stock for the next day? And is this a one- step forecast? And when I print the model.predict I get a huge list so I use the numpy argmax function to give me a number. Here is the code:
import tensorflow as tf
from tensorflow.keras.layers import LSTM, Dense, Dropout, Input, GlobalMaxPooling1D
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.optimizers import Adam

df = pd.read_csv('TSLA.csv')

series = df['Close'].values.reshape(-1, 1)

scaler = StandardScaler()
scaler.fit(series[:len(series)//2])
series = scaler.transform(series).flatten()

X = []
Y = []
T = 10
D = 1

for t in range(len(series) - T):

    X.append(series[t:t+T])
    Y.append(series[t+T])

X = np.array(X).reshape(-1, T, D)
Y = np.array(Y)
N = len(X)

print(X.shape, Y.shape)

model = tf.keras.Sequential([
    Input(shape=(T, D)),
    LSTM(50),
    Dense(100, activation='relu'),
    Dropout(0.25),
    Dense(1)
])

model.compile(optimizer=Adam(lr=0.01), loss='mse')
r = model.fit(X[:-N//2], Y[:-N//2], validation_data=(X[-N//2:], Y[-N//2:]), epochs=200)

plt.plot(r.history['loss'])
plt.plot(r.history['val_loss'])
plt.show()

preds = model.predict(X)
outs = preds[:,0]

print(outs)
print(np.argmax(outs))

A: Argmax doesn't make sense here. The 90 values are the 90 predictions for the next day of the training set. When you run this:
preds = model.predict(X)

It gives you the next day value for all 90 data points of your train set. This line:
print(np.argmax(outs))

Makes no sense.
By the way, you can get stock prices with Python, you don't need a CSV.
pip install pandas-datareader

from pandas_datareader import data as wb

ticker=wb.DataReader('TSLA',start='2015-1-1',data_source='yahoo')
print(ticker)

                  High         Low  ...      Volume   Adj Close
Date                                ...
2015-01-02   44.650002   42.652000  ...  23822000.0   43.862000
2015-01-05   43.299999   41.431999  ...  26842500.0   42.018002
2015-01-06   42.840000   40.841999  ...  31309500.0   42.256001
2015-01-07   42.956001   41.956001  ...  14842000.0   42.189999
2015-01-08   42.759998   42.001999  ...  17212500.0   42.124001
                ...         ...  ...         ...         ...
2020-10-13  448.890015  436.600006  ...  34463700.0  446.649994
2020-10-14  465.899994  447.350006  ...  48045400.0  461.299988
2020-10-15  456.570007  442.500000  ...  35672400.0  448.880005
2020-10-16  455.950012  438.850006  ...  32620000.0  439.670013
2020-10-19  447.000000  437.649994  ...   9422697.0  442.840607