text:
Q: Add parameter at onClose in relation Modal Goal:
When you press the button named "yes 1", the value should contain "yes yes" and in the end the console.log should display "test yes yes".
When you press the button named "yes 2", the value should contain "no no" and in the end the console.log should display "test no no".
The display of the value "test yes yes" or "test no no" take place at index.tsx.
The execution or the decision take place at ModalForm.tsx.
Problem:
In technical perspectiv, tried to find a solution by using this code  onClick={props.onClose("yes yes")} but it doesn't work.
How do I solve this case?
Stackblitz:
https://stackblitz.com/edit/react-ts-rpltpq
Thank you!

index.html

<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>

index.tsx
import React, { Component, useState, useEffect } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import { ModalForm } from './ModalForm';

import './style.css';

interface dddd {
  clientid: string | undefined;
  idid: number;
}

const getTest = () => {
  console.log('test');
};

const App = () => {
  const [clientiddd, setClientid] = useState('ddfdf');
  const [idid, setIdid] = useState(0);

  return (

      <button
        data-bs-toggle="modal"
        data-bs-target="#myModalll"
        className={'btn btn-outline-dark'}
      >
        {'data'}
      </button>

      <ModalForm clientid={clientiddd} onClose={getTest} />

  );
};

render(<App />, document.getElementById('root'));

ModalForm.tsx
import React, { Component } from 'react';

interface ModalProps {
  clientid: string | undefined;
  onClose: () => void;
}

export const ModalForm = (props: ModalProps) => {
  return (

T

            <button
              type="button"
              className="btn-close btn-close-black"
              data-bs-dismiss="modal"
              onClick={props.onClose}
            ></button>

            TITLE:

            <button
              type="button"
              data-bs-dismiss="modal"
              onClick={props.onClose}
            >
              yes 1
            </button>
            <button
              type="button"
              data-bs-dismiss="modal"
              onClick={props.onClose}
            >
              yes 2
            </button>

  );
};

A: It's somewhat hard to understand your question, but let me try.
onClick={props.onClose('yes yes')}

What this code does is that it calls props.onClick with yes yes as an argument and assigns the returned value as the onClick listener.
Assume the props.onClose is this:
function onClose() {
  console.log('test')
}

What it does here is that it calls this function (it logs test to the console) but since this function is not returning anything, it passes undefined as the onClick here.
If instead your function was this:
function onClose(result) {
  return function () {
    console.log('test', result)
  }
}

Now it would call props.onClose with yes yes and it would return a function. This anonymous function would be passed as the onClick event listener and when you click, it would call that so there would be test yes yes logged only after clicking.
You can as well do it differently, keep your onClose function as it was but introduce result:
function onClose(result) {
  console.log('test', result)
}

but now you have to pass this function instead of calling it:
onClick={() => props.onClose('yes yes')}

As you can see, there will always be one anonymous function somewhere in there, it's just a question of where that function is and what is called when. Hope this explanation helps.

A: https://stackblitz.com/edit/react-ts-nw6upt?file=index.html

index.html

<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>

index.tsx
import React, { Component, useState, useEffect } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import { ModalForm } from './ModalForm';

interface dddd {
  clientid: string | undefined;
  idid: number;
}

const getTest = (result: string) => {
  console.log('testff ' + result);
};

const App = () => {
  const [clientiddd, setClientid] = useState('ddfdf');
  const [idid, setIdid] = useState(0);

  return (

      <button
        data-bs-toggle="modal"
        data-bs-target="#myModalll"
        className={'btn btn-outline-dark'}
      >
        {'data'}
      </button>

      <ModalForm clientid={clientiddd} onClose={getTest} />

  );
};

render(<App />, document.getElementById('root'));

ModalForm.tsx
import React, { Component } from 'react';

interface ModalProps {
  clientid: string | undefined;
  onClose: (result: string) => void;
}

export const ModalForm = (props: ModalProps) => {
  return (

T

            <button
              type="button"
              className="btn-close btn-close-black"
              data-bs-dismiss="modal"
              onClick={() => props.onClose('ccc')}
            ></button>

            TITLE:

            <button
              type="button"
              data-bs-dismiss="modal"
              onClick={() => props.onClose('aaa')}
            >
              yes 1
            </button>
            <button
              type="button"
              data-bs-dismiss="modal"
              onClick={() => props.onClose('bbb')}
            >
              yes 2
            </button>

  );
};


text:
Q: c#: Looking for data structure similar to Dictionary, that doesn't raise an error when indexing with a non-existing key I like using Dictionary, but checking every time if some key exists before indexing it is a nuisance. Is there any built-in data structure in c#, that would return null when a key doesn't exist, instead of raising an error?
If there is none, is there some custom class for that? I would like to avoid creating my own class and I'm not sure if this behavior is even possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add custom fields to category pages? I have a website about HTML5 games, built with some PHP script.
One of its plugins you can create custom fields for each category page.
I created different custom fields (description text) for each category page.
But when I want to show these fields on category pages, unfortunately each category page shows all custom fields of all categories.
Here is a code I added to category.php file:
<?php

    $categories = get_all_categories();
    foreach ($categories as $category){
        $category_info = $category->get_field('category_info');

        if(is_null($category_info)){
            $category_info = 'no info';
        }
        echo $category_info;
    }
?>

I want to show only 1 custom field (which is particular to each category) in every category page.
Here is get_all_categories() default function of the script:
function get_all_categories(){
    $data = Category::getList();
    return $data['results'];
}

Thanks


text:
Q: Easy pie chart is not Working in Flask page I'm trying to load easy pie chart for my HTML+Flask page and I received only the label without circle.
{% block head %}

<title>Home</title>
<link rel="stylesheet"  href="{{ url_for('static', filename='css/index.css') }}"/>

{% endblock %}
{% block body %}

75%

{% endblock %}

Can anyone help me what is wrong with this code and how to fix this.


text:
Q: Understanding relation between energy use, watts and amps I'm looking into air conditioners and I've been unable to fully understand the relation between watts, amps and the energy ratings (in this case, the one used in the United States, the yellow Energy Guide label).
Both are 115 V.
Air conditioner 1: 8000 BTU, it is listed as 660 W cooling power, 6.2 A cooling current. The yellow label Energy Guide lists yearly costs at $65. The energy efficiency ratio is 12.
Air conditioner 2: 9500 BTU, it is listed as 920 W cooling power, 11.5 A cooling current. The yellow label Energy Guide lists yearly costs at $50. The energy efficiency ratio is 13.8.
Questions:

*

*Why in both air conditioners the amps is not equal to watts divided by 115 volts? 660 / 115 = 5.74 A and 920 / 115 = 8 A.

*The air conditioner 1 clearly uses less energy than air conditioner 2. However air conditioner 2 is listed as cheaper in yearly costs. Maybe it has to do with the way it cools the room, using less energy over time? But then why watts are higher, if the energy consumption is lower?
Thanks for helping me understanding this!

A: The Energy Guide numbers include a range of assumptions about room size, annual hours of operation, and cooling load. The manufacturers have to include values for standby power consumption as well. All of this means that while watts, amps, and volts are fundamentally related, the values reported on the label aren't. They are the result of specific testing requirements and reporting criteria that manufacturers must adhere to.
What you can assume is that in a similar application (such as the same room in your house) air conditioner (2) will cost you about 30% less to operate annually than air conditioner (1):
($65 - $50) / $50 = 30%

If you want to get into the details, you can read the Code of Federal Regulations -- Title 10 Energy -- Chapter II Department of Energy -- Subchapter D Energy Conservation -- Part 430 Energy Conservation Program for Consumer Products -- Subpart B Test Procedures -- Section 23 Test procedures for the measurement of energy and water consumption.
Here you'll find that assumed annual operation is 750 hours. More specifics are found in Appendix F to Subpart B of Part 430—Uniform Test Method for Measuring the Energy Consumption of Room Air Conditioners, which references  ANSI/AHAM RAC-1-2015
Room Air Conditioners, the testing standard that manufacturers need to follow when developing the numbers that go on the label.


text:
Q: target first array, first value in array of arrays I have an array of arrays, how do I target the first array, first value?
questions: [
              [
                'Purchase only', 'Sale and purchase',
                'Sale only', 'Remortgage'
              ],
              [
                'Leasehold', 'Freehold'
              ],
              [
                'Yes', 'No'
              ]
            ]

so I can do this:
    if (this.quoteResults[1] == this.questions[0][0])
DOESNT WORK

Instead of this:
    if (this.quoteResults[1] ===  'Purchase only')
THIS WORKS BUT I WANT TO USE ARRAY INDEX INSTEAD

A: Your issue arises when you use 'this'. You are able to access this.quoteResults[1] but you are not able to access 'questions'. Make sure both quoteResults and questions are in your scope when you use 'this'. Try printing questions[0][0] inside the function where you have your if statement. Because questions[0][0] is the correct way of accessing it so that is not the issue.
Also, we do not know what quoteResults[1] contains, what it's data type is.
var questions = [
          [
            'Purchase only', 'Sale and purchase',
            'Sale only', 'Remortgage'
          ],
          [
            'Leasehold', 'Freehold'
          ],
          [
            'Yes', 'No'
          ]
        ]
      console.log(questions[0][0]);


text:
Q: Bootstrap datetimepicker - how to use the text "today" for the today button? I have seen some datepicker versions where the "today" button/bar under the calendar shows up as "Today". Mine has the calendar icon.
I don't want to reload a different version, because what I have is actually working, but I'm worried about end-users who won't necessarily know/assume that button means "today."
In the .js for datetimepicker, it selects the glyphicon calendar for the "today" button. If I disable that specific setting, there is nothing that shows up in the bar below the calendar.
        icons: {
        time: "glyphicon glyphicon-time",
        date: "glyphicon glyphicon-calendar",
        up: "glyphicon glyphicon-chevron-up",
        down: "glyphicon glyphicon-chevron-down",
        previous: "glyphicon glyphicon-chevron-left",
        next: "glyphicon glyphicon-chevron-right",
        today: "glyphicon glyphicon-calendar",
        clear: "glyphicon glyphicon-trash",
        close: "glyphicon glyphicon-remove"
    },

