text:
Q: Cannot let go of an object when in another object's collider I have some fairly simple code that allows me to grab, move, and let go of objects (in this case, the "LoopCubes" are the only things I want to be able to pick up:
public void grab(object sender, ClickedEventArgs e)
{
    if ((objectTouching != null) && objectTouching.CompareTag("LoopCube") == true)
    {
        objectTouching.gameObject.transform.SetParent(gameObject.transform);
    }
}

//Letting go of grip
public void releaseGrab(object sender, ClickedEventArgs e)
{
    if (objectTouching != null)
    {
        objectTouching.gameObject.transform.parent = null;
    }
}

This works as intended. However, a problem arises when I want to let go of the cube when the controller/cube are within a box collider (marked as a trigger). I can't let go and the cube becomes 'stuck' to the controller. What am I doing wrong?

A: Since I can't see your code I'm going to make some assumptions.
This is what I'm guessing is happening:

*

*Enter a trigger and set it to objectTouching

*Grab objectTouching & move around

*Enter another trigger, which sets objectTouching to something else, still having the previous objectTouching grabbed

*Release, which tries to release the current objectTouching, which is the last trigger you entered - not the grabbed object.


text:
Q: Как правильно: "503 Service Temporarily Unavailable" или "503 Service Unavailable"?
*

*На php.net отсутствует информация по формату заголовков header.

*В спецификации HTTP/1.0 указано: 503 Service Unavailable.

В сети встречаются оба формата записи:
header('HTTP/1.0 503 Service Unavailable');
header('HTTP/1.0 503 Service Temporarily Unavailable');

Так же интересует корректность этих заголовков:
header('HTTP/1.0 400 Bad Request');
header('HTTP/1.0 404 Not Found');

A: По стандарту – "503 Service Unavailable"
Но вы вольны использовать любую формулировку или вовсе оставить только код:

6.1.1 Status Code and Reason Phrase

The Status-Code element is a 3-digit integer result code of the
attempt to understand and satisfy the request. These codes are fully
defined in section 10. The Reason-Phrase is intended to give a short
textual description of the Status-Code. The Status-Code is intended
for use by automata and the Reason-Phrase is intended for the human
user. The client is not required to examine or display the Reason-
Phrase.

(курсив мой)

6.1.1 Код состояния и поясняющая фраза

Код состояния — это трехциферный код, обозначающий попытку понять и ответить на запрос. Подобные коды подробно определяются в секции 10. Смысл поясняющей фразы в том, чтобы дать короткое текстовое описание кода состояния. Предполагается, что код состояния будет обрабатываться машиной, а поясняющую фразу будет читать человек. От клиента не требуется, чтобы он обрабатывал или отображал поясняющую фразу.

Есть одна интересная оговорка о разнице между временными и постоянными поломками:

Except when responding to a HEAD request, the
server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition. User agents SHOULD display any included entity to the
user

На все запросы кроме HEAD [к ответу со статусом 5хх]  сервер ДОЛЖЕН добавлять данные о ситуации, в которой произошла ошибка, а также о том, является проблема постоянной или временной. Пользовательские агенты [например, браузеры] ДОЛЖНЫ отображать пользователю любые приложенные данные.

Итог:

*

*Вам не стоит беспокоиться о формулировке поясняющей фразы. Почти наверняка пользователь её не увидит, а программы вообще не должны её учитывать.

*Вы должны приложить к ответу 5xx данные о том, почему произошла ошибка и является ли она постоянной или временной. Наверняка пользователь увидит эти данные.

По субъективному опыту, хорошим тоном в GET-запросах является специальная страница, которая говорит о том, что случилась какая-то ошибка, но о ней уже известно и идёт работа над тем, чтобы её исправить.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twig include content and check if already include I have read the changelog of the twig (1.15.0 (2013-12-06))
https://github.com/fabpot/Twig/blob/master/CHANGELOG
* added a source function to include the content of a template without rendering it

But How can I do it? And what does it do exactly?
there is a function to check if a twig has already been included?
thanks !

A: The changelog refers to Twig's new include function, as opposed to the include tag.
There's some examples in the documentation (click the links above), and also some usage examples in slide 19-21 of this presentation.
When the changelog says "without rendering it", it means it isn't immediately output to the response stream, which enables you to catch and filter the contents before outputting/printing them.


text:
Q: Gutenberg block missing classes inside editor Iam trying to create a custom block to use in the gutenberg editor.
I have a rudimentary setup which kinda works.
But inside the Gutenberg editor my custom block seems to be missing some classes.
This results in the following:
The wrapper div of my block has just the classes:
block-editor-block-list__block

For example, the classes of a paragraph block:
block-editor-rich-text__editable block-editor-block-list__block wp-block rich-text

Or the default blockquote block:
wp-block-quote block-editor-block-list__block wp-block

With the class wp-block missing on my custom block, the block is always displayed as full-width,
without margins in the editor.
(nothing to do with the alignment option)
I tried to add className: props.className to the elements, but this doesnt add the missing classes to the wrapper of the block.
const {registerBlockType} = wp.blocks; //Blocks API
const {createElement} = wp.element; //React.createElement
const {__} = wp.i18n; //translation functions
const {InspectorControls} = wp.blockEditor; //Block inspector wrapper
const {SelectControl,PanelBody,ServerSideRender} = wp.components; //Block inspector wrapper
const {withSelect} = wp.data;

registerBlockType( 'my-custom-block/my-block', {
    title: __( 'My Custom Block', 'textdomain' ), // Block title
    category:  __( 'common' ), //category
    icon: 'images-alt',
    attributes:  {
        slideshow: {
            type: 'number',
            default: '0'
        },
        align: {
            type: 'string',
            default: 'center'
        }
    },
    supports: {
        align: ['center', 'wide', 'full']
    },
    keywords: [
        __( 'posts', 'textdomain' ),
        __( 'custom posts', 'textdomain' )
    ],

    //display the edit interface + preview
    edit: withSelect( function( select ) {
        return {
            posts: select( 'core' ).getEntityRecords( 'postType', 'posts', {per_page: 100} ),
        };
    } )( function( props ) {
            if ( ! props.posts ) {
                return __( 'Loading...', 'textdomain' );
            }

            let options = [ { value: 0, label: __( 'Select a post', 'textdomain' ) } ];

            if (props.posts.length > 0) {
                props.posts.forEach ((post) => {
                    options.push({value:post.id, label:post.name});
                });
            } else {
                return __( 'No posts', 'textdomain' );
            }

            const attributes =  props.attributes;
            const setAttributes = props.setAttributes;

            //Function to update heading level
            function changePost(post){
                setAttributes({post});
            }

            //Display block preview and UI
            return createElement('div', {
                className: props.className,
            }, [
                //Preview a block with a PHP render callback
                createElement( ServerSideRender, {
                    block: 'my-custom-block/my-block',
                    attributes: attributes,
                    className: props.className,
                } ),
                // Block inspector
                createElement( InspectorControls, {}, [
                    // Create a panel
                    createElement(PanelBody, {
                        title: __( 'Post Settings', 'textdomain' ),
                        initialOpen: true
                    }, [
                        // Create select field
                        createElement(SelectControl, {
                            value: attributes.post,
                            label: __( 'Select a slideshow', 'textdomain' ),
                            onChange: changePost,
                            options: options
                        })
                    ])// END PanelBody
                ])// END Block inspector
            ])

            //here
    } ),
    save(){
        return null;//save has to exist. This all we need
    }
});

props.className returns wp-block-my-custom-block-my-block.
Here is a screenshot of the block inside the editor, and also the classes.
You can see the classes and the full-width problem:

And here is a screenshot of a normal block:

And here is a screenshot of the full block HTML in the editor:

Iam new to creating blocks, I dont found any infos on what Iam doing wrong here.
Also Iam not familiar with ESNext code.


text:
Q: How to stop execution of outer function from a inner function? Here is what I want to do:
def bfunc():
    try:
        do_someting
    except Exception as e:
        return

def afunc():
    bfunc()
    xxx

def cfunc():
    xxx

def main():
    afunc()
    cfunc()

in bfunc(),I catch the exception.Now in my main(), I want to stop the afunc() execution when an exception occurs but proceed to execute cfunc().
How can I do this or is there any other way to catch the exception without too many nested try statements?
Tx

A: Because bfunc() is a function, therefore, to stop the execution of bfunc you can simply use return to stop bfunc. This won't affect cfunc because return only affect bfunc.
def bfunc():
    try:
        # do_someting
    except Exception as e:
        return # Exit the bfunc() immediately

You can use below code to see whether print will work or not
def bfunc():
    try:
        raise IndexError
    except Exception as e:
        return

def main():
    bfunc()
    print("Hello world")

if __name__ == "__main__":
    main()

A: Just move the try exception block to afunc. It should give the effect you want.
def bfunc():
    do_someting

def afunc():
    try:
        bfunc()
    except Exception as e:
        return
    xxx #you can move it to try block in order to catch exceptions here too, but I don't know if it's what you like to do


text:
Q: Nuget.exe update vs Update-Package in Visual Studio and Web/App.configs When updating a package version for a project via the command line using "nuget update (projectFile|packages.config) -Id (packageName) -NonInteractive" I have a bunch of web.configs generated (with transforms), and the existing app.configs are not transformed.
When updating the same package version for the same project via VS (Update-Package -Id (packageName)), there are no web.configs generated and the appropriate app.configs are transformed.
I realize the web.config's that are created have no adverse effect, but the extra file clutter bothers me.
Why is the behavior inconsistent? And is there a way for the CLI to adhere to the VS behavior (which I want)?
Using the latest version of nuget.exe 4.4.1

A:
Why is the behavior inconsistent?

That because the different behavior of nuget install command between NuGet CLI  and Visual Studio.
As we know, config transformations provide a simple way for a package to modify a web.config or app.config when the package is installed. And when we update a NuGet package, NuGet will uninstall the old version nuget package, then install the latest nuget package to the project.
However, the behavior of nuget install command between NuGet CLI  and Visual Studio are different.
The operation nuget install packages on NuGet CLI:

Obviously, NuGet will not re-transform app.configs when you using the update-packages operation on the NuGet CLI.
Conversely, operation nuget-install packages on Visual Studio:

Installs a package and its dependencies into a project

So using update-package on Visual Studio can appropriately transform app.configs file.

And is there a way for the CLI to adhere to the VS behavior (which I
  want)?

To my knowledge, I am afraid the answer is not. Because package manager console is providing is access to visual studio objects. We could not use it with NuGet CLI without Visual Studio:
https://github.com/NuGet/Home/issues/1512


text:
Q: Streamline some jQuery I wish to streamline some jQuery as it is taking too long to fire on some devices.
Does anyone have any ideas?
$( "#adultsPlus" ).click(function() {

    if($(".adults > select").val() != 9) {

        $(".adults > select").val(parseInt($(".adults > select").val())+1).change();

        $("#adultsCount").text($(".adults > select").val());
    }
});

A: Well, I don't exactly know why it takes too long on your devices, but obviously your code could be optimized to prevent frequent DOM searches of $(".adults > select").
Something like:
$( "#adultsPlus" ).click(function() {
    var adults = $(".adults > select");
    var adultsValue = parseInt(adults.val());

    if(adultsValue != 9) {
        adultsValue++;
        adults.val(adultsValue).change();
        $("#adultsCount").text(adultsValue);
    }
});


text:
Q: VScode mix.exs error - Could not compile with "make" Background
I have an umbrella app where I am making a build for windows using bakeware:
https://github.com/bake-bake-bake/bakeware
I have followed the normal setup for windows:
choco install -y zstandard make mingw

I have installed elixir and erlang otp via their official website installers:

*

*https://elixir-lang.org/install.html#windows

*https://www.erlang.org/downloads
Problem
I am able to run and do everything normally, but my VSCode marks my mix.exs file as a huge red error blob:
an exception was raised:
    ** (Mix.Error) Could not compile with "make" (exit status: 2).

        (mix 1.13.1) lib/mix.ex:515: Mix.raise/2
        (elixir_make 0.6.3) lib/mix/tasks/compile.make.ex:154: Mix.Tasks.Compile.ElixirMake.run/1
        (mix 1.13.1) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3
        (mix 1.13.1) lib/mix/tasks/compile.all.ex:92: Mix.Tasks.Compile.All.run_compiler/2
        (mix 1.13.1) lib/mix/tasks/compile.all.ex:72: Mix.Tasks.Compile.All.compile/4
        (mix 1.13.1) lib/mix/tasks/compile.all.ex:59: Mix.Tasks.Compile.All.with_logger_app/2
        (mix 1.13.1) lib/mix/tasks/compile.all.ex:36: Mix.Tasks.Compile.All.run/1
        (mix 1.13.1) lib/mix/task.ex:397: anonymous fn/3 in Mix.Task.run_task/3ElixirLS

Question
In Bakeware's page there is a section:

Change the default MAKE environment variable used by elixir_make from nmake to make (set it permanently to get rid of the errors in VSCode)

*

*But how do I do this?

*Is something wrong with my VSCode setup?

A: The elixir_make docs say to set the make_executable in your mix.exs to the make command installed on the system.
And then in your shell, either set the environment variables the Windows Way (If you already set the environment variables but they aren't taking, you may need to restart your terminal or VS Code), or if you're using bash, you can put them in your .bash_profile as the bakeware docs show.
Command Prompt:
set MAKE=make
set CC=gcc

or MinGW
export MAKE=make
export CC=gcc
mix release

A: Answer
I was able to somehow fix the issue.
Bakeware, the dependency, really likes Powershell. But not any powershell. A powershell with admin rights.
To get rid of the warning one must perform the following steps while VSCode is closed:

*

*Open Windows Powershell in admin mode

*set $env:CC="gcc"

*set $env:MAKE="make"

*set MIX_ENV to something. It doesnt have to be prod, but since powershell does not set this value by default, you have to manually set it yourself. Before running tests, fetching dependencies or anything.

*mix deps.get
After this, if you still get the red wall of death, trying deleting your .elixir_ls folder to force to go again.
Then open VSCode with code .
Hope it works for you, it did for me.
Trying this with any other terminal will result in seeing the red wall of death. According to my experiments, powershell is the only that works.


text:
Q: Nginx redirect from one domain to dynamic domain? I have two instances of nginx server running one with corporate ip and second with internal ip.I want a link from external nginx get redirected to internal nginx server and use external nginx as gateway. Also need to make sure that internal nginx running on dynamic IP
Tried to use variable for dynamic IP as shown in code snippet
 location /route/(?<section>.+){
      proxy_bind 172.31.*.*;
      proxy_pass http://$section/single-table-view;
      proxy_set_header Host $http_host;
}

A: You need to configure nginx as mentioned below:
If you want to redirect your External nginx to Internal nginx you should configure your External server like:
server {
        listen 80;
        listen [::]:80;
        server_name domain_name;

        location / {

                proxy_pass http://InternalNginxIpAddress:PortYouWant;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

Now each request from External nginx will be forwarded to Internal nginx, where your Internal nginx server is set as
proxy_pass http://localhost:PortYouWant;


text:
Q: assisatnce in the sql function I have posted below written code earlier and got the correct code with the removal of errors, but my criteria is not satisfying, below is the raw data im passing as the paramater
 2007:10113:/I/69071/MLI/Eldridge

and in return the output should be  "69071", for this i have given the below function but im not gettig the output,a nd i have kept some other condition to satisfy other requirements also, please help me.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON  --2007:10113:/I/69071/MLI/Eldridge
go
ALTER FUNCTION [dbo].[Empnum] (@RAWDATA NVARCHAR(300))
RETURNS VARCHAR(30)
 AS
BEGIN
DECLARE @TEMP1 NVARCHAR(300), @EMPNUM NVARCHAR(10), @TEMP2 NVARCHAR(300), @TEMP3 NVARCHAR(300)
SET @TEMP3 = 'Disabled'
SET @EMPNUM=''
SET @TEMP2 = @RAWDATA
IF( CHARINDEX(@TEMP3,@RAWDATA,1) = 0)
BEGIN
--   SET @EMPNUM='11'
 IF ISNUMERIC(SUBSTRING(@RAWDATA,1,1)) = 1
      BEGIN
 --
       IF((LEN(@RAWDATA) - LEN(REPLACE(@TEMP2,'/','')))>1)
             BEGIN
             SET @RAWDATA=SUBSTRING(@RAWDATA,CHARINDEX('/',@RAWDATA)+1,LEN(@RAWDATA))
              SET @RAWDATA=SUBSTRING(@RAWDATA,CHARINDEX('/',@RAWDATA)+1,LEN(@RAWDATA))
               SET @RAWDATA=SUBSTRING(@RAWDATA,1,CHARINDEX('/',@RAWDATA)-1)
  IF( CHARINDEX('*C',@RAWDATA) = 0 OR
     CHARINDEX('CV',@RAWDATA) = 0 OR
     CHARINDEX('AV',@RAWDATA) = 0 OR
     CHARINDEX('LV',@RAWDATA) = 0 )
      BEGIN
         SET @EMPNUM = ''
         RETURN @EMPNUM
     END
  ELSE
     BEGIN
         IF ISNUMERIC(SUBSTRING(@RAWDATA,1,1)) = 1
             BEGIN
                 SET @EMPNUM = @RAWDATA
                 RETURN @EMPNUM
          END
 ELSE
     IF((SUBSTRING(@RAWDATA,1,1)='C') AND ISNUMERIC(SUBSTRING(@RAWDATA,2,1)) = 1)
         BEGIN
             SET @EMPNUM = SUBSTRING(@RAWDATA,2,LEN(@RAWDATA))
             RETURN @EMPNUM
         END
END
 END
END
END
  RETURN @EMPNUM
 END

A: I have found the error in my code, and changed the "="o "<>"
IF( CHARINDEX('*C',@RAWDATA) <> 0 OR
 CHARINDEX('CV',@RAWDATA) <> 0 OR
 CHARINDEX('AV',@RAWDATA) <> 0 OR
 CHARINDEX('LV',@RAWDATA) <> 0 )
 BEGIN
     SET @EMPNUM = ''
     RETURN @EMPNUM
 END


text:
Q: strange bytes length when using python3 struct.pack() I am writing a python3 script to write some numbers as binary on file. While doing it I found something quite strange. for example, the following python code writes a "unsign short" and a "float" number to tmp file:
import struct
with open('tmp', "wb") as f:
  id1 = 1
  i = 0.5785536878880112
  fmt = "Hf"
  data = struct.pack('Hf', id1, i)
  f.write(data)
  print("no. of bytes:%d"%struct.calcsize(fmt))

According to the docs "H" (unsigned short) is 2 bytes and "f"(float) is 4 bytes. so I'd expect a 6-byte file, however the output is a 8byte data:
01 00 00 00 18 1c 14 3f

as indicated by
struct.calcsize(fmt)

which says "Hf" is of 8 bytes in size
if I do it separately, e.g.
data = struct.pack('H', id1)
f.write(data)
data = struct.pack('f', i)
f.write(data)

then the output is an expected 6-byte file:
01 00 18 1c 14 3f

what is happening here?

A: According to the documentation, specifying the byte order removes any padding:

No padding is added when using non-native size and alignment, e.g. with '<', '>', '=', and '!'.

Therefore, assuming you require little endian packing, the following gives the required output:
>>> struct.pack('<Hf', id1, i)
'\x01\x00\x18\x1c\x14?'

Note the <. (3f can be encoded as ASCII ?, hence the replacement)

A: struct.pack() aligns values according to their length, so a 4-byte value will always start at an index divisible by 4. If you write the data in chunks like you did in the second example, this padding can't be performed, obviously.
As the docs you linked to say:

By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).


text:
Q: MySql's Connector/Net with MVC 3 I'd like to get some information regarding using MySQL alongside ASP.NET (particularly MVC 3). From what I've found and experienced, it doesn't quite seem as customizable in terms of the Membership and User classes which come with Asp.Net, especially when it comes to validation or registration.
For example, after configuring my web.config file to use MySQL, I found myself realizing that, although a fair amount of tables were auto-generated for me to use, I wasn't able to change the names of them. Because of this, it seemed as though if I were to change a column name, or add a column to the table, it wouldn't quite work with the system, since everything has been pre-built.
Yet, with ADO.Net/Entity Framework, it appears that I might actually be able to have more freedom in how I go about creating my websites using MsSQL. Is this true? Is MySQL just not meant for ASP.Net, despite the the fact that you can install and use it at your leisure. Or is it that it just requires more work to get everything working, and you kind of have to reinvent the wheel by creating your own database classes and validation tools?
I'm not trying to bash either MySql or MsSql, I'm simply looking for a good analysis on the topic, as Google hasn't helped me much in this area.

A: This is more an issue with the default providers, and one of the many reasons why the 1st thing I did when I learnt about them was to try and make my own. (To be clear, creating your own one from scratch does require a fair amount of work, there are a few good tutorials out there that can give you a quick start)
[It'd make all our lives easier if the .Net framework used Interfaces for the providers rather than the base class... ]
To be clear, the big thing with the auto generated providers is the sprocs they use require the specified names, if you want to change the table names then you'll have to also update all the Sprocs as well. (This is true for any custom provider you may chose to build/use)


text:
Q: C++ wrapper for bound member function on resource constrained MCU I am trying to implement a pointer to member function wrapper where the return type and parameter types are known but the class type of the member function is not known. This is for a C++ project targeting resource constrained (No heap allocation/c++ standard library) microprocessor.
The following code seems to work (you can run it HERE) and it fulfills our general requirements, but it uses reinterpret_cast hackery.
//can't use any c++ std libs or heap allocation
#include <cstdio>

template<typename Ret,typename... Args>
struct member_cb
{

    template<typename T>
    void set_cb(T *obj_,Ret (T::*func)(Args...))
    {
        obj = reinterpret_cast<member_cb*>(obj_);
        cb = reinterpret_cast<Ret (member_cb::*)(Args...)>(func);
    }

    Ret operator()(Args... num)
    {
        return (obj->*cb)(num...);
    }

    member_cb* obj;
    Ret (member_cb::*cb)(Args...);

};

struct Bar{

    void someFunc(int n2){
        printf("someFunc called with parameter: %d\n",n2);
    }

};

int main()
{
    //class type of Bar is not known at wrapper creation
    member_cb<void,int> foo;

    Bar bar;

    foo.set_cb(&bar, &Bar::someFunc);

    foo(42);
}

I want to do this without the reinterpret_cast. I believe there is a solution using a lambda that is created by the set_cb() function something like this:
template<typename Ret,typename... Args>
struct member_cb
{
    template<typename T>
    void set_cb(T *obj_,Ret (T::*func)(Args...))
    {
        cb_func = [=](Args...num)
        {
            (obj_->*func)(num...);
        };
    }

    Ret operator()(Args... args)
    {
        return cb_func(args...);
    }

    Ret (*cb_func)(Args...);
}

The above code will not compile (you can try it HERE). Problem is that the regular function pointers like cb_func can only point to lambdas that have no captures, and the lambda has to capture the obj_ and the func parameters. Any suggestions on making this work would be appreciated.

A: A simple, compiler-independent solution:
template <typename Signature>
struct member_cb;

template <typename Ret, typename... Args>
struct member_cb<Ret(Args...)>
{
    template <typename T, Ret (T::*func)(Args...)>
    static Ret wrapper(void *object, Args&&... args) {
        T *o = reinterpret_cast<T *>(object);
        return (o->*func)(std::forward<Args>(args)...);
    }

    template <typename T, Ret (T::*func)(Args...)>
    void set_cb(T *obj_)
    {
        obj = obj_;
        cb_func = wrapper<T, func>;
    }

    // since C++17:
    template <auto func, typename T>
    void set_cb(T *obj_)
    {
        obj = obj_;
        cb_func = wrapper<T, func>;
    }

    Ret operator() (Args&& ...args)
    {
        return cb_func(obj, std::forward<Args>(args)...);
    }

    void *obj;
    Ret (*cb_func)(void *, Args&&...);
};

...
member_cb<void(int)> foo;
foo.set_cb<Bar, &Bar::someFunc>(&bar);
foo.set_cb<&Bar::someFunc>(&bar); // since C++17

The key limitation is that someFunc must be known at compile-time at the place set_cb is called, so you can't take arbitrary method pointer and convert it to a member_cb. It is possible to change the object keeping the method pointer intact, though (but that's not type-safe).
Another possible problem is that the compiler may need to emit a wrapper instance for each and every method that is ever used as a callback.
The upside is that it should work on any C++11-compliant compiler (C++17 for nicer syntax), and member_cb itself is small.


text:
Q: TurboPower LockBox 3 will not install in Delphi XE4 - error during compile I am trying to use LockBox 3 in Delphi XE4 to replace an encryption suite that has inexplicably stopped working.  I opened the Delphi project file and the three bpl's show up, but when I right-click and then choose install on LockBox3VCLDD240.bpl, it tries to compile and then gives the following error message:
[MSBuild Error] "0" is an invalid value for the "DebugInformation" parameter of the "DCC" task. The "DebugInformation" parameter is of type "System.Boolean".
I tried changing "Debug Information" to True in Project -> Options -> Delphi Compiler -> Linking, but the error still comes up.  Can anyone offer assistance?

A: I was able to get the above error message to go away by going to Project ->  Options -> Delphi Compiler -> Compiling and changing Debugging -> Debug Information to true.

A: If you want to add the new Delphi XE5 and up syntax (that uses "0" instead of "false" for DebugInformation) to Delphi XE4 or other versions you can edit  C:\Program Files (x86)\Embarcadero\RAD Studio\11.0\bin\CodeGear.Delphi.Targets and append:
<PropertyGroup>
  <DCC_DebugInformation Condition=" '$(DCC_DebugInformation)'=='0' ">false</DCC_DebugInformation>
  <DCC_DebugInformation Condition=" '$(DCC_DebugInformation)'=='1' ">true</DCC_DebugInformation>
</PropertyGroup>

after the "Static Properties" block comment.
Using this trick is useful when you work with projects that must remain compatible with XE5 or upper and you don't want to edit the project debug configuration every time.


text:
Q: Concavity related question. From a graph of $f'(x)$, how to find on what intervals $f(x)$ is increasing or decreasing, $f'(x)$ is increasing or decreasing, on what intervals $f(x)$ is concave up or down, $f'(x)$ is concave up or down?
This is the graph of $f'(x)$

So far, what I've tried:
for $f(x):$ Increasing on $(-5, -3.25)\cup (-1.5, 1)$ and Decreasing on $(-3.25, -1.5) \cup (1,6)$
for $f'(x):$ Increasing on $(-2.5, 0) \cup (3.5, 6)$ and Decreasing on $(-5, -2.5) \cup (0, 3.5)$

A: Concave up is where the graph looks like a smile, and concave down is where the graph looks like a frown. It looks like the graph is frowning in the interval $(-1.5,2)$, so concave down there, and smiling in $(-4.5,-1.5)$ and in $(2,5.5)$, so concave up there. When you took a picture, your book was not flat, and this distorted the graph a bit, so you take a look one more time in your book :)


text:
Q: Matching hex bytes in hex strings using regular expressions What I have is an input string which represents a hex number, e.g.:
E3E4E5E64E

I would like to test it, using a regular expression, whether certain hex byte is present
in the number represented by this hex string, e.g.: 4E.
When I'm trying to simply match 4E, I'm hitting both the correct 4E byte at the end of the string and incorrect 4E which does not form a byte, but is simply the last digit of E4
and first digit of E5.
Is it possible to write a regular expression to operate on pairs of characters?

A: /([A-Fa-f0-9]{2})/g
I am guessing that you want every 2 hex characters.
http://www.regex101.com/r/nO5qL2
Edit:
Ok, I understand now what you want, you want to match the 4E at the end, but not any occurences like 4E from E4E5.
Here it is:
/^([A-Fa-f0-9]{2})*(4E)/
The first group is matching 0, 2, 4, .. 2n characters and then it will match the 4E group(not necessary for 4E to be group but it is easier to extract it).
Example:
http://www.regex101.com/r/iQ7uX4
Of course, you can replace 4E with anything you want.
Java RegExp may need a .* at the end of the RegExp, I cannot test right now.

A: You can try this as your regex:
4E(?=(?:..)*$)

See it here on Regexr
(?=(?:..)*$) is a lookahead assertion. 4E is only matched if this assertion is true. This assertion is true if there are only multiples of 2 characters (?:..)* till the end (ensured with the anchor $).

A: Try it out
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       //Input String
       String str = "4EE4E5E64E";
       String splitArray,pattern="4E";

       //Convert into json Array
       splitArray=Arrays.toString(str.split("(?<=\\G.{2})"));

       //Split based on ","
       String[] tempArray = splitArray.split(",");

       for(int i=0;i<tempArray.length;i++)
       {
           String compareString=tempArray[i];

           //Remove whitespaces
           compareString=compareString.replaceAll("\\s+","");
           if(i==0||(i==tempArray.length-1))
           {
               if(i==0)
               {
                    compareString=compareString.substring(1,3);
               }else
               {
                    compareString=compareString.substring(0,2);
               }
           }

           //Compare with pattern string If yes goes inside
           if(compareString.equalsIgnoreCase(pattern))
           {
               System.out.println("Yes");
           }
       }
    }
}