What switch, setting, or icon can I use to make the button display the word "Today," instead?

A: Okay, I figured it out.
I created a png image of a blue rectange with a white centered "Today."  I went into the datetimepicker.css and created a class that refers to the image -
.calendar-today-button {
background-image: url(../../images/todaybtn.png);
background-repeat: no-repeat;
background-position: center;

}
I found the function in the JavaScript code where it calls on the icon classes when constructing the buttons/controls for the "Today" button -
F = function() {
            var b = [];
            return d.showTodayButton && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "today",
                title: d.tooltips.today
            }).append(a("<span>").addClass("d.icons.time")))), !d.sideBySide && B() && A() && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "togglePicker",
                title: d.tooltips.selectTime
            }).append(a("<span>").addClass(d.icons.time)))), d.showClear && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "clear",
                title: d.tooltips.clear
            }).append(a("<span>").addClass(d.icons.clear)))), d.showClose && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "close",
                title: d.tooltips.close
            }).append(a("<span>").addClass(d.icons.close)))), a("<table>").addClass("table-condensed").append(a("<tbody>").append(a("<tr>").append(b)))
        },

I changed the calendar icon to my calendar button class -
            F = function() {
            var b = [];
            return d.showTodayButton && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "today",
                title: d.tooltips.today
            }).append(a("<span>").addClass("calendar-today-button")))), !d.sideBySide && B() && A() && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "togglePicker",
                title: d.tooltips.selectTime
            }).append(a("<span>").addClass(d.icons.time)))), d.showClear && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "clear",
                title: d.tooltips.clear
            }).append(a("<span>").addClass(d.icons.clear)))), d.showClose && b.push(a("<td>").append(a("<a>").attr({
                "data-action": "close",
                title: d.tooltips.close
            }).append(a("<span>").addClass(d.icons.close)))), a("<table>").addClass("table-condensed").append(a("<tbody>").append(a("<tr>").append(b)))
        },


text:
Q: Can C# style object initialization be used in Java? In C# it's possible to write:
MyClass obj = new MyClass()
{
    field1 = "hello",
    field2 = "world",
    field3 = new MyOtherClass()
    {
        etc....
    }
}

I can see that array initialization can be done in a similar way but can something similar to the above be done in Java too, and if so, what's the syntax?

A: That initialization syntax is not present in Java.
A similar approach is to use double brace initialization, where you create an anonymous inner sub class with an initializer block:
MyClass obj = new MyClass() {{
  // in Java these would be more like this: setFieldX(value);
  field1 = "hello";
  field2 = "world";
  field3 = new MyOtherClass() ...
}};

Be aware though, that you're actually creating a subclass.
Another approach is to create a builder for MyClass, and have code like this:
MyClass obj = new MyClassBuilder().
  withField1("hello").
  withField2("world").
  withField3(new MyOtherClass()).
  build();

A: Java does not have the capability built in to instantiate an object using the shorter syntax. The C# compiler handles this and separates out the property setters in the IL. Until the Java langauge devs decide this is important, you will not be able to take this shortcut.

A: Just create constructors for initialization.
MyClass obj = new MyClass()
{
    field1 = "hello",
    field2 = "world",
    field3 = new MyOtherClass()
    {
        etc....
    }

    public MyClass()
    {
        initialize();
    }

    public MyClass(String field1)
    {
        this.field1 = field1;
        this();
    }

    public MyClass(String field, Boolean isField1)
    {
        if (isField1)
            this( field );
        else
            this.field2 = field;

        this();
    }

    public MyClass(String field1, String field2)
    {
        this.field2 = field2;
        this(field1);
    }

    public MyClass(MyOtherClass field3)
    {
        this.field3 = field3;
    }

    public MyClass(String field1, String field2, MyOtherClass field3)
    {
        this(field3);
        this(field1, field2);
    }

    private void initialize(){
        // Do any class bootstrapping here.
    }
}

// Then you have several ways to create an object instance, with initialization
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass( "Field 1 Value" );
MyClass myClass3 = new MyClass( "Field 1 Value", true );
MyClass myClass4 = new MyClass( "Field 2 Value", false );
MyClass myClass5 = new MyClass( "Field 1 Value", "Field 2 Value" );
MyClass myClass6 = new MyClass( "Field 1 Value", "Field 2 Value", new MyOtherClass() );
MyClass myClass7 = new MyClass( new MyOtherClass() );

A: Yes you can do that, you just need to add the types before the field1, field2 etc other than that what you have should work. Its known as an anonymous class in Java.


text:
Q: Does excel retain RLS when a saved copy of `analyze in excel` report is shared with another user? Link: https://learn.microsoft.com/en-us/power-bi/collaborate-share/service-analyze-in-excel#save-and-share-your-new-workbook

When a user opens the workbook that you've shared your workbook with
them, they see your PivotTables and data as they were when you last
saved the workbook.

Does RLS not apply when an excel file is shared with another user?
For exmaple: suppose I have RLS to restrict myself only to see country A. But if person having access to country B opens the analyze in excel report and saves this and shares it to me, then will I see country B even though I don't have access to country B?
Ofcourse if I refresh it will only show me country A based on my RLS.

A: You share a current snapshot of excel so yes, you can see Country B, because there is no way to validated RLS rules without refreshing (without sending a request to the powerbi Engine);  Think about this as saving screenshot and sharing this screenshot.

A: I would recommend if the data visible in the Analyze in Excel PivotTable is sensitive you should not share this without first Clearing the PivotTable Cache. This is a feature of the free OLAP PivotTable Extensions add-in for Excel.
It is true that upon refresh (with or without first clearing the PivotTable cache) that the user will have to authenticate with Power BI and RLS should properly limit the data visible in the PivotTable after refresh. The question is the initial data visible in the sheet which a user can see without authenticating to Power BI.


text:
Q: tensorflow import error in python 2.7.6 I have installed tensor flow from tensorflow website. While trying to import tensor flow its showing following error
>>>import tensorflow as tf

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line  24, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 75, in <module>
from tensorflow.core.framework.graph_pb2 import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
from google.protobuf import descriptor as _descriptor
File "/usr/local/lib/python2.7/dist-packages/google/protobuf/__init__.py",   line 37, in <module>
__import__('pkg_resources').declare_namespace(__name__)
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py",   line 36, in <module>
import email.parser
File "/usr/lib/python2.7/email/parser.py", line 12, in <module>
from email.feedparser import FeedParser
File "/usr/lib/python2.7/email/feedparser.py", line 27, in <module>
from email import message
File "/usr/lib/python2.7/email/message.py", line 16, in <module>
import email.charset
File "/usr/lib/python2.7/email/charset.py", line 13, in <module>
import email.base64mime
File "/usr/lib/python2.7/email/base64mime.py", line 40, in <module>
from email.utils import fix_eols
File "/usr/lib/python2.7/email/utils.py", line 28, in <module>
import socket
File "/home/tamarind/socket.py", line 5, in <module>
This module provides socket operations and some related functions.
TypeError: 'module' object is not callable

I think its problem with socket please suggest. Please suggest.

A: It looks like /home/tamarind/socket.py is taking precedence over the python socket module. Just rename/remove that (or import TensorFlow from a different directory) and it should work. You may need to remove socket.pyc too.