You can also use JSONObject and JSONArray class for spliting an array and comparing with pattern string.

A: Regular expressions are quite limited. They can't "understand" the context.
For more details, read about:

*

*Regular expressions

*Regular languages

*Chomsky hierarchy of languages
So, with standard regular expressions, it is not possible to distinguish between 4E standing between two hex numbers E4E5 and one forming the hex byte 4E.
However, nothing forces you to rely on regexes only! For example, if you know your string contains hex string only, you can accept only those matches resulting from a regexp that start at even position indices.

A: I guess the regular expression: ([4E]{2}) can fit fine for you...!!


text:
Q: const_missing error when changing I18n backedn I'm trying to upgrade the I18n backend of my application to use the database instead of the yml files for internationalization.  I'm following the steps found for the I18n-active_record gem found here: https://github.com/svenfuchs/i18n-active_record.
Unfortunately, the aws-s3 gem seems to be conflicting somehow as I can't even start my server or console once I create the locale.rb initializer.  Here is a summary of the steps I'm following:
gem "i18n-active_record", "~> 0.0.2"
create new file config/initializers/locale.rb
inside locale.rb
I18n.backend = I18n::Backend::Database.new
restart localhost server to load initializer

Error Message
/Users/user_name/.rvm/gems/ree-1.8.7-2010.02@app/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:206:in `const_missing': uninitialized constant I18n::Backend::Database (NameError)
...(Several more lines)
Any help or insight would be appreciated!

A: Great question and great discussion.  The answer is contained in a combination of the comments up above, but for those of you who are upgrading to a Rails 3 application, this is a summary of the steps I had to take.
Add this to your Gemfile:
gem 'i18n-active_record', :require => 'i18n/active_record'

Add this to a new config file config/initializers/locale.rb
require 'i18n/backend/active_record'
I18n.backend = I18n::Backend::ActiveRecord.new

Take out any code in application.rb that was previously initializing the record store.  This clears the missing content errors.  Full instructions are on the Github repo for this backend module which was removed from the core I18n: https://github.com/svenfuchs/i18n-active_record

A: Although the readme in github says so, I don't think the Database constant is actually defined by the gem. Try
I18n.backend = I18n::Backend::ActiveRecord.new


text:
Q: lookup within filtered range I have a dataframe with data from ecommerce panel.
It has orders and returns mixed together.
Each row has orderID - it's the same number for normal orders and for corresponding returns that come back from customers.
My data looks like this:

orderID
Shop
Revenue
Note

44
0
-32
Return

45
0
-100
Return

44
1
14

45
3
20
Something else

46
2
50

47
1
80
Something

48
2
222

For each return I want to find a 'Shop' column value that corresponds to original order.
For example : 'orderID' == 44 comes twice: once as return (with 'Shop' == 0) and once as normal order (with 'Shop' == 1).
I want to replace all the 0 values with 'Shop' column with values from earlier orders
My desired output looks like this:

orderID
Shop
Revenue
Note

44
1
-32
Return

45
3
-100
Return

44
1
14

45
3
20
Something else

46
2
50

47
1
80
Something

48
2
222

I know how to do it in Google Sheets (first I filter table removing 'Shop'==0 values and then I vlookup for numbers in this filtered array)
I know how to filter this table using Pandas but I don't know how to write it.
I assume that I will need to write a temporary column first, where I store both types of values - for normal orders (just copied) and for returns.
Original dataframe is 1 000 000+ rows
My data in .csv is available here:
https://docs.google.com/spreadsheets/d/e/2PACX-1vQAJ4tMc_Bcvv-4FsUy3E7sG0m9hm-nLTVLj-LwlSEns-YJ1pbq6gSKp5mj5lZqRI2EgHOsOutwnn1I/pub?gid=0&single=true&output=csv
Thank you for any advice!

A: IIUC, using map:
m = df.query('Shop != 0').set_index('orderID')['Shop']
df['Shop'] = df['orderID'].map(m)
print(df)

Output:
   orderID  Shop  Revenue            Note
0       44     1      -32          Return
1       45     3     -100          Return
2       44     1       14             NaN
3       45     3       20  Something else
4       46     2       50             NaN
5       47     1       80       Something
6       48     2      222             NaN

Create a pd.Series using query to filter out zero shops then set_index and map shops to orderID.
This works if there is a 1-1 shop to order mapping. If you have multiple shops per order, then you'll need logic to determine which shop valid.
If you have duplicate order to the same shop, then you need to drop_duplicates first.


text:
Q: neo4j query performance - getting nodes with degree >1 match (n:A)-[r:Transaction]-(m:B) with n,count(r) num where num>1 return n

There are 100M nodes and 250M relations in the graph.
The above query is a simple group by in a relational DB and returns in < 5mins. It takes forever in Cypher, any ideas what can make it faster

A: So you want nodes of type A that have more than one :Transaction relationship with one or more nodes of type B?
Try
MATCH (n:A) WHERE size((n:A)-[:Transaction]-(m:B)) > 1
RETURN n

Check out this blog post for more on efficient relationship counting.


text:
Q: C++ initializer list and default values Is this code valid with C++14
using namespace std;
struct Point
{
  int x = 0;
  int y = 0;
};
Point p2 {1, 1};

It compiles fine with clang++ 7.0, it doesn't work with G++ 4.9 in both cases I pass --std=c++1y to the compiler.
In G++ it works when I remove the default values from the struct definition.
g++ test_constexpr_ctor.cc --std=c++1y -o test
test_constexpr_ctor.cc:7:15: error: no matching function for call to 'Point::Point(<brace-enclosed initializer list>)'
Point p2 {1, 1};
            ^
test_constexpr_ctor.cc:7:15: note: candidates are:
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point()
struct Point
        ^
test_constexpr_ctor.cc:1:8: note:   candidate expects 0 arguments, 2 provided
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(const Point&)
test_constexpr_ctor.cc:1:8: note:   candidate expects 1 argument, 2 provided
test_constexpr_ctor.cc:1:8: note: constexpr Point::Point(Point&&)
test_constexpr_ctor.cc:1:8: note:   candidate expects 1 argument, 2 provided

A: The code is valid.

*

*(8.5.4/3):

List-initialization of an object or reference of type
  T
  is defined as follows:
  —
   If
  T
  is an aggregate, aggregate initialization is performed

*An aggregate in c++14 is defined as (8.5.1/1):

An
  aggregate
  is an array or a class (Clause
   9
  ) with no user-provided constructors (
  12.1
  ), no private or
  protected non-static data members (Clause
   11
  ), no base classes (Clause
   10
  ), and no virtual functions (
  10.3
  ).

Note that in c++11 this definition looked different (emphasis mine):

An
  aggregate
  is an array or a class (Clause
   9
  ) with no user-provided constructors (
  12.1
  ), no
  brace-or-equal-
  initializer
  s for non-static data members (
  9.2
  ), no private or protected non-static data members (Clause
   11
  ),
  no base classes (Clause
   10
  ), and no virtual functions (
  10.3
  ).

Since this part is removed in c++14, your struct is definitely an aggregate and thus aggregate initialization should be performed.
This is fixed in gcc5 (search the changes list for "aggregates with non-static data member initializers"). I wouldn't call it a "bug" though, it's rather the gcc team only implemented that change in gcc 5.1.0.

A: The code you posted is absolutely correct.
However the behaviour you have is a not yet closed bug of G++ version 4.9.1. Actually, it may be a duplicate and closed in some other bug report, because the problem is fixed since g++ 5.1.0 or maybe even earlier version. To find actual bug you may use bugzilla's search.


text:
Q: Smallest Non-negative number in a matrix There is a question I encountered which said to fill an $N \times N$ matrix such that each entry in the matrix is the smallest non-negative number which does not appear
either above the entry or to its left. That is for $N = 6$ the matrix looks like this:
$$\begin{array}{}
0&1&2&3&4&5\\
1&0&3&2&5&4\\
2&3&0&1&6&7\\
3&2&1&0&7&6\\
4&5&6&7&0&1\\
5&4&7&6&1&0
\end{array}$$
I was asked to find a function such that given row and column I can calculate the value at that point i.e
$$f(\text{row}, \text{column}) = \text{Matrix}[\text{row}][\text{column}]$$
I was looking at Nimbers and found the matrix in it exactly similar to it. There was also given a formula to calculate to calculate Matrix[row][column] which was row XOR column (XOR is bitwise exor).
However I was able to get the answer I am still unable as to how to arrive at the solution i.e. the proof that each entry in the matrix is the smallest non-negative number which does not appear either above the entry or to its left is equal to row XOR column.

A: Denote by $a(m,n)$ the entry in row $m$, column $n$ of the matrix. By definition
$$a(m,n)=\operatorname{mex}\big(\{a(k,n):k<m\}\cup\{a(m,k):k<n\}\big)\;,\tag{1}$$
where $\operatorname{mex}(A)$ is the smallest non-negative integer not in $A$. The problem is to show that when all of the numbers involved are expressed in binary, $a(m,n)=m\oplus n$, the bitwise exclusive OR of $m$ and $n$. We'll do this by induction on $m+n$. It's certainly true when $m+n=0$: $a(0,0)=0=0\oplus 0$. Now assume let $m,n\in\mathbb{N}$, and assume that it's true for all $m',n'\in\mathbb{N}$ with $m'+n'<m+n$; we'll show that it's true for $m$ and $n$.
Let $s=m\oplus n$. To show that $s=a(m,n)$ as defined by $(1)$, I need to show two things:

*

*if $0\le t<s$, $t\in\{a(k,n):k<m\}\cup\{a(m,k):k<n\}$; and

*$s\notin\{a(k,n):k<m\}\cup\{a(m,k):k<n\}$.

To show (1), suppose that $0\le t<s$, let $d=t\oplus s$, and let $k$ be the number of bits in $d$, so that $2^{k-1}\le d<2^k$. That is, $d$ has a $1$ in the $k$-th position counting from the right. Since $t<s$, this implies that $t$ has a $0$ in the $k$-th position, and $s$ has a $1$ there. Since $s=m\oplus n$, exactly one of $m$ and $n$ must have a $1$ in the $k$-th position; without loss of generality assume that $m$ has a $1$ in the $k$-th position. Then $d\oplus m$ has a $0$ in the $k$-th position and is identical to $m$ in positions to the left of the $k$-th position, so $d\oplus m<m$. Let $k=d\oplus m$; then $$k\oplus n=d\oplus m\oplus n=d\oplus s=t\oplus s\oplus s=t\;.$$ Moreover, $k<m$, so $k+n<m+n$, and therefore $t=k\oplus n=a(k,n)$ by the induction hypothesis. This completes the proof of (1).
To show (2), suppose, on the contrary, that $s\in\{a(k,n):k<m\}\cup\{a(m,k):k<n\}$. Without loss of generality we may assume that $s\in\{a(k,n):k<m\}$. Let $k<n$ be such that $s=a(k,n)$. Clearly $k+n<m+n$, so by the induction hypothesis we have $$k\oplus n=a(k,n)=s=m\oplus n\;,$$ and therefore $$k=k\oplus n\oplus n=m\oplus n\oplus n=m\;,$$ contradicting the choice of $k$. Thus, (2) also holds, and $m\oplus n=a(m,n)$.

A: I really like this question.  I saw it on a website a year or so ago, closed the page so that I wouldn't see the answer, and then never found it again.  I solved it by proving by induction that $$ f(4i+r, 4j+s) = f(r,s)+4f(i,j)$$ --- this relation is apparent if you draw enough of the matrix.  Let me know if you would like the details.  Once you have this relation, you can apply it repeatedly to get
$$f(\sum a_i 4^i, \sum b_i 4^i) = \sum h(a_i,b_i) 4^i$$
where $h$ is a the function determined by the first 4x4 block of the matrix.  This explains why it is possible to think of f as a "bitwise" operation.

A: It's the XOR function, and you can prove it by induction on the bit length.
For $0\leq x,y<2^n$ with binary expansions
$$
  x=\sum_{i=0}^{n-1} x_i 2^i,
  \quad
  y=\sum_{i=0}^{n-1} y_i 2^i
  \quad
  \text{for}
  \quad
  x_i, y_i \in \{0,1\},
  \quad
  \text{and}
  \quad
  x,y \in I_n=\{0,1,\dots,2^n-1\},
$$
we start by assuming inductively that
$$
  f(x,y) = XOR(x,y) \equiv \sum_{i=0}^{n-1} x_i y_i 2^i
$$
and observe (also as part of our inductive hypothesis)
that each row and column (where one of $x$ or $y$ is
fixed, but the other varies freely over $I_n$)
contains precisely the values $I_n$ (once each).
Now for the inductive step, we let $x_n,y_n\in\{0,1\}$ be arbitrary, and
note first that the base block $(x_i,y_i)=(0,0)$ is our inductive hypothesis.
Next, note that for $(x_i,y_i)=(0,1)$ and $(x_i,y_i)=(1,0)$, all of the values
in $I_n$ are already taken and so the minimality rule will assign values to $f$
starting with $2^n$ rather than $0$, filling these blocks with the values
$I_{n+1} \setminus I_n = \{2^n,2^n+1,\dots,2^{n+1}-1\}$. Furthermore, these
values will be assigned within each block in the same order as they were
in the base block. Finally, the block $(x_i,y_i)=(1,1)$ will match the base block,
since its predecessors (the two non-base, inductive blocks already considered)
used the values from $I_{n+1} \setminus I_n$ but left those from $I_n$ vacant.
Thus, the minimality criterion is additive:
$$
  f(2^i x_i + x, 2^i y_i + y)
  = 2^i XOR(x_i,y_i) + f(x,y)
  = 2^i x_i y_i + f(x,y)
$$
which proves the inductive step.
The key insight that makes this proof work is that the blocks of $(x,y)$
for $0 \leq x,y < N$ are "full" (containing each value from $0$ to $N-1$
in each row and column) iff $N=2^n$ is a power of two.

A: All these proofs rely on the observation that this question is related to the bitwise XOR operator (after a few examples, this is very easy to see). However, I still cannot see the intuitive connection between the original problem and the Nimbers. Does anyone have a clear insight on this?

A: Lets say you selected a row (say $A$ represented using n-bits). Now, for all the $2^n$ columns (say $B$) you select, you will get different bit strings, hence different numbers.
For a particular $A$, $A\oplus B$ is distinct for distinct values of $B$. Thats why you get different numbers and that too within the range of n-bit. The same is not true for AND or OR operators.
A  B  A xor B    A and B   A or B
0  0     0          0         0
0  1     1          0         1
1  0     1          0         1
1  1     0          1         1

Here you notice that if you take bitwise AND, then for a particular row you can get same values for different columns. For example, for $5^{th}$ row ie $(101)_2$ will have a value 5 $(101)_2$ at $5^{th}(101)_2$ as well as $7^{th}(111)_2$ column.
So, A[5][5] = A[5][7] = 5 which is not required. This problem comes because of 0 in the bitstring.
Similarly for OR, this repetition will come because of 1 in the bitstring.
A[5][5] = A[5][4] = A[5][1] = A[5][0] = 5
So, you can now see why bitwise XOR is used.
But its not using the smallest possible value. In your array, you can see that 4 and 5 are missing in $3^{rd}$ and $4^{th}$ rows; and 2 and 3 in $5^{th}$ and $6^{th}$ rows. This is because you have 6 rows and columns for which you need 3 bits which can accommodate 8 values.
\begin{array}{} 0&1&2&3&4&5\\ 5&0&1&2&3&4\\ 4&5&0&1&2&3\\ 3&4&5&0&1&2\\ 2&3&4&5&0&1\\1&2&3&4&5&0 \end{array}
To get the minimum values, you can just shift the values while stepping onto the next row.


text:
Q: Conditional ROW NUMBER or COMBINE GROUP BYs I need to GROUP BY two different columns and combine.  Furthermore,  IF a size with a different group_id matches another size, then I want to include ALL of those rows for that group_id.
For example, since 55 is in group_id 10 and group_id 20 I want to include all of the results in group_id 20 (IE 55,88,55,88).
p_id  | group_id | size | the_date
------+----------+-----------+--------
1     |    10    |  55  | 2012-10-24
1     |    10    |  54  | 2014-08-09
1     |    20    |  55  | 2013-05-20
1     |    20    |  88  | 2014-05-20
1     |    20    |  55  | 2015-05-20
1     |    30    |  33  | 2014-05-20
1     |    30    |  55  | 2015-05-20
1     |    30    |  33  | 2015-05-20
1     |    40    |  99  | 2015-05-20

I've looked at some of the other questions on stack AND tried using row_number and first_value but nothing has worked.  Below is my desired result.
p_id  | group_id | size |       group_id_arr         |         size_arr            |  date_arr
------+----------+------+----------------------------+-----------------------------+-----------
1     |    10    |   55 | {10,20,30,20,10,30,30,20}  |  {55,55,33,88,55,55,33,55}  | {2012-10-24,2013-05-20,2014-05-20,2014-05-20,2014-08-09,2015-05-20,2015-05-20,2015-05-20}
1     |    40    |   99 |          {40}              |            {99}             | {2015-05-20}

Here is my DBFiddle where I am trying to achieve the following so I can aggregrate.
 rn   |   p_id   | group_id | size | the_date
------+----------+----------+------+-----------
1     |    1     |    10    |  55  | 2012-10-24
2     |    1     |    20    |  55  | 2013-05-20
3     |    1     |    30    |  33  | 2014-05-20
4     |    1     |    20    |  88  | 2014-05-20
5     |    1     |    10    |  54  | 2014-08-09
6     |    1     |    30    |  55  | 2015-05-20
7     |    1     |    30    |  33  | 2015-05-20
8     |    1     |    20    |  55  | 2015-05-20
1     |    1     |    40    |  99  | 2015-05-20

Please let me know if you have any questions. I'm open to all approaches, thanks.

A: I am not quiet sure about the ordering in the final arrays but this should be a detail you can fix:
demo: db<>fiddle
WITH sizes as (
    SELECT group_id, the_date, array_agg(size) sizes
    FROM base_table
    GROUP BY group_id, the_date
)
SELECT
    a_group_id,
    array_agg(b_group_id order by the_date),
    array_agg(size order by the_date) as sizes,
    array_agg(the_date order by the_date)
FROM (
    SELECT
        a.group_id as a_group_id,
        b.group_id as b_group_id,
        unnest(b.sizes) size, b.the_date
    FROM sizes a
    INNER JOIN sizes b
    ON a.sizes && b.sizes
) s
GROUP BY a_group_id

*

*Aggregate the sizes per group_id

*Cross join the aggregates with themself where one size array has at least one member with another. That gives you a table that you expected and decribed.

*Grouping by the group_id.

A:  select t.id as p_id,min(t.group_id) as group_id, t1.size as size,array_agg(t.size) as size_arr,array_agg(t.group_id) as grp_arr, array_agg(t.date_column) as date_arr from t
 join
 (select distinct group_id as grp_id, size from t where size=99 or size=55) t1
 on t1.grp_id=t.group_id
 group by t.id ,t1.size;

Check this one :)


text:
Q: Can not send JSON using POST request and Jackson This is my entity class:
@Entity
@Table(name = "menuitem")
public class MenuItem {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY )
@Column(name = "id")
private Integer id;

@Column(name = "title")
private String title;

@Column(name = "eng_title")
private String engTitle;

@Column(name = "price")
private double price;

@Column(name = "description")
private String description;

@Column(name = "consist_of")
private String consistOf;

@Column(name = "volume_value")
private double volumeValue;

@Column(name = "volume_title")
private String volumeTitle;

@ManyToOne
@JoinColumn(name = "category_id",insertable = false, updatable = false)
private Category category;

@Column(name = "category_id")
private int categoryId;

public MenuItem() {

}

public MenuItem(JSONObject jsonObject) {
    if (!jsonObject.isNull("id")) {
        this.id = jsonObject.getInt("id");
    }

    if (!jsonObject.isNull("title")) {
        this.title = jsonObject.getString("title");
    }

    if (!jsonObject.isNull("engTitle")) {
        this.engTitle = jsonObject.getString("engTitle");
    }

    if (!jsonObject.isNull("price")) {
        this.price = jsonObject.getDouble("price");
    }

    if (!jsonObject.isNull("description")) {
        this.description = jsonObject.getString("description");
    }

    if (!jsonObject.isNull("consistOf")) {
        this.consistOf = jsonObject.getString("consistOf");
    }

    if (!jsonObject.isNull("volumeValue")) {
        this.volumeValue = jsonObject.getDouble("volumeValue");
    }

    if (!jsonObject.isNull("volumeTitle")) {
        this.volumeTitle = jsonObject.getString("volumeTitle");
    }
}

public MenuItem(Integer id, String title, String engTitle, double price,
        String description, String consistOf, double volumeValue,
        String volumeTitle) {
    super();
    this.id = id;
    this.title = title;
    this.engTitle = engTitle;
    this.price = price;
    this.description = description;
    this.consistOf = consistOf;
    this.volumeValue = volumeValue;
    this.volumeTitle = volumeTitle;
}

@Override
public String toString() {
    return "MenuItem [id=" + id + ", title=" + title + ", engTitle="
            + engTitle + ", price=" + price + ", description="
            + description + ", consistOf=" + consistOf + ", volumeValue="
            + volumeValue + ", volumeTitle=" + volumeTitle + ", categoryId=" + categoryId + "]";
}

public String getEngTitle() {
    return engTitle;
}

public void setEngTitle(String engTitle) {
    this.engTitle = engTitle;
}

public void setId(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getConsistOf() {
    return consistOf;
}

public void setConsistOf(String consistOf) {
    this.consistOf = consistOf;
}

public double getVolumeValue() {
    return volumeValue;
}

public void setVolumeValue(double volumeValue) {
    this.volumeValue = volumeValue;
}

public String getVolumeTitle() {
    return volumeTitle;
}

public void setVolumeTitle(String volumeTitle) {
    this.volumeTitle = volumeTitle;
}

@JsonBackReference
@JsonIgnore
public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}

public void setCategoryId(int categoryId) {
    this.categoryId = categoryId;
}

}
This is my root context:
<beans:bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:array>
                <beans:bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <beans:property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
                </beans:bean>
            </beans:array>
        </beans:property>
    </beans:bean>

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!-- Configure to plugin JSON as request and response in method handler -->
    <beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

    <mvc:interceptors>
        <beans:bean class="ru.tenet.cafe.interceptor.LoginInterceptor" />
    </mvc:interceptors>

    <context:component-scan base-package="ru.tenet.cafe" />

    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <beans:bean id="dataSourceMain" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <beans:property name="driverClass" value="org.postgresql.Driver" />
        <beans:property name="jdbcUrl"
            value="jdbc:postgresql://192.168.101.158:5432/cafe" />
        <beans:property name="user" value="postgres" />
        <beans:property name="password" value="123" />
        <beans:property name="minPoolSize" value="5" />
        <beans:property name="maxPoolSize" value="8" />
        <beans:property name="preferredTestQuery" value="SELECT 1" />
        <beans:property name="acquireIncrement" value="1" />
        <beans:property name="idleConnectionTestPeriod" value="100" />
        <beans:property name="maxStatements" value="0" />
        <beans:property name="checkoutTimeout" value="60000" />
    </beans:bean>

    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSourceMain" />
        <beans:property name="configLocation">
            <beans:value>/WEB-INF/db/hibernate.cfg.xml</beans:value>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.connection.characterEncoding">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.charSet">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.useUnicode">true</beans:prop>
                <beans:prop key="hibernate.show_sql">false</beans:prop>
            </beans:props>
        </beans:property>

    </beans:bean>

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

This is my controller:
@RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
            @RequestBody MenuItem menuItem) {
        menuService.create(menuItem);
        return new ResponseEntity<String>(HttpStatus.OK);

    }

But if I send POST request with the following body
{
   "title":"Пепперони",
   "engTitle":"Pepperoni",
   "price":300,
   "description":"Сами лючщи пица слющи. Тольки щто привезли дарагой.",
   "consistOf":"E666, стальная стружка, вода (без ГМО)",
   "volumeValue":500,
   "volumeTitle":"г",
   "categoryId":38
}

I will get:

415 The server refused this request because the request entity is in a
  format not supported by the requested resource for the requested
  method.

What the hell?

A: let's start with a little definition :

415 Unsupported Media Type
The request entity has a media type which
the server or resource does not support. For example, the client
uploads an image as image/svg+xml, but the server requires that images
use a different format.

Which can be solved by :
@RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json; charset=UTF-8", consumes = "application/json; charset=UTF-8")

Explanation : Basically you need to specify what kind of data your endpoint is going to consume / produce. Don't forget when sending the request to specify the header
Content-Type: application/json

A: Your current controller must be replaced with the following code:
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<String> create() {
    MenuItem menuItem = null;
    menuService.create(menuItem); // Fill in the menuItem
    // Now respond
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(menuItem, responseHeaders, HttpStatus.OK);
}


text:
Q: iOS Identifying views in ObjC and Swift What is the best practice to identify views in iOS?
For instance, you could have a lot of views that aren't worth subclassing because you need to work with just one subview in those views.
I like to use view tags, and for easy identification I would do like so for ObjC:
enum {
    kViewTagSomeButton = 10,
    kViewTagSomeOtherButton,
}

But to do this in Swift, this becomes quite verbose:
enum ViewTag: Int {
    case SomeButton = 10, SomeOtherButton, ...
}

if view.tag == ViewTag.SomeButton.rawValue {
    // Do something
}

Or should I use a completely different approach?
Edited
Changed the whole question to a more appropriate context


text:
Q: Windows 8: docking/snapping windows to more than left or right Anybody know of a program that'll allow me to dock windows (non-metro apps) to more than just the left or right of the desktop?
I have a 27 inch 1440p monitor that I bought with the idea of being able to work on simultaneous things on the screen (I prefer this to having multiple monitors). It'd be great if when I was working with 3 windows I could maybe snap one to the left, then have the remaining ones take up the vertical space remaining on the right equally.
I can obviously do this by grabbing each window and resizing/moving as necessary, but it's not very convenient.
What I had in mind was something like what you have when developing software with WPF on .Net where you can continuously dock controls to either left, top, right, bottom and each control is arranged according to remaining space in the dock panel.

A: You can exercise fine control over the location of your windows with WinSplit Revolution. After it is installed, move windows around with Ctrl+Alt+Numpad.
WinSplit uses a system where pressing the same button more then one time allows you to adjust the size in the position you have chosen, so pressing Ctrl+Alt+4 one time would move the window to the  left side of your screen at 50% size, and pressing Ctrl+Alt+4 twice would move it to the left 33%. This is all adjustable. (Right click the icon → choose layout settings)
To get the windows in the specific example you describe, you would

*

*Select the left window and press Ctrl+Alt+4 twice

*Select the middle window and press Ctrl+Alt+5 twice

*Select the right window and press Ctrl+Alt+6 twice

The end result:


text:
Q: compiling issue with netBeans 11.2 NetBeans is giving me so much headaches, i need to set it up for my lab class, the issue is if i download and re-install it, it will build for the first time, but then it wont run, then after the first time i built, it wont let me built anymore, ive been doing alot of research, some saying that it could be the MinGW packages, but i downloaded all the basic MinGW packages, seems like the same issue occurs. please help
cd 'C:\Netb\Lab_1'
C:\MinGW\msys\1.0\bin\make.exe -f Makefile CONF=Debug
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Netb/Lab_1'
"/C/MinGW/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW_1-Windows/lab_1.exe
make.exe[2]: Entering directory `/c/Netb/Lab_1'
mkdir -p dist/Debug/MinGW_1-Windows
gcc     -o dist/Debug/MinGW_1-Windows/lab_1 build/Debug/MinGW_1-Windows/main.o
c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot open output file dist/Debug/MinGW_1-Windows/lab_1.exe: Permission denied
collect2.exe: error: ld returned 1 exit status
make.exe[2]: *** [dist/Debug/MinGW_1-Windows/lab_1.exe] Error 1
make.exe[2]: Leaving directory `/c/Netb/Lab_1'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/Netb/Lab_1'
make.exe": *** [.build-impl] Error 2


text:
Q: Present & Remove XIB as UIView over KeyWindow I'm presenting a Xib over the KeyWindow as my custom alert view.
The problem I'm having is that when I present the view again (after it's been removed from superview), the button's that had targets to them still have their old actions assigned to them. So when a button is tapped, it performs it's new action and the old one.
Aside from setting up code to .removeTarget(nil, action: nil, for: .allEvents) from the buttons. Why are the buttons not being presented fresh when the view get's added to subview a new time?
Code in the app delegate:
let AlertScreen = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert

    func ShowAlert (LeftButton: String, RightButton: String) {

        AlertScreen.frame = UIScreen.main.bounds
        AlertScreen.LeftButton.setTitle(LeftButton, for: .normal)
        AlertScreen.RightButton.setTitle(RightButton, for: .normal)
        UIApplication.shared.keyWindow?.addSubview(AlertScreen)

    }

Then in whatever view controller I require the alert view to show over, I simply show the alert, then I assign an action such as:
AlertScreen.RightButton.addTarget(self, action: #selector(LoadItems), for: .touchUpInside)

A: You only create the view once using:
let AlertScreen = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert

You are presenting the save view over and over again. If you want to fresh views, you need to create a new view every time you present it.
var currentAlert: Alert?

func showAlert (LeftButton: String, RightButton: String) {

    removeAlert()
    currentAlert = Bundle.main.loadNibNamed("Alert", owner: nil, options: nil)?.last as! Alert
    currentAlert.frame = UIScreen.main.bounds
    currentAlert.LeftButton.setTitle(LeftButton, for: .normal)
    currentAlert.RightButton.setTitle(RightButton, for: .normal)
    UIApplication.shared.keyWindow?.addSubview(currentAlert)

}

func removeAlert() {
    currentAlert?.removeFromSuperView()
    currentAlert = nil
}


text:
Q: Dimensionality reduction: Feature Selection or Feature Extraction? Case:
I have a dataset with a large number of features, which I want to reduce. Should I look for a method that identifies the most important ones and throw away the rest, or should I look for a method that attempts to create a smaller number of new features from the old ones?
Which method of dimensionality reduction is more common in practice: feature selection or feature extraction? Is one superior to the other? How should I know which one to prefer? Finally, is there any benefit in combining the two?

A: It depends on the situation and objective, however in general it is preferable to retain your original variables as these can be more easily interpreted. There is no better option between the two as it depends entirely on the problem at hand.
Combining the two is unnecessary and you should pick one. And this is about as much that can be said given the details that you've given us.


text:
Q: What can I do so my jupyter notebook will work properly? I recently updated my windows10 and after that my jupyter notebook is not functioning properly. I tried to import sklearn.datasets but it gave an error like
HTTP Error 429: Too Many Requests

this one just after one time execution.
And also I am unable to get an option of run as administrator here. What should I do?
I tried updating anaconda navigator. Opening jupyter through command prompt. Launching through navigator power shell. But its not working.


text:
Q: Zend framework 1: form validation of two related fields My ZF1-form has fieldland and fieldnumber which are related to each other and i need to check that either both or none are filled. How to do this validation? In ZF1 forms have no method setValidatorGroup. So is there an alternative?
The form is defined in a xml, so fielddefinition looks like:
    <klant_mobiel_land>
        <type>text</type>
        <options>
            <label>Mobiel landcode, abonneenummer:</label>
            <maxlength>5</maxlength>
            <size>5</size>
            <validators>
                <telefoonnummerlandcodecinco>
                   <validator>TelefoonnummerLandcodeCinco</validator>
                </telefoonnummerlandcodecinco>
            </validators>
        </options>
    </klant_mobiel_land>
    <klant_mobiel_nummer>
        <type>text</type>
        <options>
            <maxlength>10</maxlength>
            <size>15</size>
        </options>
    </klant_mobiel_nummer>

I expect to need a validationgroup, first of all, is that on option? And second, how should that be defined in xml? Something like this perhaps:
  <validationgroups>
        <mobilephone_group>
            <elements>
                <klant_mobiel_nr>klant_mobiel_nummer</klant_mobiel_nr>
                <klant_mobiel_land>klant_mobiel_land</klant_mobiel_land>
            </elements>
            <validators>
                <neitherorbothfields>
                    <validator>neitherorbothfields</validator>
                </neitherorbothfields>
            </validators>
        </mobilephone_group>
    </validationgroups>

And the validator itself, how should it get the two values passed to it? Something like this perhaps:
class Zend_Validate_NeitherOrBothFields extends Zend_Validate_Abstract
{
     public function isValid($value, $context = null)
    {
        if (mytestToSeeIfNeitherOrBothAreFilled) {
            $this->_error('Only one of the two fields has been filled, fill either none or both', $value);
            return false;
        };
        return true;
    }

Best regards, Tim van Steenbergen, tieka.nl

A: Typically, the validator uses the optional $context var, precisely as you have indicated above. But you will attach the validator to a single field (so any validation failures will also be attached to that field).
The standard example is a registration form that solicits a password value and a confirm_password value. The validator could be attached to the password field and the validator's isValid($value, $context = null) method would compare $value to $context['confirm_password']. A failure would then set an error on the password field which would then be referenced in the view-script or the form-decorators.

A: You can have you custom validator, and use the 2nd parameter available to isValid to have other post fields something like following:
class Zend_Validate_NeitherOrBothFields  extends Zend_Validate_Abstract
{
    public function isValid($value, $context = NULL) {
       // in $context you will have all data from post which you can use to validate and do the stuffs you want and the end you can set the error message and return true/false
        if ($context['password'] !== $context['confirm_password']) {
            $this->_error('some message');
            return false;
        }
        return true;
    }
}

Then in your Zend Form just bind this validator to one of your field (say just to password)


text:
Q: Slicing the vector in R The authour just wrote:
" The way we extract the rest of a vector by slicing will make R copy that subvector. The first time we call rest, we get the entire vector minus the first element, the second time we get the entire vector minus the first two, and so on. This adds up to about half the length of the vector squared. So while the search algorithm should be run in linear time, the way we extract the rest of a vector makes it run in quadratic time" (Functional Programming in R
Advanced Statistical Programming for Data Science, Analysis and Finance)
Can you help me to understand why while implementing the rest function every time the vector lessen by 1?
The example code is below:
lin_search <- function(element, sequence) {
  if (is_empty(sequence)) FALSE
  else if (first(sequence) == element) TRUE
  else lin_search(element, rest(sequence))
}

  is_empty <- function(x) length(x) == 0
  first <- function(x) x[1]

  rest <- function(x) {
  if (length(x) == 1) NULL else x[2:length(x)]
   }


text:
Q: Need to replace DevExpress Bootstrap for ASP.NET Core in project. Solution from experience? Rewrite with different framework like Vue? Smthn else? We need to get rid of DevExpress Bootstrap Controls for ASP.NET Core from project.
What would be the easiest/cheapest/feastet solution?
To simply rewrite everything with a different framework like Angular/Vue/React?
Maybe there is a known framework/method of migrating to DevExpress ASP.NET Core Controls? Or to something else?

A: How many controls were used from DevExpress?
If you only used a few controls, then you only need a few replacements.
I would not call purchase of some controls from DevExpress a whole "framework", but that of only purchasing some controls to use with your project.
So, does the project use 3-5 or 50 of those DevExpress controls? (by using, I mean DIFFERENT kinds of controls).
If you only used a few, say like their GridView, then you would only need to find a replacement for their gridview control, or simply use the built-in one, and fancy it up with some css, and addtional options. (I would make a user control).
So, you want to determine what the controls used did, how many different controls were used, and then find some controls that have a great look and feel that you like.
Their grid controls are VERY nice, since they have some "really" nice filter options for the header of that grid control.
So, you need to find some control replacements, but how many did the project use will quite much determine scope here.
So, in place of say their tab control, then consider using the jQuery one. As noted, I would wrap say the jQuery.UI tab control into a user control, so then you can just drag + drop in that jQuery.UI "tab" control in place of the devExpress one.
Same goes for the multi-select combo box (dropdown list).
So, either you cobbile together some replacements of your own, or you find some replacemetns, or you buy some more controls from another vendor.
The challenge and issue will of course be that each of their controls has a specific object and event model.
However, that's not really any different then say if you started used sweet-alert, and now want to replace sweet-alert say with some jQuery.UI dialogs.
I would say that the real challenge of replacing their controls is often not so much finding a replacement, but finding something that has a great look and feel. The main huge wonderful bonus of the devExpress controls tends to be their look and feel. In other words, they had someone with REALLY good taste in terms of look and feel.
I mean, for years I used the ajaxtoolkit. (free, open source). it was and still remains a fantastic set of controls. The pop dialog, the tab control, the multi-select combo box, the HTML editor?
They are all great, but their HUGE downside is not the features, but the controls from that free toolkit look like something from the 1980's!!!
The popular jQuery.UI? Same thing, the controls look ugly and something designed by a un-employed rodeo clown living in a trailer park.
There is a HUGE but BEYOND huge reason that bootstap is so popular.
Know the answer?
Why of course bootstrap is popular for ONE big HUGE massive SIMPLE reason:
Bootstrap has a fantastic look + feel. (zero other reasons for bootstrap being popular!!).
If you ever hired a graphic artist to re-work the look and feel of your web site? Guess what? Their resulting work and suggestions will look like the default of bootstrap!!!
So, someone in the print and graphic design industry or someone with VERY good talent and great taste created the bootstrap system. So, when you use bootstrap, then you get fantastic looking results, results that normally would take a full time graphic artist on your staff.
Regardless, we are wondering off topic here.
The main issue you have to determine is how many controls were used from devExpress. Most of their controls do follow a similar object model as the base controls found in asp.net webform controls.
So, for example, jQuery.UI controls has a great set of features (a great set of UI components), but they look way too dated and old fashioned.
The issue you have is not that you want to replace some of the devExpress controls you used, but how much work it would be to replace say a dev-express "gridview" with another different grid control. Every single one of those controls used will not only require you to spend HUGE amounts of time finding a replacement, but I think the LARGER issue is finding something that don't look like it was created by someone living in mom's basement, or by that drunken un-employed rodeo clown that does not belong in our industry.
your issue is not finding some replacement controls, your issue is how much code  and money (time and resources) you have available to replace those controls.
You can no more change a bunch of code in c# to then using say client side JavaScript can then you take some Pascal code, and covert that code to vb.net code.
There no more a replacement for those controls from dev-express then there is deciding tomorrow to re-write some server side code in vb.net to now being client side JavaScript code.
In fact, what I am quite much telling you?
How the computer and IT industry has worked for 50+ years has NOT change one bit, and it not change one bit if you decide to rip out some existing controls and replace them with different controls.
Its possible you are asking for something you never seen, never heard of, and thus are imagining some magic wand here, but those don't exist in our industry either, do they?
As I noted, for quite some time, I used the AjaxToolKit. Turns out that jQuery.UI has near EVERY the same kind of controls available. But, the massive difference is jQuery.UI controls are client side ones, but worse yet, they don't work the same as the AjaxToolKit ones. In other words, there is a nice "tab" control in AjaxToolkit, and there is a nice tab control in jQuery.UI. So, they both are  tab control, but THEY are VAST different in their operations, how you use them, how they work.
However, both the jQuery.UI and the AjaxToolkit tab control?
My gosh, do they look like crap.
At least the jQuery.UI one can be easy bootstrapped styled.
Again, note how we not really now back to a JUST having a control replacement, but one that looks VERY nice and VERY tasteful out of the box, and a control that should take zero efforts on your part to obtain that great look and feel.
Want to know what product has those great looking controls and great look and feel out of the box?
the DevExpress ones!!!


text:
Q: SourceTree Terminal not working properly I'm using Windows 10, SourceTree
and Git .
When i want to Switch branch by using the SourceTree terminal it shows :

error: pathspec '3.Building-the-API-Implementing-Basic-Requirements'
  did not match any file(s) known to git.

But if i execute same command from Git Bash in my project directory, it works fine.

Why the SourceTree terminal is not working ? Is there any issue to work SourceTree terminal ?

A: For the record, I just found out that the Git 2.31 update on SourceTree 3.3.4 Windows causes this very issue, either if you're using the embedded or system Git, and can be fixed by reverting to Git 2.30.2, either configuration.

A: I, too, have Git 2.31.1 installed in the System and using it as my Sourcetree's Git version (not Embedded).
Alternatively, without reinstalling Sourcetree:

*

*Go to Tools > Options > Git.

*Uncheck/disable Use Git Bash as default terminal..

*Restart Sourcetree (optional).

*Clicking on the Terminal now will launch a Terminal/Command-line in the repository's home directory.

In some cases, depending on your Git's and Sourcetree's configuration and add-ons, you can also do this after Step 4 above.

*Go back to Tools > Options > Git.

*Check/Enable Use Git Bash as default terminal..

*Restart Sourcetree (optional).

*Clicking on the Terminal now could launch Git Bash.

A: I solved this issue by re-install (uninstall and install) SourceTree. So i think my installed SourceTree was corrupted somehow.


text:
Q: How to set new borders with oxyplot forn a UWP? I got a problem with the borders of my x-axis.
As you can see in the pictures I´m working with a CalenderDatePicker.
Process: User chooses two dates. As soon as he chooses the dates the borders of the x-axis change and you see a period of time as the new borders.

A: Actually, if you check the oxyplot document, you will know how to update the plot.

To update the plot, you must do one of the following alternatives:
Change the Model property of the PlotView control
Call Invalidate on the PlotView control
Call Invalidate on the PlotModel

I've made a simple code sample for your reference:
xmlns:oxy="using:OxyPlot.Windows"

<Page.DataContext>
    <local:MainViewModel/>
</Page.DataContext>
<Grid>
    <oxy:PlotView Model="{Binding MyModel}" x:Name="oxyplot"/>
    <Button Content="reset" Click="Button_Click"></Button>
</Grid>

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        oxyplot.Model.Axes[0].Minimum = 20;
        oxyplot.InvalidatePlot();
        oxyplot.Model.InvalidatePlot(true);
    }
}

public class MainViewModel
{
    public MainViewModel()
    {
        this.MyModel = new PlotModel { Title = "Example 1" };
        this.MyModel.Axes.Add(new LinearAxis() { Minimum = 10, Maximum = 100, Position = AxisPosition.Bottom });
    }

    public PlotModel MyModel { get; private set; }
}


text:
Q: Overriding functions that takes inherited structures struct struct1
{};
struct struct2:public struct1
{};
class Base
{
public:
    virtual void foo(struct1 *s)
    {
        cout<<"foo in Base"<<endl;
    }
};
class Der:public Base
{
public:
    virtual void foo(struct2 *s)
    {
        cout<<"Foo in Der"<<endl;
    }
};
int main()
{
    struct2 s;
    Base *b = new Der();
    b->foo(&s);
}

When I call the function in main It calls the member in Base."foo in Base" gets printed. It prints "foo in Der" when the Derived class function takes struct1 pointer. But Is there any way to make it take struct2 pointer and display "foo in Der"

A: What you are asking for, interpreting that you mean to override the behavior of Base::foo, would be co-variant arguments to the function, and that is not possible in OO, as the derived type would be narrowing the contract of the base type, and thus it would break the Liskov Substitution Principle. You would not be able to substitute an object of type Base with an object of type Der, as the latter does not accept a struct1 object that is not a struct2 object.
When the derived type function has the same signature (i.e. also takes a struct1*), then it overrides the behavior of the Base and dynamic dispatch kicks in. But when you the signature has struct2* it does not override but rather hides the Base function.


text:
Q: How to change Window's RTL text cursor icon? Is it possible to change the text cursor icons in Windows 10?
Specifically, I want to change the RTL text cursor icon because it resembles the LTR icon too much, making it difficult to notice if you are in RTL or LTR mode.
LTR text cursor:

RTL text cursor:


text:
Q: PsExec running PowerShell cmdlets with spaces in the arguments I'm attempting to use PsExec to run Expand-Archive on a remote computer, extracting to a folder inside Program Files, but Expand-Archive keeps returning the error:
Expand-Archive : A positional parameter cannot be found that accepts argument 'Files\Folder'

I take this to mean that Expand-Archive gets to the space in "Program Files" and thinks one argument is done and starts trying to interpret the next.
I have used the following variants of the command, all with the same outcome:
Double-quotes around entire Powershell portion, using %programfiles% environment variable:
.\PsExec.exe \\computername /s cmd /c "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command expand-archive c:\temp\bc.zip -destinationpath %programfiles%\Folder"

Single-quotes just around the destination folder path, using %programfiles% environment variable:
.\PsExec.exe \\computername /s cmd /c C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command expand-archive c:\temp\bc.zip -destinationpath '%programfiles%\Folder'

Double-quotes just around the destination folder path, using %programfiles% environment variable:
.\PsExec.exe \\computername /s cmd /c C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command expand-archive c:\temp\bc.zip -destinationpath "%programfiles%\Folder"

No quotes, using %programfiles% environment variable:
.\PsExec.exe \\computername /s cmd /c C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command expand-archive c:\temp\bc.zip -destinationpath %programfiles%\Folder

Double-quotes around fully typed folder path:
.\PsExec.exe \\computername /s cmd /c C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command expand-archive c:\temp\bc.zip -destinationpath "C:\Program Files\Folder"

A: I have tried doing the same with psexec, and i'm facing all kinds of errors.
I would personally use powershell's invoke command. Would this also work for you? If not i will try to fiddle with psexec some more if you would like.
Example :
$PATH = "EnterPath"
$COMPUTERNAME = "EnterComputerName"
Invoke-Command -ComputerName $COMPUTERNAME -ScriptBlock {
    $DESTINATIONPATH = $env:ProgramFiles
    Expand-Archive -Path $using:PATH -DestinationPath $DESTINATIONPATH

}
The script will run on given computer, $env:ProgramFiles translates to the variable on the remote computer, equivalent of %programfiles% in cmd.

A: I wouldn't say that the accepted answer is not correct, but rather it's not targeting the actual issue in my opinion.
Here there's not any issue with PSExec, but issue with how the PowerShell command is called.
When calling Powershell command many a times we cannot just pass commands without quotes, especially those commands that need quoted arguments like spaced-paths of OS directory structure. So we have to apply ampersand & before command when calling the command and escape the command's inner quotes for arguments, which pretty much looks like this:
powershell "& Expand-Archive \"<filepathwithspaces>\" \"<targetfolderpathwithspaces>\""

OR
.\PsExec.exe \\computername /s cmd /c C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command "& expand-archive c:\temp\bc.zip -destinationpath \"C:\Program Files\Folder\""

You can also ignore the -command switch in the above one-liner as long as you provide & properly before actual command :)


text:
Q: TortoiseSVN could not begin a transaction I have just created an svn repository on a remote secure server (You need a user name and a password to access it) using puTTY:
svnadmin create repo_name

Then, I created a working copy using the import command, and pointing to the repository. The working copy then shows up, obviously completely empty besides the .svn folder.
Now, I want to create the structure, adding the branches, tags, and trunk folder. However, when I open the Repo-browser and try to create a new folder I end up with this error:

How do I fix this?

A: You should check the logs on the server side. Most likely, there is a problem with permissions. See this post https://serverfault.com/questions/625579/svn-cant-open-file-var-www-svn-repo-db-txn-current-lock-permission-denied

A: Please check if there is enough space in SVN Server. This is space issue only.

A: *

*svn import does not create Working Copy, just add revision into repository from a set of unversioned files

*Even after you created repository with svnadmin create this repository have to be accessible with any possible transport (and you have to know URL|protocol)
If you used local access (with file:///) you have to check ownership and permissions of all objects in repository (as files and folders)… and .svn subdir isn't repository

You have to write more technical details if you want to get help here


text:
Q: JSF EL 2.2. parameter binding Since EL version 2.2, the following value expression is allowed:
<h:outputText value="#{entry.getRow(column)}" />

Where column would be another variable. Eventually, what seemed to work so well on an outputText, I would like to reuse on an inputText:
<h:inputText value="#{entry.setRow(column)}" />

"setRow" is defined as follows:
public void setRow(String columnName, String content) {
    // ...
}

My question is: Does that work? Or rather, I know that doesn't work, since I'm getting an error about how the requested "setRow" method does not exist. So, does what I am trying to do here work in general - and if so, how can it be done?
Thanks for any feedback and best regards
Pascal

A: That's indeed not a valid expression for a "set" operation. The value expression has to be a fullworthy bean property expression, but you're having there a bean method expression.
You can achieve the particular functional requirement using a Map instead.
private Map<String, String> columns = new HashMap<String, String>();

public Map<String, String> getColumns() {
    return columns;
}

with
<h:inputText value="#{bean.columns[column]}" />

On form submit, EL will use Map#put() method to set the value (hence, no setter required for the map) which will then be available in the action method by iterating over the map entries.


text:
Q: Slow performance bulk updating relationship property in Neo4j I would like to efficiently update property on all relationships in my path.
MATCH (u:UserNode {userId: $userId})<-[r:PARENT_OF*1..]-(parent:UserNode {userId: $parentId})
FOREACH (r IN relationships(p) | SET r.numberProperty = r.numberProperty + $number)
RETURN 1

Problem is that this query takes about 1600ms for 670 relationships.
I expect to have tens of thousands of relationship I will need to update in bulk and it's critical for me that this update takes tens / lower hundreds of milliseconds.
Simply finding the path without updating takes about 60ms, so the problem lies in update itself
MATCH (u:UserNode {userId: $userId})<-[r:PARENT_OF*1..]-(parent:UserNode {userId: $parentId})

I already tried using apoc.periodic.iterate like this
CALL apoc.periodic.iterate(
  "MATCH (u:UserNode {userId: $userId})<-[r:PARENT_OF*1..]-(parent:UserNode {userId: $parentId}) RETURN r",
  "SET r.numberProperty = r.numberProperty + $number",
  {batchSize: 100, parallel: true, params: {userId: $userId, number: \$number}}
)
YIELD batch
RETURN 1

hoping it would update it in parallel and make it faster, but it is even slower than the first query.


text:
Q: Python pydantic model passing None as int value is not a valid integer (type=type_error.integer) I have a model which takes a few inputs including a sourceSiteId. This is an integer but also has many values as None. I have tried a few things with the model but still receive an error of value is not a valid integer (type=type_error.integer) when the value is None. Below is my model.
class LatLongModel(BaseModel):
    # id: str
    object_id: Optional[int] = None
    primo_id: Optional[int] = None
    name: Optional[str] = None
    entity_type: Optional[str] = None
    division_id: Optional[int] = None
    division: Optional[str] = None
    status: Optional[str] = None
    longitude: Optional[float] = None
    latitude: Optional[float] = None
    site_id: Optional[int] = None
    source_site_id: Optional[int] = None
    site_type: Optional[str] = None

I have also tried to do source_site_id: int = None and source_site_id: Optional[int] but no luck. What can I try to get this model to accept integers as well as None type for source_site_id?

A: Some background, a field type int will try to coerce the value of None (or whatever you pass in) as an int. You can override this behavior by including a custom validator:
from typing import Optional
from pydantic import BaseModel, validator

class LatLongModel(BaseModel):
    # id: str
    object_id: Optional[int] = None
    primo_id: Optional[int] = None
    name: Optional[str] = None
    entity_type: Optional[str] = None
    division_id: Optional[int] = None
    division: Optional[str] = None
    status: Optional[str] = None
    longitude: Optional[float] = None
    latitude: Optional[float] = None
    site_id: Optional[int] = None
    source_site_id: Optional[int] = None
    site_type: Optional[str] = None

    # Custom validator here
    @validator('site_id', 'source_site_id', pre=True)
    def allow_none(cls, v):
        if v is None:
             return None
        else:
            return v

A: You could try to find the issue by defining a __new__ method in your model. It might help you catch the problematic value(s) (empty string or something else) :
class LatLongModel(BaseModel):

    def __new__(cls, *args, **kwargs):
        for k,v in kwargs.items():
            print(f"'{k}' : {v.__repr__()} ({type(v)})")
        return super().__new__(cls)

    # [...]
    source_site_id: Optional[int] = None

l = LatLongModel(source_site_id="")

> 'source_site_id' : '' (<class 'str'>)
> Stacktrace [...] pydantic.error_wrappers.ValidationError: 1 validation error for LatLongModel
source_site_id
  value is not a valid integer (type=type_error.integer)


text:
Q: How to update two tables with foreign key I would like to insert into database new customer.
 To do that I have to put in table CLIENT FirstName, LastName, Postcode. To second table CLIENTGROUP I have to put customer group, like Visitor or VIP. First Tables Id is foreign key in second.
When I put a new customer in CLIENT id is increased automatically. How to make a query that would updated id in CLIENTGROUP?
I will have to join two query
        var connection = OpenConnection();
        var command = connection.CreateCommand();
        command.CommandText = "insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode)";
        AddParameterString(command, "@FirstName", model.FirstName);
        AddParameterString(command, "@LastName", model.LastName);
        AddParameterDecimal(command, "@Turnover", model.Postcode);

        command.ExecuteNonQuery();

        command.CommandText = "insert into ClientGroup (ClientGroup) values (@ClientGroup)";
        AddParameterString(command, "@ClientGroup", model.ClienGroup);"
        command.ExecuteNonQuery();

but I simply have no Idea how.

A: Add SELECT SCOPE_IDENTITY() to the first insert query, that would give you id of inserted customer. Use ExecuteScalar method on c# side (if you use ADO.NET). Query:
INSERT INTO Customer (/*...*/) VALUES (/*...*/)
SELECT SCOPE_IDENTITY()

c#:
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = @"
    insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode)
    SELECT SCOPE_IDENTITY()";

AddParameterString(command, "@FirstName", model.FirstName);
AddParameterString(command, "@LastName", model.LastName);
AddParameterDecimal(command, "@Turnover", model.Postcode);

int customerId = (int) command.ExecuteNonQuery();

// ...use customerId in the second insert

You might also consider wrapping these two insert queries with transaction.

A: Your code will look like this. Also assuming ClientId is the name of your primary key column . Also set auto increment off for your foreign key (in ClientGroup table).
    var connection = OpenConnection();
    var command = connection.CreateCommand();
    command.CommandText = "insert into Klient(FirstName,LastName,Postcode) values (@FirstName, @LastName, @Postcode) Select Ident_Current('Klient')";
    AddParameterString(command, "@FirstName", model.FirstName);
    AddParameterString(command, "@LastName", model.LastName);
    AddParameterDecimal(command, "@Turnover", model.Postcode);

    int foreignKey = command.ExecuteScaler();

    command.CommandText = "insert into ClientGroup (ClientId,ClientGroup) values (@ClientId, @ClientGroup)";
    AddParameterString(command, "@ClientId", foreignKey);
    AddParameterString(command, "@ClientGroup", model.ClienGroup);
    command.ExecuteNonQuery();


text:
Q: Trouble configuring custom folder for site (Apache) I'm trying to configure httpd on fedora, but my two day effort has gotten me nowhere.
I installed httpd and php, added the configuration file for the site, everything is fine. I try to load it and see "access denied." but I have already granted to the apache user and apache group 755 rights (on every folder along the path).
Errors in apache log:

[Mon Jun 06 20:25:18.088420 2022] [negotiation:error] [pid 12656:tid
12758] (13)Permission denied: [client 127.0.0.1:45920] AH00686: cannot
read directory for multi: /home/concasse_master/Desktop/sample/public/
[Mon Jun 06 20:25:18.089421 2022] [proxy_fcgi:error] [pid 12656:tid
12758] [client 127.0.0.1:45920] AH01071: Got error 'Unable to open
primary script: /home/concasse_master/Desktop/sample/public/index.php
(Permission denied)'

localhost.conf:
<VirtualHost *:8080>
    ServerName localhost
    DocumentRoot /home/concasse_master/Desktop/sample/public
    ErrorLog logs/error.log
    CustomLog logs/access.log combined
    <Directory /home/concasse_master/Desktop/sample/public/>
       Options Indexes FollowSymLinks MultiViews
       AllowOverride All
       Require all granted
    </Directory>
</VirtualHost>