text:
Q: How to enforce compiler generic code using e.g. clang warnings?? I've been developing a support library for various c++17 projects for a few years.
In order to minimize problems and maximize portability I have been using strict standards compliant c++17 and no extensions as well as compiling with both default GCC and clang on Ubuntu 20.04 along with wall wextra etc fixing all.
Recently I tried to compile to code using msvs19 but the sheer number of outright compilation errors stunned me.
Is there any way to configure clang to warn on features that won't compile in msvs or aren't supported by msvs?
Like a way to explicitly warn on all not yet implemented standard features or inconsistently implemented standard festures. The lib provides alot of metatemplate stuff, like for(auto& [a,b,c,...]:zip(as,bs,..) which hits inconsistencies or outright compiler crashes when implemented straightforwardly, or differ between compilers. Making maintainable a pain as I lack dedicated build VM servers.
Also what is the best way to get float128 i.e. standards compliant long double in msvs? Does not have to be that long double is float128, just that it exists?


text:
Q: Error while Trying to draw a Recursion Tree? Here is the code:
\documentclass[tikz,border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree={
   draw,
   align=center
}
[TowersOfHanoi\left 4, 1, 3, 2\right
[TowersOfHanoi\left 3, 1, 2, 3\right
  [TowersOfHanoi\left 2, 1, 3, 2\right
    [TowersOfHanoi\left 1, 1, 2, 3\right]
    [TowersOfHanoi\left 1, 2, 3, 1\right]
  ]
  [TowersOfHanoi\left 2, 3, 2, 1\right
    [TowersOfHanoi\left 1, 3, 1, 2\right]
    [TowersOfHanoi\left 1, 1, 2, 3\right]
  ]
]
[TowersOfHanoi\left 3, 2, 3, 1\right
  [TowersOfHanoi\left 2, 2, 1, 3\right
    [TowersOfHanoi\left 1, 2, 3, 1\right]
    [TowersOfHanoi\left 1 ,3, 1, 2\right]
  ]
  [TowersOfHanoi\left 2, 1, 3, 2\right
    [TowersOfHanoi\left 1, 1, 2, 3\right]
    [TowersOfHanoi\left 1, 2, 3, 1\right]
  ]
 ]
]
\end{forest}
\end{document}

Here is the error message:

! Missing \endcsname inserted.
  to be read again
                     \right
  l.32 \end{forest}
?

What am I doing wrong?

Note: The above code is a slightly modified version of this benchmark code which reproduces the drawing.

A: First of all, the commas. A comma means that the text of the node is ended, and options pertaining to it follows. To have commas in the node text, wrap it in braces.
Second, \left/\right. They require math mode, and they also require a delimiter to follow them, which you've forgotten. I'd remove them altogether though, and insert just (/) instead. \left .. \right isn't needed when you only have numbers between them like that.
As noted in a comment below, align=center doesn't really do much useful here, so unless you're planning to, for example, add linebreaks, it can be removed.
\documentclass[tikz,border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree={
   draw
}
[{TowersOfHanoi(4, 1, 3, 2)}
[{TowersOfHanoi(3, 1, 2, 3)}
  [{TowersOfHanoi(2, 1, 3, 2)}
    [{TowersOfHanoi(1, 1, 2, 3)}]
    [{TowersOfHanoi(1, 2, 3, 1)}]
  ]
  [{TowersOfHanoi(2, 3, 2, 1)}
    [{TowersOfHanoi(1, 3, 1, 2)}]
    [{TowersOfHanoi(1, 1, 2, 3)}]
  ]
]
[{TowersOfHanoi(3, 2, 3, 1)}
  [{TowersOfHanoi(2, 2, 1, 3)}
    [{TowersOfHanoi(1, 2, 3, 1)}]
    [{TowersOfHanoi(1 ,3, 1, 2)}]
  ]
  [{TowersOfHanoi(2, 1, 2, 2)}
    [{TowersOfHanoi(1, 1, 2, 3)}]
    [{TowersOfHanoi(1, 2, 3, 1)}]
  ]
 ]
]
\end{forest}
\end{document}

That said, your tree becomes very wide when you write TowersOfHanoi in every node. Perhaps you could consider abbreviating it to ToH, or leaving it out altogether.
\documentclass[tikz,border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree={
   draw,
}
[{ToH(4, 1, 3, 2)},label={above:ToH = TowersOfHanoi}
[{ToH(3, 1, 2, 3)}
  [{ToH(2, 1, 3, 2)}
    [{ToH(1, 1, 2, 3)}]
    [{ToH(1, 2, 3, 1)}]
  ]
  [{ToH(2, 3, 2, 1)}
    [{ToH(1, 3, 1, 2)}]
    [{ToH(1, 1, 2, 3)}]
  ]
]
[{ToH(3, 2, 3,1)}
  [{ToH(2, 2, 1, 3)}
    [{ToH(1, 2, 3, 1)}]
    [{ToH(1, 3, 1, 2)}]
  ]
  [{ToH(2, 1, 2, 2)}
    [{ToH(1, 1, 2, 3)}]
    [{ToH(1, 2, 3, 1)}]
  ]
 ]
]
\end{forest}

\begin{forest}
for tree={
   draw,
}
[{(4, 1, 3, 2)},label={above:Arguments to TowersOfHanoi}
[{(3, 1, 2, 3)}
  [{(2, 1, 3, 2)}
    [{(1, 1, 2, 3)}]
    [{(1, 2, 3, 1)}]
  ]
  [{(2, 3, 2, 1)}
    [{(1, 3, 1, 2)}]
    [{(1, 1, 2, 3)}]
  ]
]
[{(3, 2, 3,1)}
  [{(2, 2, 1, 3)}
    [{(1, 2, 3, 1)}]
    [{(1, 3, 1, 2)}]
  ]
  [{(2, 1, 2, 2)}
    [{(1, 1, 2, 3)}]
    [{(1, 2, 3, 1)}]
  ]
 ]
]
\end{forest}
\end{document}


text:
Q: Unable to use beeline -f filename I am unable to run
beeline -f file_queries.hql

Error:
$ beeline -f edip_validations_hql.hql
beeline> {My Query}
No current connection

Note: I am on Kerberos so I have done kinit. Usually for beeline to work I have to do a
 !connect jdbc:hive2://XX.xxxx.xx.org:10000/default;principal=hive/somedomain.org@MYXXX-DEV.XX.ORG

However I am not clear how this would work. Any pointers would help.

A: I just found out one way to run File in Hive Beeline.
Just Go to the Hive beeline
//use !run to run script File
beeline> !run ///C:/ScriptFile

Above Method surely helpful to run file beeline after connect to the hive server.

A: All -
I found out how to do this.
 beeline -u 'jdbc:hive2://server.domain.<>.com:10000/default;principal=hive/server.domain.com@SERVER.DOMAIN.COM' -f filename.hql

A: You should be able to add that connect string to your .hql file prior to the query.  But I have not seen a way to pass a keytab in the connect string and that generic hive principal will ask for a user/password.  For now, I'm still using hive -f which works with my existing kinit.  Hope you find another solution since for now beeline -f is useless to me on a secure cluster.


text:
Q: Why I can't desctructure value from a target in onChange event? I am trying to desctructure in 1 time my value from my element, but I have to do it in a separated line.. That's not blocking, but really annoying.
What I want to do :
    const onChangeValue = ({ target: value}) => {
        onChange({ attribute, indexValue, value });
    };

What I need to do :
const onChangeValue = ({ target }) => {
        const { value } = target;
        onChange({ attribute, indexValue, value });
    };

Anys ideas ? I'm working with React (CRA)
I hope I won't make a question that already have been asked.. cause I search don't find anything.

A: You're 2 snippets aren't equivalent, hence 1 works while the other doesn't. The equivalent of you're second example using parameter destructuring would be
const onChangeValue = ({ target: {value}) => {
        onChange({ attribute, indexValue, value });
    };

Your first snippet (without the {} around value is renaming target to value, whereas the curly braces in my snippet specify that value is a property in target, which is itself a property in the argument.
To clarify, given an argument named arg,

*

*your 1st snippet accesses arg.target and assigns it to value.

*your 2nd snippet accesses arg.target, assigns it to target, then assigns target.value to value.

A: If you don't want to change the variable name you don't need to do this.
const onChangeValue = ({ target }) => {
    onChange({ attribute, indexValue, target });
};

Will work, and you'll end up with the object:
onChangeValue = {
    attribute: someValue,  // same value as 'attribute'
    indexValue: someValue, // same value as 'indexValue'
    target: someValue      // same value as 'target'
}

If you want to change the name, you can do that without the new variable as well:
const onChangeValue = ({ target }) => {
    onChange({ attribute, indexValue, value: target.value });
};

In this vase target will evaluate to it's value, and you can use a custom key name ("value", in this case), giving you:
onChangeValue = {
    attribute: someValue,  // same value as 'attribute'
    indexValue: someValue, // same value as 'indexValue'
    value: target.value    // same value as 'target.value' with key/name 'value'
}


text:
Q: Merge char* arrays to uint16_t I'm trying to merge a char*-array into a uint16_t. This is my code so far:
char* arr = new char[2]{0};
arr[0] = 0x0; // Binary: 00000000
arr[1] = 0xBE; // Binary: 10111110

uint16_t merged = (arr[0] << 8) + arr[1];
cout << merged << " As Bitset: " << bitset<16>(merged) << endl;

I was expecting merged to be 0xBE, or in binary 00000000 10111110.
But the output of the application is:
65470 As Bitset: 1111111110111110

In the following descriptions I'm reading bits from left to right.
So arr[1] is at the right position, which is the last 8 bits.
The first 8 bits however are set to 1, which they should not be.
Also, if I change the values to
arr[0] = 0x1; // Binary: 00000001
arr[1] = 0xBE; // Binary: 10111110

The output is:
0000000010111110
Again, arr[1] is at the right position. But now the first 8 bits are 0, whereas the last on of the first 8 should be 1.
Basically what I wan't to do is append arr[1] to arr[0] and interpret the new number as whole.

A: Perhaps char is signed type in your case, and you are left-shifting 0xBE vhich is interpreted as signed negative value (-66 in a likely case of two's complement).
It is undefined behavior according to the standard. In practice it is often results in extending the sign bit, hence leading ones.

3.9.1 Fundamental types....
It is implementationdefined
  whether a char object can hold negative values.

5.8 Shift operators....
The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned
  type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable
  in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1×2E2 is representable
  in the corresponding unsigned type of the result type, then that value, converted to the result type, is the
  resulting value; otherwise, the behavior is undefined.

A: You need to assign to the wider type before shifting, otherwise you're shifting away† your high bits before they ever even hit the only variable here that's big enough to hold them.
uint16_t merged = arr[0];
merged <<= 8;
merged += arr[1];

Or, arguably:
const uint16_t merged = ((uint16_t)arr[0] << 8) + arr[1];

You also may want to consider converting through unsigned char first to avoid oddities with the high bit set. Try out a few different values in your unit test suite and see what happens.
† Well, your program has undefined behaviour from this out-of-range shift, so who knows what might happen!


text:
Q: error during Haar Training with TBB using traincascade.exe I have about 931 cropped positive samples and 1162 negative samples(non object of interest). The cropped images have a resolution of 54x12 and are placed in a folder. The .txt file containing the positive samples looks something like this : picture1.bmp 1 0 0 54 12 .  I have a .txt file for negative imagesthat contains only name of negative images like Noneye001.bmp.
Command Used:
1.For .vec file generation
C:\Opencv2.4.3\opencv\build\bin\Debug\opencv_createsamplesd.exe -info positive/info.txt -num 931 -vec data/vector.vec -maxxangle 0.6 -maxyangle 0 -maxzangle 0.3 -maxidev 100 -bgcolor 0 -bgthresh 0 -w 54 -h 12

2.For Haartraining
C:\Opencv2.4.3\opencv\build\bin\Debug\opencv_traincascaded.exe -data data/cascade -vec data/vector.vec -bg negative/infofile.txt -numPos 931 -numNeg 1162 -numStages 20 -precalcValBufSize 256 -precalcIdxBufSize 256 -featureType HAAR -mode ALL -w 54 -h 12

I getting following error
PARAMETERS:
cascadeDirName: data/cascade
vecFileName: data/vector.vec
bgFileName: negative/infofile.txt
numPos: 931
numNeg: 1162
numStages: 20
precalcValBufSize[Mb] : 256
precalcIdxBufSize[Mb] : 256
stageType: BOOST
featureType: HAAR
sampleWidth: 54
sampleHeight: 12
boostType: GAB
minHitRate: 0.995
maxFalseAlarmRate: 0.5
weightTrimRate: 0.95
maxDepth: 1
maxWeakCount: 100
mode: ALL

===== TRAINING 0-stage =====
<BEGIN
POS count : consumed   931 : 931
NEG count : acceptanceRatio    1162 : 1
Precalculation time: 41.787
+----+---------+---------+
|  N |    HR   |    FA   |
+----+---------+---------+
|   1|        1|        1|
+----+---------+---------+
|   2|        1|        1|
+----+---------+---------+
|   3| 0.996778| 0.300344|
+----+---------+---------+
END>

===== TRAINING 1-stage =====
<BEGIN
OpenCV Error: Bad argument (Can not get new positive sample. The most possible r
eason is insufficient count of samples in given vec-file.
) in unknown function, file ..\..\..\apps\traincascade\imagestorage.cpp, line 15
9

I tried increasing and decreasing no. of negative samples but it didn't help.
Please help.......
Thanks in advance.

A: This is because you have 931 positive images and are trying to train 931 for the positive stage.
You need to reduce this number as on each training stage for every "Mis classifcation" it will try and get another image.
Turn this down to 800 and see how you get on, I imagine it wont fail.
If you need some more info there is an OpenCVAnswers question on it Here

A: opencv_createsamples has  a -num parameter that sets the number of positive samples (it doesn't simply read the number of lines in the positive sample file).  The default , if -num is not set, is 1000 samples.  This is why the opencv_traincascade is failing near 1000 samples, due to  there being only 1000 positive examples.
For harder problems you may need more than 1000 samples and thus will need to set the -num parameter.


text:
Q: Electron-builder NSIS, embedding other installers I have created a little electron program for one of my friends, it is a patcher for a private metin2 server of some sort. The game itself is really old so it requires a few redisturables to be installed.
[dxwebsetup0411 / dotNetFx35setup / vcredist_x86 ( i believe its a 2013 version) ]
I want to include them as an option at the end of the install (or even before it, doesn't really matter).
I have found a few examples how to do so but they are all for Standalone NSIS installers and when i try to include that script ( in the build/installer.nsh file ), the build process crashes, presumably because its not the main build script therefor adding Sections is prohibited (?).
Im really new to NSIS scripts and NSIS overall.
So far i only figured out how to put checkboxes and labels and so on in, with the help of nsDialogs, but as i looked at its documentation, it seemed that there are no option where i could do this.
Any help would be greatly appreciated.
EDIT :
My script currently is almost empty, I only changed the default directory, but anyway here is that:
!macro preInit
  SetRegView 64
  WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Decay2"
  WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Decay2"
  SetRegView 32
  WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Decay2"
  WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "C:\Decay2"
!macroend

Everything i know about electron-builder's NSIS main script and this included script is here :

*

*Custom Script Example

*NSIS- Electron Builder

A: It is definitely possible to embed other installers and execute them. See this example on SO:
Embedding other installers using NSIS
or these official NSIS tutorials/guides: https://nsis.sourceforge.io/Embedding_other_installers
Please post your script and build file(s) if you have some issue with your script and you expect specific answer.


text: Q: Overwrite a specific memory address in android So im wondering if it is possible to overwrite a specific address several times, kind of like formatting so that nothing can be recovered from that location. As in a multiple pass wipe, where the first pass all 1's are written and then a second with all 0's. But only where a specific file is/was.


text:
Q: UTF-8 is encoding not working in PHP 8 encoding is not working when i am fetching data from mysql table i have some special characters in database unable to fetch some cities with special characters like Østfold city and Ærø so when i type ostfold its not fetching Østfold city from database. while i am perfectly getting Šiauliai and Çorum from db when i write sia and cor respectively.
I have a city table i am getting cities from this table using jquery autocomplete ajax so when I type first three letters it shows me list of related letters I am working in CodeIgniter framwork.
my settings of CodeIgniter database.php :-
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';

My database table city's column setting is :-
city_name(column name)  varchar(100)    utf8_general_ci(Collation)

Please help me anything else i have to change for this why i am unable to get cities starting with this characters like Ø and Æ.

A: try this code i hope this will resolved your problem.
file_exists(mb_convert_encoding("file_å.txt", "UTF-8"));

A: The collation table does not list Æ to be equal to A, neither does it list Ø to be equal to O.
You don't have an encoding problem (otherwise Çorum = corum wouldn't work), but instead an expectations problem. You expected them to be equal. By the definition of the collation table, they aren't.

A: See Reference
Ø = O for only one collation:  utf8_unicode_520_ci; most treat it like a letter between O and P.  A few collate it after Z.
Æ is a different matter.  It collates the same as the two letters AE in utf8_unicode_520_ci and at least one other collation.  Otherwise it is between A and B or after Z.
Ç is yet another matter.  It is equal to C for all collations except utf8_turkish_ci, in which case it is a letter between C and D.
Š = S for many collations; between S and T for some.
Bottom line:  Use utf8_unicode_520_ci for the column and the connection; type Æ as AE.


text:
Q: Can you put JFrames inside Full Screen Exclusive Mode? To be honest, I didn't quite know how to express my question in the title. So if someone has a clearer idea of what i'm trying to ask, then please be so kind as to edit it, for the greater good of mankind.
I have the following code:
public class Main {
  public static void main(String[] args) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();

    JFrame frame = new JFrame();
    Window window = new Window(frame);

    JButton btn = new JButton("Quit");
    window.add(btn);

    if(gd.isFullScreenSupported())
        gd.setFullScreenWindow(window);

    btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            gd.setFullScreenWindow(null);
        }
    });
}

}
What I want to do is make a library system, illustrated in full screen mode. Inside the full screen mode, there should be simple frame windows with text fields in them and so on... No heavy 2D/3D graphics required here...
My problem is, the quit button is resized to fit the entire screen. I've tried to use setBounds, setSize, etc, on the frame, window and even button... But it doesn't seem to let me be able to center the button in the middle.
So my question: Is it possible to make JFrame application windows inside a JFrame application window which is set to full screen exclusive mode? Or is it only possible to use full screen exclusive mode together with 2D/3D methods like drawing?
Note: The only thing I intend to use full screen mode for is to set it to a black background, and have a Jframe window ontop of this black background in the center of the application. It is to give the illusion that the application is actually a system.
Thank you.
P.S. please note that the quit button was merely for my own testing purposes. It won't be part of the actual system, so my question does not revolve around how to resize this particular quit button.

A: Fullscreen Exclusive Mode is not meant to have Swing components inside. It is meant as a high performance way to draw graphics in Java (and can benefit as much as possible of underlaying hardware if done right).
What you want to do could be done by using an undecorated JDesktopPane and maximize it over the dimensions of the screen. Then proceed with using a JInternalFrame to have a JFrame like window inside that JDesktopPane.
I've included links to the respective API sections, they should get you started.

A: I think that what you are after is an MDI Application. If that is what you are after you could take a look here.

A: Your problem is that you do not use layout manager correctly.
Learn about layout managers - the modules that put and size/resize the visual components on screen. Then decide how do you want your button to look like and then decide which layout manager to use. It will do its job.

A: You know what i also had the exact same problem and the only thing i know from my experience is that you can use jinternal frame and set its property undecorated to true then add your custom title bar according to your requirement.


text:
Q: What makes an SQL query optimiser decide between a nested loop and a hash join In general what makes an SQL query optimiser decide between a nested loop and a hash join.

A: NESTED LOOPS are good if the condition inside the loop is sargable, that is index can be used to limit the number of records.
For a query like this:
SELECT  *
FROM    a
JOIN    b
ON      b.b1 = a.a1
WHERE   a.a2 = @myvar

, with a leading, each record from a will be taken and all corresponding records in b should be found.
If b.b1 is indexed and has high cardinality, then NESTED LOOP will be a preferred way.
In SQL Server, it is also the only way to execute non-equijoins (something other than = condition in the ON clause)
HASH JOIN is the fastest method if all (or almost all) records should be parsed.
It takes all records from b, builds a hash table over them, then takes all records from a and uses the value of the join column as a key to look up the hash table.

*

*NESTED LOOPS takes this time:
Na * (Nb / C) * R,
where Na and Nb are the numbers of records in a and b, C is the index cardinality, and R is constant time required for the row lookup (1 is all fields in SELECT, WHERE and ORDER BY clauses are covered by the index, about 10 if they are not)

*HASH JOIN takes this time:
Na + (Nb * H)
, where H is sum of constants required to build and lookup the hash table (per record). They are programmed into the engine.
SQL Server computes the cardinality using the table statistics, computes and compares the two values and chooses the best plan.

A: Typically, it's going to be dependent on the size of the sets that are being joined.
I highly recommend reading "Inside Microsoft SQL Server 2008: T-SQL Querying" by Itzik Ben-Gan:
http://www.solidq.com/insidetsql/books/insidetsql2008/
(the 2005 edition is just as applicable on this topic as well)
He goes into your question, as well as many others when it comes to getting the most out of your queries.


text:
Q: How to 'dynamically render' HTML elements with PHP else/if statements? I am attempting to display the correct HTML under a "p" tag with PHP based on a true/false value which is pulled from WordPress ACF plugin, for every individual post. It's my first time using PHP and I'm not sure how to go about this.
My code is:

     <?php if (the_field('relocation', $job->ID) === 1) ?>

Currently, if the post has "relocation" marked as false - an empty applied-grid-filter "p" tag appears. If the post has "relocation" marked as true - an applied-grid-filter "p" tag with the number "1" for true appears.
How can I make it so that when it is marked false, no P tag is made at all - and when the post is marked true, a P tag with textcontent of "Relocation" is made?
edit full context:

<?php if (count($jobs)) { ?>

        <?php foreach ($jobs as $job) { ?>

<?= esc_html($job->post_title) ?>

<?php the_field('minimum_salary', $job->ID) ?>K
                        - <?php the_field('maximum_salary', $job->ID) ?>K

                        <img
                                class="job-search-location-icon"
                                src="<?= get_template_directory_uri() ?>/assets/location-icon.png"
                        />

Louisville, KY

                    <?php the_field('short_description', $job->ID) ?>

                    <?php foreach (get_terms('industry', ['object_id' => $job->ID]) as $term) { ?>

<?= esc_html($term->name) ?>

                    <?php } ?>
                    <?php foreach (get_terms('job_type', ['object_id' => $job->ID]) as $term) { ?>

<?= esc_html($term->name) ?>

                    <?php } ?>

                    <?php
                    if (the_field('relocation', $job->ID) === 1) { ?>

Relocation

                    <?php } ?>

                    <?php
                    if (the_field('travel', $job->ID) === 0) { ?>

No Travel

                    <?php } ?>

                <a class="job-view-more" href="<?php the_permalink($job->ID) ?>">View More

        <?php } ?>

<?php } else { ?>

No results found! Try another search.

<?php } ?>

A: Just move the html code inside your php code. You also might wanna use get_field instead of the_field. Also consider using the equal == instead of the identical === comparison operator which will be tolerant if the return value is not a number but for example true/false.
Also have a look at https://www.php.net/manual/en/language.operators.comparison.php for this.
<?php
if (get_field('relocation', $job->ID) == 1) { ?>

<?php }; ?>


text:
Q: I want to scrape reddit data using praw. I am getting raise ResponseException(response) error after adding the for loop subredditcmv=reddit.subreddit('changemyview')
cmv_subreddit=subredditcmv.top(limit=15)
cmv_dict={"Title":[], \
          "Score":[], \
          "id":[], \
          "number_of_comments":[],\
          "post":[],\
          "created":[]
          }
for posts in cmv_subreddit:
    cmv_dict["Title"].append(posts.title)
    cmv_dict["Score"].append(posts.score)
    cmv_dict["id"].append(posts.id)
    cmv_dict["number_of_comments"].append(posts.num_comments)
    cmv_dict["post"].append(posts.selftext)
    cmv_dict["created"].append(posts.created)

receiving this error

File "C:\Users\source\repos\lib\site-packages\prawcore\auth.py", line
  31, in _post
      raise ResponseException(response)
ResponseException: received 401 HTTP response

A: The 401 error mean that your request lacks valid authentication credentials for the target resource. You need to authenticate yourself with the reddit api.
However, if you only want to fetch data, you can use the read-only mode or request the data to the reddit api yourself

A: You are not authenticated with reddit's API (see the PRAW authentication page). Logging in first should fix this issue.


text:
Q: Caused by: ...cannot be cast to org.hibernate.engine.jdbc.connections.spi.ConnectionProvider What I am doing wrong? I think, trouble is in hibernate-core-3.5.6-Final-patched-play-1.1.1 library.
But I do not know where to get never maven dependency with connection package and ConnectionProvider.
I have config like this:
  <spring.version>4.1.3.RELEASE</spring.version>

  <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.7.Final</version>
        <scope>provided</scope>
    </dependency>

  <property name="hibernate.connection.provider_class">
        com.vse.uslugi.utilities.sql.DBCPConnectionProvider
  </property>

DBCPConnectionProvider.java http://pastebin.com/06AnvwuN

A: your class is implementing a different interface than hibernate is expecting.
you are implementing:
org.hibernate.connection.ConnectionProvider;

while hibernate was compiled against / expects:
org.hibernate.engine.jdbc.connections.spi.ConnectionProvider

the answer is likely much better explained here
to quote "Hibernate keeps changing the package containing the ConnectionProvider base class. It changed from version 3 to 4 and has changed again with verson 4.3."
Having said that, this only explains why you have the problem and shows what you're doing wrong but it doesn't solve your problem. What is the final-patched-play-1.1.1 library? if this is the latest version then I guess you will have to downgrade to hibernate 3 in order to use it.


text:
Q: How to remove certain number of lines every time particular string is found in file I want to remove 1 previous line and 10 following lines every time a string was found in the file.
foo.txt:
}
Name: john
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12
Apple
orange
grape
pine
}
Name: Ruben
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
grape
zebra
donkey
}
Name: Tom
Line
Line
Line
Line
Line
Line
Line
Line
Line
Line
Tiger
red
blue
orange
tomato
cat
}
Desired Out.txt :
Name: john
Apple
orange
grape
pine
Name: Ruben
grape
zebra
donkey
Name: Tom
Tiger
red
blue
orange
tomato
cat
I want to use sed or nawk. The flower brace and the next 10 lines after Name: should go away. Using Solaris 5.10 with ksh.

A: Using awk
$ awk '/}/{next;} /Name:/{print;n=NR+10} NR>n' file
Name: john
Apple
orange
grape
pine
Name: Ruben
grape
zebra
donkey
Name: Tom
Tiger
red
blue
orange
tomato
cat

How it works

*

*/}/{next;}
Skip over any line containing }.

*/Name:/{print;n=NR+10}
When we reach a line containing Name:, print it and, so we know when to start printing again, set n to 10 plus the current line number.

*NR>n
If the current line number is greater than n, then do the default action: print the line.
Using sed
With very similar logic:
$ sed -e '/}/d' -e '/Name:/{p;N;N;N;N;N;N;N;N;N;N;d;}' file
Name: john
Apple
orange
grape
pine
Name: Ruben
grape
zebra
donkey
Name: Tom
Tiger
red
blue
orange
tomato
cat

How it works

*

*/}/d
Delete any line containing }.

*/Name:/{p;N;N;N;N;N;N;N;N;N;N;d;}
If we find a line containing Name:, print it, then read in the next 10 lines and delete them.
Lines not falling into either the above categories are printed.


text:
Q: Upload files from webserver to GitHub I was wondering if it is possible to, via git, copy files from my webserver to my GitHub repo to start editing it with github?
Thanks

A: If you mean you want to copy the files directly from your webserver to GitHub, then no, that is not possible with git alone. While you could do it with some fairly straightforward shell scripting, I recommend that you try it manually for now.
First, create a new repository on GitHub - the following documentation will walk you through this: https://help.github.com/articles/create-a-repo/.
Then you can clone it to your computer! - https://help.github.com/articles/cloning-a-repository/
Download a copy of your current webserver files - your html, css, js (if any), images, etc, the whole shebang, but make sure you don't have any passwords or other secrets in there.
Copy your webserver files into the folder that was created when you cloned the repository.
Now, you need to add your files to the "index" (also called the staging area or cache), and then commit them to the repository. To do this, open a terminal, cd to the cloned repository folder, and then run:
git commit -am 'Initial Commit'

Lastly, push your changes to GitHub:
git push

Done! (but read below...)
I suggest having a look at GitHub Pages https://help.github.com/articles/what-is-github-pages/.
If you used GitHub Pages, each time you git push your new changes to GitHub, the website will update automatically. Whereas if you follow my answer above, you will need to reupload your website to your webserver each time you want it to update.
A note about editing files on GitHub:
While GitHub has a great text editor inbuilt into their web interface, I only use it for simple changes - to correct spelling mistakes, grammar, etc. When you want to make changes to HTML, CSS, or code in general, it is best to use a text editor designed for coding (like Atom) on your computer, and then push the changes to GitHub with git push.


text:
Q: Java 7 support of AES-GCM in SSL/TLS? According to Java 7 documentation as well as third party vendors, it appears Java 7 should support AES-GCM suites:

*

*ibm java 7

*java 7 ssl doc
I was hitting some errors in negotiation between client and server unable to negotiate a cipher due to restricting it to only the AES-GCM ciphers.  After investigation I found that it appears that the cipher suites are not supported on client nor server (tomcat instance).  Ran some sample code on client to get the output:
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());

SSLParameters params = context.getSupportedSSLParameters();
String[] suites = params.getCipherSuites();
System.out.println("Java version : " + System.getProperty("java.runtime.version"));
System.out.println("Connecting with " + suites.length + " cipher suites supported:");

for (int i = 0; i < suites.length; i++) {
    System.out.println();
    System.out.print(" ********* ");
    System.out.print(suites[i]);
    System.out.print(" ********* ");
}

Java version: 1.7.0_51-b13
Connecting with 63 cipher suites supported:

 ********* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_DHE_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_DHE_DSS_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDHE_RSA_WITH_RC4_128_SHA *********
 ********* SSL_RSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDH_RSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_RSA_WITH_RC4_128_MD5 *********
 ********* TLS_EMPTY_RENEGOTIATION_INFO_SCSV *********
 ********* TLS_DH_anon_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_anon_WITH_AES_128_CBC_SHA *********
 ********* TLS_DH_anon_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_anon_WITH_RC4_128_SHA *********
 ********* SSL_DH_anon_WITH_RC4_128_MD5 *********
 ********* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DH_anon_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_RSA_WITH_NULL_SHA256 *********
 ********* TLS_ECDHE_ECDSA_WITH_NULL_SHA *********
 ********* TLS_ECDHE_RSA_WITH_NULL_SHA *********
 ********* SSL_RSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_RSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_anon_WITH_NULL_SHA *********
 ********* SSL_RSA_WITH_NULL_MD5 *********
 ********* SSL_RSA_WITH_DES_CBC_SHA *********
 ********* SSL_DHE_RSA_WITH_DES_CBC_SHA *********
 ********* SSL_DHE_DSS_WITH_DES_CBC_SHA *********
 ********* SSL_DH_anon_WITH_DES_CBC_SHA *********
 ********* SSL_RSA_EXPORT_WITH_RC4_40_MD5 *********
 ********* SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 *********
 ********* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA *********
 ********* TLS_KRB5_WITH_RC4_128_SHA *********
 ********* TLS_KRB5_WITH_RC4_128_MD5 *********
 ********* TLS_KRB5_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_KRB5_WITH_3DES_EDE_CBC_MD5 *********
 ********* TLS_KRB5_WITH_DES_CBC_SHA *********
 ********* TLS_KRB5_WITH_DES_CBC_MD5 *********
 ********* TLS_KRB5_EXPORT_WITH_RC4_40_SHA *********
 ********* TLS_KRB5_EXPORT_WITH_RC4_40_MD5 *********
 ********* TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA *********
 ********* TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 ********* INFO - Received response from post device of :

Did not know if anyone else has come across such an issue.
Does Java 7 support use of AES-GCM in SSL/TLS?

A: As others said Java 1.7 does not support that cipher but, if you have the possibility to tweak your java installation you can add the security providers.
Here the steps:

*

*download from bouncycastle.org bcprov-ext-jdk15on-159.jar and bctls-jdk15on-159.jar and put then into the lib/ext directory of your jre/jdk (159 is the latest version now)

*edit the file lib/security/java.security of your jre/jdk and put the following lines:

*

*security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
-security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider

*renumerate all the following security providers by adding 2 (so security.provider.1=sun.security.provider.Sun becomes security.provider.3=sun.security.provider.Sun)

That's all, it should work now

A: AES-GCM is available in TLS v1.2. See [The Transport Layer Security (TLS) Protocol Version 1.2][1], section 6.2.3.3. TLSv1.1 did not add any cipher suites, and TLSv1.0 never had AES-GCM or the elliptic curve gear. (The elliptic curve stuff showed up in TLSv1.2 also).
The latest public build 80 of Java 7

*

*does support TLSv1.2 after changing code to use SSLContext.getInstance("TLSv1.2") in case of socket programming or just declaring the -Dhttps.protocols=TLSv1.2 in case of HTTP programming.

*does not support the AES-GCM cipher suite even under TLSv1.2, according to a request implemented only in a commercial build 191 of Java 7,
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8180834
Its interesting that the TLS_ECDHE_ECDSA_* cipher suites are showing up in your dump since they are TLSv1.2 ciphers.

A: Both Oracle JDK and OpenJDK start to support GCM ciphers in java 8.

*

*For OpenJDK, please see JEP 115: AEAD CipherSuites

*For Oracle JDK, please see JDK 8 Security Enhancements and Java Cryptography Architecture Oracle Providers Documentation for JDK 8

A: There are no GCM cipher suites in the SunJSSE Provider of Java 7 (assuming an Oracle JRE), although it supports TLS 1.2.
These have been introduced in Java 8 (see cipher suite table in the "The SunJSSE Provider" section).
1.8.0-ea-b124
Connecting with 71 cipher suites supported:

 ********* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_DHE_RSA_WITH_AES_128_CBC_SHA *********
 ********* TLS_DHE_DSS_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDHE_RSA_WITH_RC4_128_SHA *********
 ********* SSL_RSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDH_RSA_WITH_RC4_128_SHA *********
 ********* TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_RSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_RSA_WITH_RC4_128_MD5 *********
 ********* TLS_EMPTY_RENEGOTIATION_INFO_SCSV *********
 ********* TLS_DH_anon_WITH_AES_128_GCM_SHA256 *********
 ********* TLS_DH_anon_WITH_AES_128_CBC_SHA256 *********
 ********* TLS_ECDH_anon_WITH_AES_128_CBC_SHA *********
 ********* TLS_DH_anon_WITH_AES_128_CBC_SHA *********
 ********* TLS_ECDH_anon_WITH_RC4_128_SHA *********
 ********* SSL_DH_anon_WITH_RC4_128_MD5 *********
 ********* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA *********
 ********* SSL_DH_anon_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_RSA_WITH_NULL_SHA256 *********
 ********* TLS_ECDHE_ECDSA_WITH_NULL_SHA *********
 ********* TLS_ECDHE_RSA_WITH_NULL_SHA *********
 ********* SSL_RSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_ECDSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_RSA_WITH_NULL_SHA *********
 ********* TLS_ECDH_anon_WITH_NULL_SHA *********
 ********* SSL_RSA_WITH_NULL_MD5 *********
 ********* SSL_RSA_WITH_DES_CBC_SHA *********
 ********* SSL_DHE_RSA_WITH_DES_CBC_SHA *********
 ********* SSL_DHE_DSS_WITH_DES_CBC_SHA *********
 ********* SSL_DH_anon_WITH_DES_CBC_SHA *********
 ********* SSL_RSA_EXPORT_WITH_RC4_40_MD5 *********
 ********* SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 *********
 ********* SSL_RSA_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA *********
 ********* SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA *********
 ********* TLS_KRB5_WITH_RC4_128_SHA *********
 ********* TLS_KRB5_WITH_RC4_128_MD5 *********
 ********* TLS_KRB5_WITH_3DES_EDE_CBC_SHA *********
 ********* TLS_KRB5_WITH_3DES_EDE_CBC_MD5 *********
 ********* TLS_KRB5_WITH_DES_CBC_SHA *********
 ********* TLS_KRB5_WITH_DES_CBC_MD5 *********
 ********* TLS_KRB5_EXPORT_WITH_RC4_40_SHA *********
 ********* TLS_KRB5_EXPORT_WITH_RC4_40_MD5 *********
 ********* TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA *********
 ********* TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 *********

A: I've recently been messing around with Java and this cipher suite nonsense quite a bit recently.
From my experience, you need the unlimited policy files to get some extra suites. I can't remember off the top my head if using those would get you the GCM ciphers, but from my recollection with IBM java it at least got me the AES256 bit ciphers.
This link shows that you can at least initialise an SSLContext with TLSv1.2 (so you should be able atleast support all of the TLSv1.2 cipher suites that do not require the unlimited jurisditcion policy files)
Having a glance at some of the links I've looked at before I can't see any GCM ciphers on oracle's cipher suite list! orace-enabled/supported-cipher-suites.
Hopefully some of those links help you out!
(I'm typing this while running out of work so forgive me if I missed any gcm ciphers :) )

A: This answer is just derived from @dandfra answer, but without adding or amending Java JRE lib/ext. This may be useful in case you use the same Java library for multiple application, and you would not impact any applications.
First, add bouncy-castle into pom.xml
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.59</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bctls-jdk15on</artifactId>
    <version>1.59</version>
</dependency>

Then add it to Java when Java program starts.
ProviderList list = Providers.getFullProviderList();
list = ProviderList.insertAt(list, new BouncyCastleProvider(), 0);
list = ProviderList.insertAt(list, new BouncyCastleJsseProvider(), 0);
Providers.setProviderList(list);

Note that use of Security.addProvider will not work, as it simply appends the provider at the end.
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new BouncyCastleJsseProvider());

You may verify it using Security,getProviders().


text:
Q: Android beacon library - minimum steps to start ranging I would like the simplest program to add in my app. The program should only take beacon information after a dialog box option is clicked, I tried many times to write the code but didn't get what are the minimum steps required to start ranging.
public class SecondClass extends Activity implements BeaconConsumer {
private BeaconManager beaconManager;
protected static final String TAG = "RangingActivity";
RegionBootstrap regionBootstrap;

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

    beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
    beaconManager.bind(this);

    region = new Region("backgroundRegion", null, null, null);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(101); //closes notification

    //opens the alert dialog
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(this);
    }
    builder.setTitle("Send data")
            .setMessage("Are you sure you want to send your data to the server?")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // if yes was pressed, send the data

                    try {
                        beaconManager.startRangingBeaconsInRegion(region);
                    } catch (RemoteException e) {
                        Log.d(TAG, "Can't start ranging");
                    }

                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // if cancel was pressed, do nothing

                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}

@Override
public void onBeaconServiceConnect() {

    beaconManager.addRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
            if (beacons.size() > 0) {
                Log.i(TAG, "The first beacon I see is about " + beacons.iterator().next().getDistance() + " meters away.");
            }
        }
    });
}
}

Can anyone explain how the onBeaconServiceConnect runs? And do I need before to start ranging to do the monitoring process, check if there is a beacon and if there is a beacon to start ranging or is okay just to have a program only ranging?
I tried to do as described in Android Beacon Library sample code section, but didn't work
Best regards
EDIT
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Added these permissions to the code, but still not work
Another thing I did was to check if ACCESS_COARSE_LOCATION was enabled by using the function described in here (2nd top most voted answer)

A: Ranging by itself is fine.
The onBeaconServiceConnect is a callback that is made when the beacon scanning service is ready to go, after you call beaconManager.bind(this);. The callback indicates you are ready to start ranging or monitoring.  Make sure you get this callback.

*

*Make sure you can detect the same beacon with an off the shelf beacon detecting like BeaconScope: https://play.google.com/store/apps/details?id=com.davidgyoungtech.beaconscanner&hl=en_US

*If using iBeacon, Eddystone or a custom beacon format. Make sure you have registered the proper BeaconParser to work with the library.  Here is the code for iBeacon: beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));  Eddystone has a different layout.

*Make sure you have programatically requested and obtained location permission from the user if you are testing on Android 6+, otherwise detections will be blocked. http://altbeacon.github.io/android-beacon-library/requesting_permission.html

*Make sure Bluetooth is on, Location is enabled for the phone.

*If on Android 10+, make sure you have obtained FINE_LOCATION permission as COARSE_LOCATION is no longer sufficient.

A: The problem was: in the sample code I thought it was already specified for iBeacons, so I left as it was... changing to
beaconManager.getBeaconParsers().add(new BeaconParser().
                setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));
worked for the beacon I am using


text:
Q: Pre-ticking checkboxes in Angular2 I'm using RC7. I want to pre-populate some checkboxes, but can't find an answer that works for me.
basically I have this
  ngOnInit() {
    this.price = [true, true, false];
  }

and have tried to use ngModel and checked to turn on 2 of the 3 checkboxes

  {{val.name}}
  <input type="checkbox" [(ngModel)]="price[i]" [checked]="price[i]" name="price">

But none of the checkboxes are checked at the end of bootstrapping. If I click on them then the correct values are available in this.price in the component.
Update: Likewise
<input type="checkbox" [(ngModel)]="price[i]" [value]="price[i]" name="price">

does not work.
Answer
I got the best result combining the two answers below, by using ngModel but with the boolean value stored in the iterable.

  {{val.name}}
  <input type="checkbox" [(ngModel)]="val.state" name="price" />

A: Instead of
[checked]="price[i]"

assign the initial value to
price[i]

then [(ngModel)]="price[i] will update the state of the checkbox

A: Try below,
@Component({
  selector: 'my-app',
  template: `
My First Angular 2 App

  {{val.name}}
  <input type="checkbox" [checked]="val" name="price">

  `
})
export class AppComponent {
  prices=[];
   ngOnInit() {
    this.prices = [true, true, false];
  }
}

Here is the Plunker!!
Hope this helps!!


text:
Q: crontab not getting my current envrioment variables I want a cron job and everything is already set up and cron is also working but unfortunately, cron is not getting my environment variables. I'm getting my environment variables using os and they're working fine across the project but not in my cron.
settings.py
SECRET_KEY = os.environ.get('SECRET_KEY')

# Cron Jobs
CRONJOBS = [
    ('* * * * *', 'projects.cron.notifications_cron', '>> /cron/django_cron.log 2<&1')
]

crontab -e
 * * * * /usr/local/bin/python /app/manage.py crontab run 744fbefdbf3ad30bec13

error in log file
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

when I set the SECRET_KEY hardcoded in my settings.py then it is working fine but I want to get it from my environment variables.

A: You can assign your environment variables into the crontab environment file (crontab -e) so I convert all my environment variables into an env.txt and merge the crontab environment file into that env.txt file and replace the crontab environment file with my env.txt.
crontab -e default:
0 */24 * * * /usr/local/bin/python /app/manage.py crontab run 5d758d881d8f93b61f4d1b6a43eb72f6 >> /cron/django_cron.log 2<&1 # django-cronjobs for app

if you assign some VARIABLE in that file like below so the crontab will get that environment.
VARIABLE=value
0 */24 * * * /usr/local/bin/python /app/manage.py crontab run 5d758d881d8f93b61f4d1b6a43eb72f6 >> /cron/django_cron.log 2<&1 # django-cronjobs for app

here is the bash command to achieve it
$ printenv > env.txt # this will add all your environment variables in to env.txt
$ cat /var/spool/cron/crontabs/root >> env.txt # this will merge crontab environment file with your env.txt
$ cat env.txt > /var/spool/cron/crontabs/root # this will replace the crontab environment file with your env.txt

that's the only solution I produce on my own, hopefully, it will help you guys. thanks

A: Define your global variable inside crontab like this,
crontab -e
myVar='my variable reference'
If your variable is not constant, means dynamic in nature.
Follow these steps below:
Find crontab file by the command below.
sudo find / -type d -name crontabs
cd <path>
Here your cronjob file lives, just vi or nano by sudo. Give permission by sudo chown <username>:<groups> <filename> or sudo chmod 755 <filename>
Process of updating your variable. The following below code is in Bash so you can utilize it in your bash files directly which can be handled or you can run in other tool like python by the help subprocess library.
lineNumber=$(grep -n 'myVar=' <file-path>)
Change the line number with your new myVar with its updated value.
sed -i '/$lineNumbers/.*/myVar=myValue/' <file-path>


text:
Q: Spring Boot running as maven plugin works, but fails as packaged application I'm trying to run a Spring Boot app that uses Jersey. When running with 'mvn spring-boot:run' it starts up and works fine.
However, when I run as a packaged application ('java -jar ...') I get a FileNotFoundException that looks like:
Caused by: java.io.FileNotFoundException: /.../appsensor-ws-rest-server-boot/target/appsensor-ws-rest-server-boot-0.0.1-SNAPSHOT.jar!/lib/appsensor-ws-rest-server-2.2.0-SNAPSHOT.jar (No such file or directory)

When I look at the generated jar via
jar -tf target/appsensor-ws-rest-server-boot-0.0.1-SNAPSHOT.jar | grep ws-rest-server

, I get:
lib/appsensor-ws-rest-server-2.2.0-SNAPSHOT.jar

So the file appears to be there. Thoughts?

A: Actually found an answer after a bit more looking, and leaving this for others who might have the same problem.
This resource had the right answer: http://midgetontoes.com/blog/2015/04/13/filenotfoundexception-when-using-jersey-with-spring-boot
Essentially, you have to modify the configuration of the spring-boot-maven-plugin in some cases and add the requiresUnpack element for any dependent jars that require unpacking.


text:
Q: Why doesn't anyone release library of "@task" decorated functions for Airflow instead of Operator classes? Functions have more user-friendly interface. At the same time Operators cannot easily take results of another Operators. So why all providers packages have only classic operators, not functional ones?
This example works fine and @task decorated functions can be declared not only inside dag and can be reused.
from airflow.operators.python import get_current_context
from airflow.utils.dates import days_ago

@task
def return_func_context():
    context = get_current_context()
    return context['dag'].dag_id

default_args = {
    'owner': 'airflow',
    'start_date': days_ago(5),
    'retries': 0,
}

@dag(default_args=default_args, schedule_interval=None, catchup=False, tags=['example_dags'])
def simple_dag():
    return_func_context()

dag = simple_dag()


text:
Q: How to do search and pagination on same page in CakePHP 3 I'm struggling to doing search and putting result on same page with pagination in CakePHP 3.x.
Firstly I tried a technique but it is not giving desired result. In that, I made  few search fields on "page 1"  and after click on "search"  I do ajax call to fetch result from function "page 2" and load result on "page 1" but after clicking on next it redirects me to "page 2" while I want to stay on "page 1".
In other technique I'm thinking to use ajax call to load "JSON" data on same page but the problem is "I have no idea and could not find form internet" how to do pagination with Json data.
Anyone of you have a better idea to do search and load data on same page with pagination.


text:
Q: Why does query select (1/2) * 100 return 0 instead of 50 in SQL server 2005 I would like to get 50 as the output instead of 0.

A: It's because of integer division; 1/2 = 0, 0 * 100 = 0.
Use 1/2.0 * 100 instead

A: This is likely because SQL Server is using integer arithmetic for the calculation. The integer part of 1/2 is 0, and 0 * 100 = 0.

A: It is probably doing integer division on the 1/2, evaluating it as 0, so then the whole statement is zero.

A: The same in C#, Java and VB.net at least: integer arithmetic.
Why do you expect SQL be any different in evaluating expressions to other languages?


text:
Q: ¿Como eliminar un objeto de un array, según el valor de una propiedad, javascript? tengo el array de la siguiente forma:
productos_seleccionados.push({
"codigo": codinv_material,
"precio": preciosocio_material
})

lo lleno apartir de unos valores tomados de unos inputs, generando un resultado de esta forma:
{codigo: "30909", precio: "48.3"}
{codigo: "30399", precio: "332.5"}
{codigo: "31541", precio: "269.5"}

como podría hacer para eliminar espeficamente el objeto con valor 30399 de la propiedad codigo
ya que despues debo ir eliminando los objetos segun el codigo que yo mande.
Por ejemplo si mando el codigo: 31541, debe eliminarse el objeto
{codigo: "31541", precio: "269.5"}

y asi enviando los valores dinamicamente.
De antemano muchas gracias.

A: function deleteItem(list, removeItem){
    arr = $.grep(list, function(item) {
      return item.codigo != removeItem;
    });
    return arr
}

new_list = deleteItem(productos_seleccionados, "31541");
console.log(new_list);

puedes recorrer toda la lista para comprobar que elemento es el que contiene el valor que quieres eliminar
Actualizar item:
function updateItem(list, updItem, new_value){
    arr = $.grep(list, function(item) {

        if(item.codigo == updItem ){
           return item.cantidad = new_value;
           // return item.cantidad = item.cantidad + 1;
        }else{
           return item;
        }
    });
    return arr
}

la linea comentada es una opción si la cantidad siempre va de uno en uno.


text:
Q: rails - check before populating through model I have two models Physician and Patient, like below :
class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

p = patient obj.
so, p.appointments.append (physican_obj) is the proper way.
But, if I run the same command twice, it is adding the same thing twice. So, is it good to check if it already exists before appending ? Whats best way to do it ?
My requirement is, I get a list of objects to add it, so I need to loop over each object and append each object. If I need to check before appending, I need to check in every loop which is a costly process.

A: An approach is to use scope.
class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient

  validate_uniqueness_of :physician_id, scope: :patient_id
end

This will make sure a record which duplicates both two ids won't be allowed.


text:
Q: AssertionError while putting value in chronicle map I'm trying to use chronicle map as off heap map for my project. When I try to put a value in the chronicle map, I'm getting the below error.
This error comes when searchStatePresent() is true. I don't know what is this and there is not much information available.
Does anyone have any idea?
Exception in thread "main" java.lang.AssertionError
        at net.openhft.chronicle.map.impl.CompiledMapQueryContext.putNewVolatile(CompiledMapQueryContext.java:3975)
        at net.openhft.chronicle.map.impl.CompiledMapQueryContext.putEntry(CompiledMapQueryContext.java:3990)
        at net.openhft.chronicle.map.impl.CompiledMapQueryContext.doInsert(CompiledMapQueryContext.java:4176)
        at net.openhft.chronicle.map.MapEntryOperations.insert(MapEntryOperations.java:153)
        at net.openhft.chronicle.map.impl.CompiledMapQueryContext.insert(CompiledMapQueryContext.java:4099)
        at net.openhft.chronicle.map.MapMethods.put(MapMethods.java:89)
        at net.openhft.chronicle.map.VanillaChronicleMap.put(VanillaChronicleMap.java:901)

A: This suggests there is an inconsistency, possibly in your hashCode/equals.
The map attempted to find the key but couldn't find it initially, however when it went to insert the key/value it found it was already there.


text:
Q: ffmpeg producing strange NAL suffixes for MPEG-TS with h264 I am making h264 stream analyzer and have found strange ffmpeg behaviour while writing and reading same frame packetized with MPEG-TS.
I have dumped both encoding and decoding frame data in HEX and found these differences:
At the beginning of frame there is NAL delimiter added:
+ 00
+ 00
+ 00
+ 01
+ 09
+ f0

that looks absolutely legit to me.
But here comes strange things:
If current packet is not the last one than some suffix is added (i.e. there is no this suffix in the last written frame). And this suffix is added to current read frame (i.e. this is not prefix to next frame).
+ e0
+ 00
+ 00
+ 00
+ 01
+ ce
+ 8c
+ 4d
+ 9d
+ 10
+ 8e
+ 25
+ e9
+ fe

(exactly starting with e0 byte added)
I am trying to understand what that could mean. If 00000001 is NAL header than it is followed by ce byte with forbidden zero-bit equals 1 that is absolutely broken.
I am using fork from ffmpeg github repo last merged with 89092fafdde894c6ba4d4f8e3cd1cce0d68bfc22 commit.
ffmpeg is built with --disable-everything --enable-encoder=libopenh264 --enable-muxer=mpegts --enable-demuxer=mpegts --enable-protocol=file --enable-parser=h264 --enable-decoder=libopenh264 --enable-shared --disable-static --disable-programs --disable-doc --enable-libopenh264 options

A: So I have found the problem.
TL;DR:
pInputFormatContext->flags |= AVFMT_FLAG_KEEP_SIDE_DATA;

right after avformat_open_input
Explanation:
I've found while debbuging that AVPacket was spoiled at utils.c:1661 while performing
av_packet_merge_side_data(pkt);

Even more, I have found subsequence of that additional data seen before:
#define FF_MERGE_MARKER 0x8c4d9d108e25e9feULL

used in av_packet_merge_side_data
Side's data type in AVPacket  is AV_PKT_DATA_MPEGTS_STREAM_ID (78) which is used only in demuxers and muxers, but not in codec.
I was confused than I've read annotation to av_read_frame that I was using to read frame data from file:
Return the next frame of a stream.
This function returns what is stored in the file, and does not validate
that what is there are valid frames for the decoder. It will split what is
stored in the file into frames and return one for each call. It will not
omit invalid data between valid frames so as to give the decoder the maximum
information possible for decoding.

I have absolutely no idea of why streams flags where different on two PCs I've used, but disabling merging side data into packet's data did the trick.
So i think it is ffmpeg's documentation issue that it has assured me that "I will be returned what is stored in file" without mentioning that some additional data can be added.


text:
Q: reading bytes in a file in vb.net After getting the file name I create a new filestream and load all the bytes from the FileStream into a byte array, now I need to get certain bytes and store them in fields like the second 4 bytes are the time the file was created. When storing these in the variables should I store them as bytes or as string/integers/etc.
Or have I done it completely wrong?
EDIT:Should I be doing this way instead of a filestream?
Dim data() as Byte = File.ReadAllBytes(path1)

A: Using File.ReadAllBytes is a perfectly fine way of doing what you want to do.  This is example of an aggregate component which uses several factored types under the covers to accomplish a common task.  If you were to manually open a StreamReader and read the contents of the file you would be re-coding the implementation of File.ReadAllBytes almost exactly.
An aggregate component is simply a type that provides a very high-level API over several lower-level types.  The File type is a perfect example of an aggregate component since it has many methods that allow you to do common tasks simply and without having to create and use the underlying types (or "factored types" like StreamReader).
I think what you have now is just fine - it is simple and straightforward (which is the entire reason aggregate components exist in the first place).

A: Try reading the stream using the Read method(s), instead of copying the entire file into memory, if all you're doing is sequential reading. Then while reading, store a date/time as a DateTime value, etc.


text:
Q: Symfony2 inject a service I have a class which I have been using as a Service for other things.  I am now setting up a Command class to run a cron job for me.  This Command class needs to use a function which is contained within the class I have set up as a Service.  So I thought the best way to get access to this function would be to inject it into my Command Class.  So in my services I have
services:
    alert_bundle.api_service:
        class: Nick\AlertBundle\Service\UapiService
        arguments: [@service_container]

    alert_bundle.cron_service:
            class: Nick\AlertBundle\Command\UapiCronCommand
            arguments: [@alert_bundle.api_service]

UapiService is the Class that contains the function I need.
UapiCronCommand is the Command Class where I am performing my Cron.
So then I have my Command Class
class UapiCronCommand extends ContainerAwareCommand
{
    protected $api_service;

    public function __construct(UapiService $api_service)
    {
        $this->api_service = $api_service;
    }

    protected function configure()
    {
        $this->setName('OntroAlertBundle:uapi_cron')
            ->setDescription('Cron Job for Alerts');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
        $allAlerts = $em->getRepository("NickAlertBundle:Alert")->getAlertEntity();

        foreach($allAlerts as $alert) {
            if ($alert instanceof Alert) {
                $this->api_service->addFlightsAction($alert);
            }
        }

        $em->flush();
    }
}

Now I was thinking that this would be injected with my UapiService class so I could now use its function, however when I test things out with

php app/console NickAlertBundle:uapi_cron

I get the error

[InvalidArgumentException]
  There are no commands defined in the "NickAlertBundle" namespace.

I think this may be because I have added a __construct function to the Command class, not to sure though.  And if this is the reason, how can I then get my service to this class?
Thanks

A: As you can see in your UapiCronCommand class the "command name" defined in the $this->setName('OntroAlertBundle:uapi_cron') is OntroAlertBundle:uapi_cron and NOT NickAlertBundle:uapi_cron (like showed also in the error message).


text:
Q: Gradle 7.4 fails with Applet been deprecated and marked for removal Eclipse is hanging on me, so I reverted to a gradle build. Gradle classes fails with the error message below.
I do have a gradle.properties file in the project directory with: "org.gradle.warning.mode=none" in it. Eclipse normally runs the code and tests just fine.
I don't care about getting the warnings anywhere. I do want to stop the build from failing.
The build file below has a lot of extra stuff that I am not using now.
Edit 1: adding @SuppressWarnings("removal") seems to work.
C:\Users\raz\git\code\src\simplegui\InsetsDemo.java:4: warning: [removal] Applet in java.appl
et has been deprecated and marked for removal
public class InsetsDemo extends Applet {
                                ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

build file:
buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'org.hidetake:gradle-ssh-plugin:1.1.2'
  }
}
plugins {
    id 'java'
    id 'checkstyle'
    id 'distribution'
    id 'application'
}
repositories {
    mavenCentral()
}
sourceSets {
    main {
        main.java.srcDirs = ["src"]
        main.resources.srcDirs = ["resources"]
    }
    test {
        test.java.srcDirs = ["tst"] // removed slow/ as it was very.
    }
}
dependencies {
    testImplementation 'junit:junit:4.13.2'
    }
jar {
    manifest {
        attributes 'Main-Class': MyStuff.main
    }
}
run {
    standardInput = System.in
}
targetCompatibility = "16"
sourceCompatibility = "16"
version = '0.1'
mainClassName = MyStuff.main // for application plugin
class MyStuff {
    public static final String main="com.tayek.utilities.Dispatcher";
}

A: Is your build really failing because of that deprecation warning? As Oliver noted in the comments, that should only be the case when you run javac with the -Werror option. But even if you used that option, then the message would look different – probably like this:
error: warnings found and -Werror specified
1 error
1 warning

So from what I can tell, it rather seems that this deprecation warning is a red herring. Just to make sure: does your build fail at all? When you run ./gradlew classes, does Gradle report something like the following …
> Compilation failed; see the compiler error output for details.

… followed by "BUILD FAILED"?
If Gradle instead reports "BUILD SUCCESSFUL" for that command, then the warning is not an issue. If your build still fails when running other tasks (e.g., as part of ./gradlew build), then there should be other errors in the log. If not, then try adding the --stacktrace option to hopefully get more details about the actual error.

That said, if you only want to (entirely) get rid of that warning, then according to this SO answer your only option would be to add a @SuppressWarnings("deprecation") annotation to your InsetsDemo class. Otherwise the warning was "mandated by the Java Language Specification."


text:
Q: Changing Haproxy configuration on openshift I have a scalable Python 2.7 app on OpenShift and I'm getting this 503 error.
I checked some answers that might work but they say to rhc into the app and change the Haproxy configurations, but I don't have a clue on how to do it.
Can someone help me please?

A: 1) Install rhc: https://developers.openshift.com/en/managing-client-tools.html and read https://blog.openshift.com/how-haproxy-scales-openshift-apps/
2) Run $ rhc setup  for the initial configuration of the tool and check https://developers.openshift.com/en/managing-log-files.html#accessing-logs-via-ssh for viewing haproxy logs
3) Run rhc ssh --app yourapp, once inside, cd haproxy/conf and change your haproxy.cfg appropriately

A: I edited haproxy.cfg:
option httpchk OPTIONS * HTTP/1.1\r\nHost:\ {{ my app link }}

It's working now.


text:
Q: Query Environment Variables values defined in Jenkins Global Properties using API I have configured an environment variable under:

Manage Jenkins -> Configure System -> Global properties.

I'm able to use the environment variable in my jobs but I can't seem to find a way to query it remotely using the API.
Is it displayed anywhere?

A: We are setting global environments like this:
for (nodeproperty in hudson.model.Hudson.instance.globalNodeProperties) {
    siteSpecific.global_environment.each {key, value ->
        println "INFO: Adding: ${key}:${value}"
        nodeproperty.getEnvVars().put(key, value)
    }

    hudson.model.Hudson.instance.save()
}

So you should be able to read them the same way, but it not through the api, couldn't find a way for that.