text:
Q: The production mode ruby app doesn't run, unicorn and nginx I'm going to deploy my ruby on rails app on my own server. So i decided to follow this tutorial that is from degital ocean:
https://www.digitalocean.com/community/tutorials/how-to-deploy-a-rails-app-with-unicorn-and-nginx-on-ubuntu-14-04
I configured my database.yml which i add host:localhost and configured rben-var in my app directory and Migrate the production database very well.
I couldn't start the rails with this command
RAILS_ENV=production rails server
And i thought maybe it is because of my last time that I set the unicorn as default for my another app(you know i have two other app which i deploy them on the server well but i removed their path from the nginx)
then I create config/unicorn.rb
finally when I started
sudo vi /etc/init.d/unicorn_drug it gives me  this error:
master failed to start, check stderr log for details

When i see the log which Is in /shared/log/unicorn.stderr.log i see following error lines.
You know i spend two days on this case but I really can't understand what is the error is:
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:129:in `start'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `load'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `<top (required)>'
I, [2017-02-27T13:38:21.860366 #1848]  INFO -- : Refreshing Gem list
NameError: uninitialized constant RegistrationController
  /root/drug_api/app/controllers/RegistrationController/confirmations_controller.rb:1:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies/interlock.rb:12:in `block in loading'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/concurrency/share_lock.rb:150:in `exclusive'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-5.0.1/lib/active_support/dependencies/interlock.rb:11:in `loading'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:476:in `block (2 levels) in eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:475:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:475:in `block in eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:473:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:473:in `eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/engine.rb:354:in `eager_load!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application/finisher.rb:59:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `instance_exec'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:30:in `run'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/initializable.rb:54:in `run_initializers'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-5.0.1/lib/rails/application.rb:352:in `initialize!'
  /root/drug_api/config/environment.rb:5:in `<top (required)>'
  config.ru:4:in `require_relative'
  config.ru:4:in `block in <main>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'
  config.ru:1:in `new'
  config.ru:1:in `<main>'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `eval'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `block in builder'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `call'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:129:in `start'
  /root/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `load'
  /root/.rbenv/versions/2.2.3/bin/unicorn:23:in `<top (required)>'

A: The problem is uninitialized constant RegistrationController, your  RegistrationController is missing. Also seems that you have named directory to RegistrationController and under that you have placed confirmation_controller. Rename the directory to registration_controller, cause you can not name path or directory with first letter capital, that is only for class name.
Check line no. 8 of your error log:
NameError: uninitialized constant RegistrationController
  /root/drug_api/app/controllers/RegistrationController/confirmations_controller.rb:1:in `<top (required)>'


text:
Q: Using VUEX necessary with NODE.js REST Backend I´m not very experienced with Frontend/Backend Architecture, but i created a simple REST Backend with NODE.js and want to build up a Frontend based on Vue.js and Framework7.
So do you recommend using VUEX there? Or how do you deal with the sessions or the different requests you sending to the Backend?
Thanks a lot!

A: You don't have to use Vuex, but I'd suggest using Vuex. Here's an example using Vuex and rest api.
In store/actions.js
import {
  fetchSomething,
} from '../api/index.js';

export const actions = {

  getSomething({ commit }) {
    fetchSomething().then((something) => {
      commit('UPATED_SOMETHING', something);
    });
  },

}

In api/index.js
export const fetchSomething = () => {

  const url = 'Some endpoint';

  return new Promise((resolve) => {
    axios.get(url).then((res) => {
      const data = res.data;
      resolve(data);
    }).catch((err) => {
      console.log(err);
    })
  })

}

In store/mutations.js
export const mutations = {

  UPATED_SOMETHING(state, data) {
   state.something = data;
  },
}

In store/index.js
import { getters } from './getters'
import { actions } from './actions'
import { mutations } from './mutations'

// initial state
const state = {
  something: null,
}

export default {
  state,
  getters,
  actions,
  mutations,
}

In store/getters.js
export const getters = {

  getSomething: state => {
    return state.something;
  },

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve selected row from a WPF DATAGRID to DataTable I want to retrieve a single selected DataGrid row to a DataTable, i have tried below code but it is not working please help me.
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = gd.SelectedItem as DataRowView;
OrignalSelectedRow.Rows.Add(rowSelected);

Please don't mess it with duplicate as i have tried different solution. And tried suggestion answer. But i got another problem.


text:
Q: Custom function never called I was trying to implement a exclude button for the multi_select filter_type, using multi_select_custom_func. I also tried custom_funcp. The problem is the custom function is never called. I'm sure it is in the scope of yadcf since I do a call right before the initialization to test it.
I would like to use this with server-side data retrieval (for both the table and the select boxes) and AJAX pagination so if there are any other tip to consider please let me know.
I can't reproduce the issue on a snippet since it requires server side loading. However I managed to get it working without the server-side loading. I think the problem is related to the columns datatable parameter.
These are the parameters that I'm using.
columns = [
                { data: "count" ,             title: "Occurrences" },
                { data: "source" ,            title: "Source" },
                { data: "relationship" ,      title: "Relation"},
                { data: "target_label" ,      title: "Target" },
                { data: "target_type" ,       title: "Target Type"},
                { data: "relationship_uri" ,  title: "Details", sortable: false,
                    render: function ( data, type, row, meta ) {
                        return `<a href="${data}"><i class="material-icons text-info">info</i></a>`;
                    }
                }
            ]

table = $(table_html).DataTable({
            pageLength: 10,
            buttons: [
                {
                    text: 'Reset Filters',
                    action: function ( e, dt, node, config ) {
                        yadcf.exResetAllFilters($(table_html).DataTable());
                    }
                }
            ],
            sDom: "<'row'<'col-sm-4'l><'col-sm-4'B><'col-sm-4'i>><'row'<'col-sm-12'tr>><'row'<'col-sm-12'p>>",
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            serverSide: true,
            ajax: url,
            processing: true,
            deferRender: false,
            responsive: true,
            //stateSave: true,
            bAutoWidth: false,
            bSortCellsTop: true,
            columns: columns,
            order: [0, 'desc']
        });

yadcf.init(table, [
                    {
                        column_number: 0,
                        filter_type: "range_number"
                    },
                    {
                        column_number: direction == 'in' ? 1 : 3,
                        filter_type: "multi_select",
                        select_type: 'select2',
                        sort_as: 'none'
                    },
                    {
                        column_number: 2,
                        filter_type: "multi_select",
                        select_type: 'select2',
                        sort_as: 'none'
                    },
                    //3rd is the 1
                    {
                        column_number: 4,
                        filter_type: "custom_func",
                        select_type: 'select2',
                        sort_as: 'none',
                        custom_func: myCustomFilterFunction,
                        data: [{
                          value: 'Donna',
                          label: 'Donna'
                        }, {
                          value: 'sad',
                          label: 'Sad'
                        }, {
                          value: 'angry',
                          label: 'Angry'
                        }, {
                          value: 'lucky',
                          label: 'Lucky'
                        }, {
                          value: 'january',
                          label: 'January'
                        }],
                        filter_default_label: "Custom func filter"
                    }
                ],
                {filters_tr_index: 1}
        );

A: The custom function is not working as you set searching false. Change the code
  oTable = $('.mytable2').DataTable({
    pageLength: 10,
    scroller: false//,
    //Should not disable the searching function
    //searching: false
  });

Try this updated code snippet

A: I couldn't find the solution to this with yadcf so in the end I implemented my own exclude toggles and I added the exclude toggle status to the AJAX data sent by DataTables.
ajax: {
                url: url,
                data:  function(data, settings) {
                    var table = $(`#${settings.sTableId}`); //get current table
                    table.find('.exclude_toggle').each(function(idx, element){
                        var field = $(element).attr('field');
                        var exclude = $(element).attr('exclude');
                        var column = _.find(data.columns, column => column.data == field);
                        column.search.exclude = JSON.parse(exclude.toLowerCase());
                    });
                    return data;
                }
}, [...]

For the exclude toggle you can use
$(`#${table_id}`).DataTable().ajax.reload();

inside the click event to force DataTables sending a new request to the server.


text:
Q: was never so truly formidable as when - Is Holmes truly formidable or not formidable at all? Sample:

The swing of his nature took him from extreme languor to devouring energy; and as I knew well, he was never so truly formidable as when, for days on end, he had been lounging in his armchair amid his improvisations and his black-letter editions.

The sentence comes from the Red-Headed Leagues. Watson describes both sides of Holme's characters: artistic vs. astute.
When Watson describes him as "he was never so truly formidable as when,....", does he mean that Holmes is not formidable at all when he relaxes at home, or that even lounging at his armchair, Homles is truly formidable for those criminals?
It looks that "be never so truly formidable when" is different from "be never so truly formidable as when".
Does the sentence "be never so .... as when" indicate negative meaning or it's just a way to emphasis?

A:
He was never so truly formidable as when ...

This is indeed a tricky formulation, easily misunderstood. It can be expanded slightly to:

There was never a time when he was so truly formidable as when ...

In modern English, we tend to use "as ... as", rather than "so ... as":

There was never a time when he was as truly formidable as when ...

If we assign some value of "formidableness" to "when he had been lounging for days on end", then we can ask "is there any time when he was equally as formidable?"
The sentence answers that question with "no" - there was never a time when he was equally as formidable.
So when he had been lounging, he was at his most formidable.


text:
Q: Android: why fragments are started if they are not visible? I have two layouts for my Activity. First one is for landscape mode and contains two FrameLayout, second one is for portrait mode and contains only one FrameLayout. Fragments are added dynamically to respective FrameLayouts!! I'm not able to understand why when I rotate the screen in portrait mode onStart() and onResume() method of the Fragment (no more visible!!!!) are called. I know that Android replicates callbacks of the Activity for all of its Fragments but this behavior for me is a non sense!! onStart() and onResume() have to been called only when fragment comes visible!!!!
This issue has already been discussed in this post. But I want to understand why Android has this behavior!!
Thank you.

A: Try setting android:configChanges="orientation" in your manifest, this will indicate you want to manage the orientation change by your own and don't need the default automanagement.
This will allow you to override onConfigurationChanged, check details at:
http://developer.android.com/guide/topics/resources/runtime-changes.html


text:
Q: How can I find the IP addresses of devices on my local network? Is there any way I can find out the IP addresses on my network?
For example my home router is 192.168.5.1 and it is connected to an airos device the IP of which is 192.168.1.20, and the airos device is connected to a mikrotik device.
How can I know what the IP of the mikrotik device is, and the IP addresses of the devices that are above it.

A: There should be a list of connected devices on your router, so you should probably check that first if you have access.
Of course, that won't help you if you want to look up subnets on connected devices. So if that is what you are after, I would suggest that you try to connect to the device that is making the subnet and check what IP you get from there. Then you could scan for other devices using something like nmap.
But like, in general, you won't be able to access subnets without being part of it.


text:
Q: WebGLRenderTarget: Null texture in shader texture Uniform While using THREE.WebGLRenderTarget to render a scene to a texture and pass that texture to a second shader, the value received in the Shader texture uniform variable is always null.
Flow of code:

*

*Shader1 is used for renderingDepthMap(Working fine while being rendered on screen)

*The rendered depthMap is passed as texture uniform to shader2 that is finally rendered on screen.

Relevant Code Snippet:
//Initialize the renderTarget
var options = {

                minFilter : THREE.LinearFilter,
                magFilter : THREE.LinearFilter,
                format : THREE.RGBAFormat,
                type : /(iPad|iPhone|iPod)/g.test(navigator.userAgent) ? THREE.HalfFloatType :
                        THREE.FloatType
            };

    renderTarget1 = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight,
                                   options);
    renderTarget1.stencilBuffer = false;
    renderTarget1.texture.needsUpdate = true;
    renderTarget1.texture.generateMipmaps = false;

    //Define the Shader2 uniforms
        uniforms = {
                     depthMap : { type: "t", value: renderTarget1.texture},
                     O_SIZE : { type: "float", value: 0.000375},
                   };

        //Creating Material for Shader2
        materialShader2 = new THREE.ShaderMaterial({
                            uniforms: uniforms,
                            vertexShader : document.getElementById('vertex2_Shader').textContent,
                            fragmentShader : document.getElementById('fragment2_Shader').textContent
                          });

    materialShader2.needsUpdate = true;

    //Animate function
    function animate()
    {
        // render depth map in renderTarget1
        renderer.setRenderTarget(renderTarget1); //setting render target
        renderer.render(sceneDepthMap, shadowCamera); // rendering depthmap to framebuffer
        renderer.setRenderTarget(null);
        renderer.render(scene2, shadowCamera);
        requestAnimationFrame( animate );
    }

A: I don't have access to your GLSL shader code, but are you sure that the uniform names are identical? It should be uniform sampler2D depthMap;, keep an eye on capitalization. Also, you no longer need to declare type: "t" in the uniform, the engine detects it automatically from its value.
Secondly, if you want to get the depth buffer of a render pass, you need to set WebGLRenderTarget.depthTexture to a new texture, because .texture stores the color buffer, not the depth buffer. You can then use that as your uniform value:
var renderTarget1 = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);
renderTarget1.depthTexture = new THREE.DepthTexture(
    window.innerWidth,
    window.innerHeight
);

var materialShader2 = new THREE.ShaderMaterial({
    uniforms: {
        // Notice uniform name, depthTexture and no type
        depthMap : { value: renderTarget1.depthTexture},
        O_SIZE : { value: 0.000375},
    },
    vertexShader : document.getElementById('vertex2_Shader').textContent,
    fragmentShader : document.getElementById('fragment2_Shader').textContent
});


text:
Q: how to store the large amount data in windows phone 8.1? in android for storing data we are using array list,hash map...etc.
in windows how we save the large amount of data? what about collections in windows phone development. Please any one explain me how to store the data in windows phone 8.1 development.

A: Here you have the main type of collections available in C#: https://msdn.microsoft.com/en-us/library/ybcx56wz.aspx
All of them can be used in Windows Phone.


text:
Q: Why can't amd loader load a script? I'm trying to make a module code work. So far I have the following code:
// third_party/test/Test.ts
export function test():void
{
    console.log("QWERTY");
}

// Main.ts
// import {test} from "./third_party/test/Test"
require([], function () {
    console.log("Loaded");
}

// index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <script data-main="build/library" type="text/javascript" src="scripts/third_party/require/require.js"></script>
    </head>
</html>

// tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "module": "amd",
        "sourceMap": true,
        "outFile": "build/library.js"
    }
}

Please note the commented import statement in Main.ts. This code works as expected - I can see the output message. But as soon as I uncomment import in Main.ts I don't see anything. There're no errors or warnings.
Since I'm using outFile compiler option I have only one js file.

A: The file produced by your compilation contains modules defined like this:
define("third_party/test/Test", ["require", "exports"], function (require, exports) {
// ...
define("Main", ["require", "exports"], function (require, exports) {
// ...

Note the first argument to define. These are the names under which your modules are known to RequireJS. Your data-main requests a module named build/library. There's no such module with this name in your bundle.
You need to ask RequireJS to load Main. Here's a simple way to do it:
<!DOCTYPE html>
<html lang="en">
    <head>
      <script type="text/javascript" src="node_modules/requirejs/require.js"></script>
      <script>
        require.config({
          // All modules are under the "build" path.
          baseUrl: "build",
          // The "library" bundle contains the module "Main" so when
          // "Main" is requested, look for it in "library".
          bundles: {
            "library": ["Main"],
          },
        });
        require(["Main"]);
      </script>
    </head>
</html>


text:
Q: MultiValueDictKeyError at /main/add at 'num1' From below Coded project i want to add two numbers and want to print their resultant value. All things goes smoothly but when i try to print the resultant value it make me causes a "MultiValueDictKeyError" errors. I have searched and tried so many ways but failed to resolve the problem.
The project tree look like this
project files tress
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

def home(request):
return render(request, 'base.html')

@csrf_exempt
def add(request):

   val1 = int(request.POST['num1'])
   val2 = int(request.POST['num2'])
   res = val1 + val2

return render(request, "main/index.html", {'add_result': res})

Index.html
{% extends 'base.html' %}

{% block content %}

This two number adding form

<form action="{% url 'add' %}" method="POST">
    Enter the first here: <input type="text" name="num1" placeholder="First Number">

    Enter the second here: <input type="text" name="num2" placeholder="Second Number">

    <input type="submit">
</form>

    Result :
{{ add_result }}

{% endblock %}

base.html
<!doctype html>

<meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0,
 minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ADDTWONUMBER</title>

THIS IS FORM OF ADDING TWO NUMBER

click here to add two number

{% block content %} {% endblock %}

urls.py
from django.urls import path
from . import views

urlpatterns = [
path('', views.home, name = 'home'),
path('main/add' , views.add, name = 'add'),
]

Errors
> MultiValueDictKeyError at /main/add
> 'num1'
> Request Method:   GET
> Request URL:  http://127.0.0.1:8000/main/add
> Django Version:   3.0.4
> Exception Type:   MultiValueDictKeyError
> Exception Value:  'num1'
> Exception Location:   /home/hudacse6/Env/lib/python3.7/site-
  packages/django/utils/datastructures.py in __getitem__, line 78
> Python Executable:    /home/hudacse6/Env/bin/python
> Python Version:   3.7.4
> Python Path:
 ['/home/hudacse6/pr1_todoapps',
 '/usr/lib/python37.zip',
 '/usr/lib/python3.7',
 '/usr/lib/python3.7/lib-dynload',
 '/home/hudacse6/Env/lib/python3.7/site-packages']
> Server time:  Wed, 18 Mar 2020 17:09:20 +0000

Error in picture
How to do dealt with this error?

A: Have you tried with get() method on request.POST ?
val1 = int(request.POST.get('num1', None))
val2 = int(request.POST.get('num2', None))


text:
Q: Proof of the equation for a rectangle in the Cartesian coordinate system with distances and absolute values Can anyone help me find an approach to deriving the equation
$$
\left\lvert \frac{x}{p}+\frac{y}{q} \right\rvert + \left\lvert \frac{x}{p}-\frac{y}{q} \right\rvert = c
$$
for a rectangle in the Cartesian coordinate system? Does the Triangle inequality or the absolute value as the distance of the points to the origin play a role here?

A: Your approach to a question like this should always be to first graph it for yourself and play around with it. Play around with values and see what they do with the equation.
I am going to answer why $|x+y|+|x-y|=2$ gives you the unit square, and I implore you to use this explanation to figure out how the division by $p$ and $q$ give you any rectangle in general.
So let's define the set $S=\{(x,y)\in\mathbb{R}^2| |x+y|+|x-y|=2 \}$\
So we want to see why $S$ is the unit square. First of all, lets build some intuition. Why is it that if $x$ or $y$ are greater than 1 or less than negative 1 we get that $(x,y)\not\in S$. There are 4 cases to consider here, but I will only show 1.
Lets say $x>1$ now if $|y|\leq x$ we get that $|x+y|+|x-y| = 2x > 2$ since both $x+y$ and $x-y$ will be positive. On the other hand, if $|y|>x$ then there are 2 cases but since $|x+y|+|x-y|$ the two cases will be almost identical, so Ill just show the case where $y>0$. In this case we have
$$|x+y|+|x-y| = |x+y|+|y-x| = 2y > 2x > 2$$
And we are done. (Note if you are expanding upon this proof yourself, there is a lot of optimizations you can do to handle multiple cases at the same time, but don't feel like you need to if that gets confusing).
Now to finish showing that this is equal to the unit cube, we will need to do a few arguments that look like the following one, again I will only show one example.
We will show for all $y$ such that $-1\leq y \leq 1$ we have $(1,y)\in S$.
Assume $-1\leq y \leq 1$ Then we have that
(note the two inequalities seem obvious, but if this is a first year course, you should probably show them in one or two lines)
$0\leq 1-1 \leq 1-y$  and also $0\leq 1 + (-1) \leq 1 + y$
so $|1+y| + |1-y| = 1+y+1-y = 2$
Once you are done dealing with all of the cases, you will have shown that all points on the square are points in $S$ and all points not on the square are not in $S$ hence $S$ is the unit square. Or in yourcase, whichever rectangle you want it to be.


text:
Q: Why is printing out with format throwing NoneType error? account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
    total += float(account_balance[key])

Then this:
print("TOTAL: {0}").format(str(total))

throws an error of:

AttributeError: 'NoneType' object has no attribute 'format'

... why?

A: It should be:
print("TOTAL: {0}".format(str(total)))

Your original code is trying to call the .format() method to the print function's return value. Since that is always None, you get an AttributeError.
If you're using Python >=3.6, I would suggest you use f-strings for this. They are wonderful to use and will make string formatting a joy:
print(f"TOTAL: {total}")

Also this code:
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
    total += float(account_balance[key])

Can be simplified and made more efficient by using sum with a generator expression:
total = sum(float(value) for value in account_balance.values())

Or alternatively using sum and map:
total = sum(map(float, account_balance.values()))

So all together to make your code nice and easy to read:
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = sum(float(value) for value in account_balance.values())
print(f"TOTAL: {total}")

Output:
TOTAL: 206.56

A: You may want to try this:
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
    total += float(account_balance[key])
print(total)
206.56


text:
Q: DotNet Core 2.1 hoarding memory in Linux I have a websocket server that hoards memory during days, till the point that Kubernetes eventually kills it. We monitor it using prometheous-net.
# dotnet --info

Host (useful for support):
  Version: 2.1.6
  Commit:  3f4f8eebd8

.NET Core SDKs installed:
  No SDKs were found.

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.6 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.6 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.6 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

But when I connect remotely and take a memory dump (using createdump), suddently the memory drops... without the service stopping, restarting or loosing any connected user. See the green line in the picture.
I can see in the graphs, that GC is collecting regularly in all generations.
GC Server is disabled using:
<PropertyGroup>
  <ServerGarbageCollection>false</ServerGarbageCollection>
</PropertyGroup>

Before disabling GC Server, the service used to grow memory way faster. Now it takes two weeks to get into 512Mb.
Other services using ASP.NET Core on request/response fashion do not show this problem. This uses Websockets, where each connection last usually around 10 minutes... so I guess everything related with the connection survives till Gen 2 easily.

Note that there are two pods, showing the same behaviour, and then one (the green) drops suddenly in memory ussage due the taking of the memory dump.

The pods did not restart during the taking of the memory dump:

No connection was lost or restarted.
Heap:
(lldb) eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x00007F8481C8D0B0
generation 1 starts at 0x00007F8481C7E820
generation 2 starts at 0x00007F852A1D7000
ephemeral segment allocation context: none
         segment             begin         allocated              size
00007F852A1D6000  00007F852A1D7000  00007F853A1D5E90  0xfffee90(268430992)
00007F84807D0000  00007F84807D1000  00007F8482278000  0x1aa7000(27947008)
Large object heap starts at 0x00007F853A1D7000
         segment             begin         allocated              size
00007F853A1D6000  00007F853A1D7000  00007F853A7C60F8  0x5ef0f8(6222072)
Total Size:              Size: 0x12094f88 (302600072) bytes.
------------------------------
GC Heap Size:            Size: 0x12094f88 (302600072) bytes.
(lldb)

Free objects:
(lldb) dumpheap -type Free -stat
Statistics:
              MT    Count    TotalSize Class Name
00000000010c52b0   219774     10740482      Free
Total 219774 objects

Is there any explanation to this behaviour?

A: The problem was the connection to RabbitMQ. Because we were using sort lived channels, the "auto-reconnect" feature of the RabbitMQ.Client was keeping a lot of state about dead channels. We switched off this configuration, since we do not need the "perks" of the "auto-reconnect" feature, and everything start working normally. It was a pain, but we basically had to setup a Windows deploy and do the usual memory analysis process with Windows tools (Jetbrains dotMemory in this case). Using lldb is not productive at all.

A: Disclaimer: I am no .NET Wizard.
But you should do two things to go with Kubernetes best practices:

*

*Define sensible resource limits for your app. If the app does not need more than 200MB memory define a resource limit to prevent the app from consuming all available host memory. But be aware that the Unix API to get available memory is not capable of processing the cgroup the process has and always outputs the host memory no matter what your cgroup says.

*Tell your app what this resource limit is. It seems like your app does not "feel the need" to free memory as there is plenty. Almost all applications, and frameworks as well, have a switch to define the maximum memory to be consumed. Tell your app this limit, and it will "see" memory pressure and perform a full GC (what I guess could be the problem here)


text:
Q: What is Linux doing differently that allows me to remove/replace files where Windows would complain the file is currently in use? The example I have is Minecraft. When running Bukkit on Linux I can remove or update the .jar files in the /plugins folder and simply run the 'reload' command.
In Windows, I have to take the whole server process down because it will complain that the .jar file is currently in use when I try to remove or replace it.
This is awesome to me, but why does it happen?
What is Linux doing differently here?

A: Linux deletes a file completely differently than the way Windows does. First, a brief explanation on how files are managed in the *unix native file systems.
The file is kept on the disk in the multilevel structure called i-node. Each i-node has an unique number on the single filesystem. The i-node structure keeps different information about a file, like its size, data blocks allocated for the file etc., but for the sake of this answer the  most important data element is a link counter. The directories are the files that keep records about the files. Each record has the i-node number it refers to, the file name length and the file name itself. This scheme allows one to have 'pointers', i.e. 'links' to the same file in different places with different names. The link counter of the i-node actually keeps the number of links that refer to this i-node.
What happens when some process opens the file? First the open() function  searches for the file record. Then it checks if the in-memory i-node structure for this i-node already exists. This may happen if some application already had this file opened. Otherwise, the system initializes a new in-memory i-node structure. Then the system increases the in-memory i-node structure open counter and returns to the application its file descriptor.
The Linux library call to delete a file is called unlink. This function removes the file record from a directory and decrements the i-node's link counter. If the system found that an in-memory i-node structure exists and its open counter is not zero then this call returns the control to the application. Otherwise it checks if the link-counter became zero and if it does then the system frees all blocks allocated for the i-node and the i-node itself and returns to the application.
What happens that an application closes a file? The function close() decrements the open counter and checks its value. If the value is non-zero the function returns to the application. Otherwise it checks if the i-node link counter is zero. If it is zero, it frees all blocks of the file and the i-node before returning to the application.
This mechanism allows you to "delete" a file while it is opened. At the same time the application that opened a file still has access to the data in the file. So, JRE, in your example, still keeps its version of file opened while there is another, updated version on the disk.
More over, this feature allows you to update the glibc(libc) - the core library of all applications - in your system without interrupting its normal operation.
Windows
20 years ago we did not know any other file system than FAT under DOS. This file system has a different structure and management principles. These principles do not allow you to delete a file when it is opened, so the DOS and lately Windows has to deny any delete requests on a file that is open. Probably NTFS would allow the same behavior as *nix file systems but Microsoft decided to maintain the habitual behavior of the file deletion.
This is the answer. Not short, but now you have the idea.
Edit:
A good read on sources of Win32 mess: https://web.archive.org/web/20190218083407/https://blogs.msdn.microsoft.com/oldnewthing/20040607-00/?p=38993
Credits to @Jon


text:
Q: Bootstrap 5 navbar - Can't get nav items to the right side, when brand is on the left side I am having issues with getting the items to the right. I got my brand on the left side and whatever i try. I can't get the items to the right side of the navbar.They stay hugging to the left side.
This is my code:

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#NavCollapse" aria-controls="NavCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

       Home

       Articles

       Games

       NG Boiler Room

       Catch Me Live

       Event Calendar

       Gallery

       Projects

       Credits

I have atm no clue, what i did wrong there. Did i messed something up or do i miss something in the code?

A: Since you'd like to align the entire navigation to the right side of the navbar, you can simply add an empty div with a margin-right of auto right before the nav link section, which will push the navigation to the right side.

In your original navbar code, this implementation would look like:

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#NavCollapse" aria-controls="NavCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

       Home

       Articles

       Games

       NG Boiler Room

       Catch Me Live

       Event Calendar

       Gallery

       Projects

       Credits

For more information and to read up on detailed implementation, check out the Bootstrap documentation on navbars:
https://getbootstrap.com/docs/5.0/components/navbar/

A: Bootstrap comes packaged with several flexbox utility classes that can be used here.
Since the .navbar-collapse class is set to be display: flex and there are only 2 children within this element, we can add the .justify-content-between class to force the 2 children to sit on opposite ends.

Alternatively, if the .navbar-collapse element will have more than 2 children, you can place the .ml-auto utility on the ul element to force it to sit on the right.

Documentation: Bootstrap flex utilities


text:
Q: How to bind a ComboBox to generic dictionary with xaml code I'm using the following code  :
private Dictionary<string, string> GetNumber { get; set; }
public ReportsLetterTra()
{
    GetNumber = new Dictionary<string, string>
                            {
                                {"1", "First"},
                                {"2", "Second"}
                            };

    InitializeComponent();
}

xaml code :
 <ComboBox
      DisplayMemberPath="value"
      SelectedValuePath="key"
      ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}"
      SelectedIndex="0" Name="cmbFromNumber" />

Why is not bind GetNumber to cmbFromNumber?!
Update :
my complete code in behind file :
using System.Collections.Generic;
using System.Windows;

namespace WpfApplication20
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Dictionary<string, string> GetNumber { get; set; }

        public Window1()
        {

            GetNumber = new Dictionary<string, string>
                                    {
                                        {"1", "First"},
                                        {"2", "Second"}
                                    };
            InitializeComponent();

        }
    }
}

my complete xaml code:
<Window x:Class="WpfApplication20.Window1" Name="eportslettra"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid Height="26">
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key"
               ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}"
               SelectedIndex="0"  Name="cmbFromNumber"    />
    </Grid>
</Window>

Where is my wrong?
Why is not bind GetNumber to cmbFromNumber?!

A: Your property is marked as private, make it public. Also, correct the casing on your ComboBox to Value and Key. Thirdly, your binding expression looks invalid, double check this. Finally, it looks like your properties are part of the view's code behind file. You might consider the MVVM design pattern.
Update
Your Window has the Name of 'eportslettra', but your binding expression uses the ElementName 'reportslettra'. Correct one of them.


text:
Q: TensorFlow RandomForest vs Deep learning I am using TensorFlow for training model which has 1 output for the 4 inputs. The problem is of regression.
I found that when I use RandomForest to train the model, it quickly converges and also runs well on the test data. But when I use a simple Neural network for the same problem, the loss(Random square error) does not converge. It gets stuck on a particular value.
I tried increasing/decreasing number of hidden layers, increasing/decreasing learning rate. I also tried multiple optimizers and tried to train the model on both normalized and non-normalized data.
I am new to this field but the literature that I have read so far vehemently asserts that the neural network should marginally and categorically work better than the random forest.
What could be the reason behind non-convergence of the model in this case?

A: If your model is not converging it means that the optimizer is stuck in a local minima in your loss function.
I don't know what optimizer you are using but try increasing the momentum or even the learning rate slightly.
Another strategy employed often is the learning rate decay, which reduces your learning rate by a factor every several epochs. This can also help you not get stuck in a local minima early in the training phase, while achieving maximum accuracy towards the end of training.
Otherwise you could try selecting an adaptive optimizer (adam, adagrad, adadelta, etc) that take care of the hyperparameter selection for you.
This is a very good post comparing different optimization techniques.
Deep Neural Networks need a significant number of data to perform adequately. Be sure you have lots of training data or your model will overfit.

A: A useful rule for beginning training models, is not to begin with the more complex methods, for example, a Linear model, which you will be able to understand and debug more easily.
In case you continue with the current methods, some ideas:

*

*Check the initial weight values (init them with a normal distribution)

*As a previous poster said, diminish the learning rate

*Do some additional checking on the data, check for NAN and outliers, the current models could be more sensitive to noise. Remember, garbage in, garbage out.


text:
Q: I want to add dot between number i'm going to convert Epoch time to '%Y-%m-%d %H:%M:%S.%N'
but "converted Epoch time(date -> Epoch time)" is expressed nanoseconds.
if convert "1612483249166", output "53067-07-24 10:26:46.000".
so i want to input "1612483249.166"
how ??????
ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime2=`gdate -u -d "1970-01-01 $ptime1 seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`

_i'm sorry if the sentence if awkward. thank you

A: How about using the calculated variable ptime1_?
ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime1_=`expr $ptime1 / 1000`
ptime2=`gdate -u -d "1970-01-01 $ptime1_ seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`


text:
Q: When is the boundary of a subset of $\mathbb{R^n}$ compact? In Euclidean space, the boundary of a subset (Closure - Interior) is always closed, but I would like to know when it's compact as well.  Is it when the subset is bounded?

A: Community wiki answer-made-of-comments:
The boundary of a bounded set is itself bounded. By the Heine-Borel theorem, if a subset of the Euclidean space is bounded then its boundary is compact. – A. De Luca
Everything that others have said is true. I just want to add that the boundary of the complement of a bounded set is also bounded. After all, everything far out is then in the interior, and thus the boundary is still bounded + closed, and hence by Heine-Borel also compact. – Jyrki Lahtonen
In $\mathbb R^n$ with $n\ge 2$, the above two cases are exhaustive: the boundedness of $\partial A$ implies that either $A$ or $A^c$ is bounded. Not so in $n=1$. The key difference is the connectedness of $\mathbb R^n \setminus B(0,R)$. – Leonid Kovalev


text: Q: Password protected WMS in Openlayers 4 I would like to use OpenLayers to access a Wms, which is protected by a password. Unfortunately, I find no solution to this problem. My problem is in particular that I want to prevent that password from publishing in the source code of the page. I use OpenLayers 4. Can someone give me an advice?


text:
Q: Show and Hide div's JavaScript works in IE but not Firefox or Chrome I have a number of spans (20 - to be exact) they all have Id's.
I then in my style sheet I set the visibility to hidden.
I made this script to show and hide these spans once clicking on a section of the image map:
function showDiv(pass) {
    var divs = document.getElementsByTagName('span');
    for (i = 0; i < divs.length; i++) {
        if (divs[i].id.match(pass)) {
            (pass).style.visibility = 'visible';
            divs[i].style.visibility = 'hidden';
        }
    }
}

It works perfectly in IE but Firefox doesn't budge, Chrome displays it alright enough with minor problems that I think I can fix.
Anyone know why Firefox doesn't accept?
Any suggestions would be greatly appreciated and compensated for in the after life :)

A: style.display = 'none';
style.display = 'inline';

EDIT
Here is my source
http://www.w3schools.com/css/pr_class_display.asp

A: It is because you are passing in a string, and then later using it as an element reference.  IE must be smart enough to search the DOM and find an element with an ID matching the string.
Try this...
if (divs[i].id.match(pass)) {
    document.getElementById(pass).style.visibility = 'visible';
    divs[i].style.visibility = 'hidden';
}

Or it could be that the String.match function is expecting a RegExp.  If the above does not resolve your problem, try this...
if (divs[i].id.match(new RegExp(pass, 'gi'))) {

A: pass is an ID. In Firefox, element ids in the DOM aren't available as global references. You can't do id.style.visibility = 'visible'; Instead your function should look something like this:
function showDiv(pass) {
    var divs = document.getElementsByTagName('span');
    for (i = 0; i < divs.length; i++) {
        if (divs[i].id.match(pass)) {
            divs[i].style.visibility = 'hidden';
        }
    }
    document.getElementById(pass).style.visibility = 'visible';
}

You should be able to set the visibility of pass outside the loop since you only need to do it once.

A:     if (divs[i].id.match(pass)) {

Is pass really a regular expression? Seems unusual to be using match here.
        (pass).style.visibility = 'visible';

This makes no sense whether pass is a string or a regex; neither have a style property. Putting the variable in parentheses has no effect. It doesn't work in any browser for me, including IE.
I would guess you meant:
function showDiv(pass) {
    var divs= document.getElementsByTagName('span');
    for (var i= 0; i<divs.length; i++)
        divs[i].style.visibility= divs[i].id==pass? 'visible' : 'hidden';
}

Note also the var i: this is necessary to stop i becoming a global variable. It is a very common source of weird errors when two for i loops start interfering with each other.


text:
Q: Visualforce multiselect picklist in salesforce1 How to display visualforce multi select picklist in visual force page using jquery mobile?

A: You have a number of options as listed on this post as well

*

*You can use this open source component provided by Force.com MVP
Abhinav Gupta

*Alternatively, you can use the jQuery Mobile custom
menu with multiple="multiple" attribute set and handle the
appropriate logic in your controller


text:
Q: Is there any way to save a PNG-8 file with Alpha Transparency in Photoshop? I recently discovered something that I previous thought was impossible: PNG-8 files can store Alpha Transparency in the same way as PNG-32 files can. Not Indexed Transparency (like GIFs), but full on Alpha Transparency.
(You can learn more about this here: http://blogs.sitepoint.com/png8-the-clear-winner)
Apparently it's possible to do this using Fireworks, but I can't find a way to do it using Photoshop.
Does anyone know a way of enabling this incredible feature in Photoshop? Through add-ons or by any other means? It's so incredibly useful for web developers that I can't believe it's not been included in the latest version (or any version) of PS!

A: An updated answer for 2015 tech.
I'm using Photoshop Creative Cloud 2015 (for PC, I don't know if there is any difference on Mac) and there is a choice to
"File > Export > Export as"
There aren't a whole lot of options to adjust from here, but if you select PNG-8 format it will automatically use full (or what appears to be full) alpha transparency in a PNG-8 format. Mileage may vary depending on image size and number of colors as to whether or not the result will actually be smaller than a regular PNG-24. On average the images I have been working with have resulted in about 1/3 final file size when compared to a PNG-24 of the same image.
NOTE: Check that the image mode is NOT indexed (lock icon on the layer) as I was not able to get the alpha transparency to work otherwise. I used RGB mode with successful results.

A: You can use Ethan Gardner's pngquant script to convert a photoshop file to alpha-tx PNG. It works on Mac and PC.
http://www.ethangardner.com/articles/alpha-transparency-in-png-8-images-without-using-fireworks/

A: Not that I know of, but save the image as PNG-24 then use this:
http://compresspng.com
(I tried http://www.8bitalpha.com and http://tinypng.org but they gave me poor results.)

A: This is an important subject, especially for web design. A big png24 image can be ~1mb, almost impossible to consider for web site design use. But same image as png8 with alpha is ~250kb, ok in a lot of situations.
And finally a drag-and-drop solution for png8 with alpha transparency, free as of 2013 04: http://tinypng.org/
And some more related tools are here: http://pngquant.org/
Enjoy!

A: If you're on a Mac, you can use the excellent (and free) ImageAlpha tool to do this to a PNG-32 using a GUI, live preview, etc.

A: go to file > save for web and device
look at right side there is a drop down after Preset you'll find there PNG 8 there are some option related to transparency,just check them out.


text:
Q: lastchild for Internet Explorer I know there are some ways to get the "lastchild" work for Internet Explorer. CSS doesn't seem to work that well.
I read about a jQuery version, but am not sure how to do that exactly.
I only need this because I use list styles with border-top and border-bottom to create "shadow-effects".
Here's my website.
The top navigation menu has a lastchild definition in a javascript fild but it doesn't seem to take proper effect:
jQuery("ul.menu li:last-child").addClass("last-child");
jQuery("ul.menu li:first-child").addClass("first-child");

The original CSS was something like that, but this displays the borders left and right in Firefox, too!:
.jqueryslidemenu ul li.first-child a{border-left:none}
.jqueryslidemenu ul.sub-menu li.first-child a{border-left:1px solid #444444!important}
.jqueryslidemenu ul li.last-child a{border-right:none}
.jqueryslidemenu ul.sub-menu li.last-child a{border-right:1px solid #444444!important}
/*IE6 hack to get sub menu links to behave correctly*/
* html .jqueryslidemenu ul li a{display: inline-block;}

I changed it to that and now the right-border only shows up in IE!:
.jqueryslidemenu ul li:first-child a{border-left:none;}
.jqueryslidemenu ul.sub-menu li.first-child a{border-left:1px solid #444444!important;}
.jqueryslidemenu ul li:last-child a{border-right:none;}
.jqueryslidemenu ul.sub-menu li.last-child a{border-right:1px solid #444444!important;}
/*IE6 hack to get sub menu links to behave correctly*/
* html .jqueryslidemenu ul li a{display: inline-block;}

A: Set the CSS programmatically using .children().last().css()
Or if you know which element is that while you are laying it out (in the backend), add a class of last to it.


text:
Q: Spark LDA consumes too much memory I'm trying to use spark mllib lda to summarize my document corpus.
My problem setting is as bellow.

*

*about 100,000 documents

*about 400,000 unique words

*100 cluster

I have 16 servers (each has 20 cores and 128GB memory).
When I execute LDA with OnlineLDAOptimizer, it gives out of memory error, suggesting me to increase spark.driver.maxResultSize like
Total size of serialized results of 11 tasks (1302 MB) is bigger than spark.driver.maxResultSize
I increased spark.driver.maxResultSize to 120GB (and also spark.driver.memory to 120GB) and re-run LDA but no lack.
It still says Total size of serialized results of 11 tasks (120.1 GB) is bigger than spark.driver.maxResultSize
I tried another dataset with about 100,000 unique words and it worked.
So, how can I estimate the memory usage when using Spark mllib LDA? I couldn't find any specification in the official documentation.
Note I used sparse vector for constructing docuemnt RDD[(Long, Vector)] passed to LDA.run() but don't know whether spark lda can handle sparse format correctly in internal.
(editted) I used Scala version of LDA. Not Python version.
This may be a related issue but no clear answer was given.
Spark LDA woes - prediction and OOM questions
(edited)
This is a snippet of my code (gist).
https://gist.github.com/lucidfrontier45/11420721c0078c5b7415
def startJob(args: RunArgs)(implicit sc: SparkContext): Unit = {
    val src = sc.textFile(args.fname, minPartitions = args.n_partitions).map(_.split("\t"))
        .flatMap {
            // input file's format is (user_id, product_name, count)
            case Array(u, p, r, t) => Some((u.toInt, p.toInt, r.toDouble))
            case _ => None
        }.persist()

    // Map to convert user_id or product_name into unique sequencential id
    val userid_map = src.map(_._1).distinct().zipWithIndex().collect().toMap
    val productid_map = src.map(_._2).distinct().zipWithIndex().collect().toMap
    val inverse_userid_map = userid_map.map(_.swap)

    // broadcat to speedup RDD map operation
    val b_userid_map = sc.broadcast(userid_map)
    val b_productid_map = sc.broadcast(productid_map)
    val b_inverse_userid_map = sc.broadcast(inverse_userid_map)

    // run map
    val transformed_src = src.map { case (u, p, r) =>
        (b_userid_map.value(u), b_productid_map.value(p).toInt, r)
    }

    println("unique items = %d".format(b_productid_map.value.size))

    // prepare for LDA input RDD[(LONG, Vector)]
    val documents = transformed_src.map { case (u, p, r) => (u, (p, r)) }
        .groupByKey()
        .map { t => (t._1, Vectors.sparse(b_productid_map.value.size, t._2.toSeq)) }.persist()

    documents.count()
    src.unpersist()

    // run Online Variational LDA
    val ldamodel = new LDA()
        .setK(args.k)
        .setMaxIterations(args.n_iter)
        .setOptimizer("online")
        .run(documents)
        .asInstanceOf[LocalLDAModel]

    val result = ldamodel.topicDistributions(documents)
        .map { case (i, v) =>
            val u = b_inverse_userid_map.value(i)
            "%d,%s".format(u, v.toArray.mkString(","))
        }
    result.saveAsTextFile(args.out)
}

Actually, I use LDA for dimensional reduction of transaction data. My data is in the format of (u, p, r)
where u is user id, p is product name, r is the number user u interacted with p. user corresponds to document and product to word in this case. Since user id and product name are arbitrary string, I converted them to unique sequential integers before submitting to LDA.
Thank you.

A: There are three common causes for this problem, which may work independently or in tandem.

*

*The job returns a lot of data to the driver using something like collect. Alas, some of the SparkML code does this. If you cannot blame (2) or (3) below for the problem, it's likely the outcome of how your data interacts with the OnlineLDAOptimizer implementation.

*The job involves a large number of tasks, each of which returns results to the driver as part of Spark's job management (as opposed to with something like collect). Check the number of tasks in the SparkUI. Also see Exceeding `spark.driver.maxResultSize` without bringing any data to the driver Are org.apache.spark.scheduler.TaskSetManager#canFetchMoreResults or org.apache.spark.scheduler.TaskResultGetter#enqueueSuccessfulTask on the stack trace?

*An estimation error: Spark significantly over-estimates the size of data that's about to be returned to the driver and throws this error in order to prevent a cluster's driver from OOM. See What is spark.driver.maxResultSize? One way to test for this is to set spark.driver.maxResultSize to 0 (no limit) and see what happens.
Hope this helps!


text:
Q: How do I use SSDP? I need a way for my application to find someone with the same application on a local network.
But can't find the docs to use a protocol like SSPD. It says its UDP on port 1900 and the ip 239.255.255.250.
It also says it can use NOTIFY and M-SEARCH.
But that is it. I've hit a wall. And I need some guidence.
OVERVIEW
Trying to make my apps automatically find each other and exchange ip/names on a local network so they can talk to each other p2p-style without a connection broker.

A: The UPnP Device Architecture reference contains the de-facto SSDP reference: it's very similar to the IETF spec and has dozens of well tested implementations already. Chapter 1 contains everything needed to implement SSDP, assuming you know how to send and receive multicast and unicast UDP messages.
My advice on implementing SSDP: Don't. It may look simple but there are a lot of gotchas on the way. Find a library or service that does SSDP for you. If you are on linux I suggest GSSDP (reference, code) (but I'm a bit biased having worked on it). I would assume other platforms have similar libraries.


text:
Q: Display charts based on checkbox selection - highcharts I have three charts, right now, all three charts are displayed by default.
I want them to be displayed based on check boxes I click.
document.querySelectorAll('#checkboxes input').forEach(function(checkbox) {
checkbox.addEventListener('change', (e) => {
const id = e.target.dataset.id,
  checked = e.target.checked,
  checkedCheckboxes = document.querySelectorAll('#checkboxes input:checked').length,
})
})

Please find the fiddle: https://jsfiddle.net/uL3qz5tm/
First chart should be displayed by default (on load).
If chart1 and chart2 are checked, chartOne and ChartTwo graphs must be displayed.
If all three checkboxes are checked, all three graphs must be displayed.
If all three checkboxes are unchecked, page must be empty.
I have commented out code I had tried (under -> Display chart based on checkbox selection), they are not efficient or behaves exactly how I want.
I would appreciate if anyone can help me with this.

A: You can change style on hidden/visible when switching checkbox.
let chart1 = Highcharts.chart('container1', {

  series: [{
    data: [1, 2, 3, 4, 5, 6, 7]
  }],

});

let chart2 = Highcharts.chart('container2', {

  series: [{
    data: [1, 2, 3, 4, 5, 6, 7].reverse()
  }],

});

let checkbox1 = document.getElementById('checkbox1');
let container1 = document.getElementById('container1');

checkbox1.addEventListener('change', () => {
  if (container1.style.visibility == 'hidden') {
    container1.style.visibility = 'visible';
  } else {
    container1.style.visibility = 'hidden';
  }
})

container2.style.visibility = 'hidden';

checkbox2.addEventListener('change', () => {
  if (container2.style.visibility == 'hidden') {
    container2.style.visibility = 'visible';
  } else {
    container2.style.visibility = 'hidden';
  }
})

Live demo: https://jsfiddle.net/BlackLabel/ju2Ld7c1/1/


text:
Q: Why does Python allow multiple instance attributes of the same name? I am taking a Python OOP course and, by playing with the code in the course, I stumbled upon something interesting.
Suppose I have this code:
class genericClass:
   def __init__(self):
      self.__secret = "secret"

generic_object = genericClass()

print(generic_object.__secret)

When I run this code I get the following error:

AttributeError: 'genericClass' object has no attribute '__secret'

But if I do the following:
class genericClass:
   def __init__(self):
      self.__secret = "secret"

generic_object = genericClass()

generic_object.__secret = "not a secret anymore" #set a different value for the '__secret attribute
print(generic_object.__secret)

Everything works and the message is printed to my terminal.
How does this happen? Does this specific instance now have 2 '__secret' attributes? If yes, how does Python differentiate between the two? If not, what is going on?


text:
Q: Cannot change QuickStyle in Qt 5.11 Hey I am using Qt Creator because there is no qml implementation in visual studio yet.
I am not able to change the style of quick components no matter what. I have tried it with global constants and as well as C++ API call but it still throws errors. I don't know what else to try.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQuickControls2/QQuickStyle>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQuickStyle::setStyle(QLatin1String("Material"));

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

I stopped at this, I get these errors:
main.qml:6: error: Expected token `{'

main.obj:-1: error: LNK2019: unresolved external symbol "__declspec(dllimport) public: static void __cdecl QQuickStyle::setStyle(class QString const &)" (__imp_?setStyle@QQuickStyle@@SAXAEBVQString@@@Z) referenced in function main

debug\RandomGenerator.exe:-1: error: LNK1120: 1 unresolved externals

I don't know what to do, there are no more tutorials explaining this.

A: You can try to do this in qml.
enter this in qtquickcontrols2.conf
[Controls]
Style=Material

[Material]
Theme=Dark

If you want to change color or another properetys enter this in main.qml in AplicationWindow
Material.accent: Material.color(Material.Blue)

More info about styles and there properetys you can find here


text:
Q: Raising IO Exceptions in SML Exception IO has structure:
Exception IO of {
name: string
....
...}

some other arguments that I do not understand.
Do I have to assign all these. I mean what do I do after this?
exception IO of {inputfile}

I usually define exception and then raise. but I do not even define an exception this way.
All I want to do is raise an exception if input file is not existant. What do I do here?
Thank You

A: Yes, you have to supply all three fields when creating an exception of type Io. The meanings of the fields are explained in the documentation:

This is the principal exception raised when an error occurs in the I/O subsystem. The components of Io are:

*

*name: The name component of the reader or writer.

*function: The name of the function raising the exception.

*cause: The underlying exception raised by the reader or writer, or detected at the stream I/O level.

  Some of the standard causes are:

*

*OS.SysErr if an actual system call was done and failed.
  *Subscript if ill-formed arguments are given.

*BlockingNotSupported

*NonblockingNotSupported

*ClosedStream

  The cause field of Io is not limited to these particular exceptions. Users who create their own readers or writers may raise any exception they like, which will be reported as the cause field of the resulting Io exception.

Note that openIn already raises an Io exception if the file does not exist (with "openIn" as the function, the filename as the name and a SysErr as the cause), so there's no need for you to raise your own.


text:
Q: How to add layer switch/on off layers in OpenLayers I have configured a WMS layer into OpenLayers localhost (port 8080), I want to show a layer toggling button which can show only OSM basemap checkbox and my layers.
What is code for it how to add this in my code?
My code is given as:
<!DOCTYPE html>

    <title>Single Image WMS</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.5.0/css/ol.css" type="text/css">


text:
Q: Make jvmpkg error in tvm for deploying tvm runtime in android I'm trying to install tvm runtime in android. I installed libtvm_runtime.so and I did make jvmpkg. But I'm getting errors.
(cd /home/aishwarya/Downloads/tvm/jvm; \ mvn clean package -Plinux-x86_64 -Dcxx="g++" \ -Dcflags="-std=c++11 -Wall -O2 -Iinclude -I/home/aishwarya/Downloads/tvm/3rdparty/dlpack/include -I/home/aishwarya/Downloads/tvm/3rdparty/dmlc-core/include -fPIC" -Dldflags="" \ -Dcurrent_libdir="/home/aishwarya/Downloads/tvm/build" -DskipTests -Dcheckstyle.skip=true) WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.google.inject.internal.cglib.core.$ReflectUtils$1 (file:/usr/share/maven/lib/guice.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) WARNING: Please consider reporting this to the maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$1 WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release
 [INFO] Scanning for projects...
 [INFO] ------------------------------------------------------------------------
 [INFO] Reactor Build Order:
 [INFO]
 [INFO] TVM4J Package - Parent [pom]
 [INFO] TVM4J Package - Core [jar]
 [INFO] TVM4J Package - Native Parent [pom]
 [INFO] TVM4J Package - Native Linux-x86_64 [so]
 [INFO] TVM4J Package - Full Parent [pom]
 [INFO] TVM4J Package - Full Linux-x86_64 [jar]
 [INFO]
 [INFO] --------------------< org.apache.tvm:tvm4j-parent >---------------------
 [INFO] Building TVM4J Package - Parent 0.0.1-SNAPSHOT [1/6]
 [INFO] --------------------------------[ pom ]---------------------------------
 [INFO]
 [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ tvm4j-parent ---
 [INFO]
 [INFO] --- maven-source-plugin:2.2.1:jar-no-fork (attach-sources) @ tvm4j-parent ---
 [INFO]
 [INFO] --- maven-jar-plugin:3.0.2:jar (empty-javadoc-jar) @ tvm4j-parent ---
 [WARNING] JAR will be empty - no content was marked for inclusion!
 [INFO] Building jar: /home/aishwarya/Downloads/tvm/jvm/target/tvm4j-parent-0.0.1-SNAPSHOT-javadoc.jar
 [INFO]
 [INFO] --- maven-javadoc-plugin:2.9.1:jar (attach-javadocs) @ tvm4j-parent ---
 [INFO] Not executing Javadoc as the project is not a Java classpath-capable package
 [INFO]
 [INFO] ---------------------< org.apache.tvm:tvm4j-core >----------------------
 [INFO] Building TVM4J Package - Core 0.0.1-SNAPSHOT [2/6]
 [INFO] --------------------------------[ jar ]---------------------------------
 [INFO]
 [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ tvm4j-core ---
 [INFO]
 [INFO] --- maven-checkstyle-plugin:2.17:check (default) @ tvm4j-core ---
 [INFO]
 [INFO] --- maven-resources-plugin:2.7:resources (default-resources) @ tvm4j-core ---
 [INFO] Using 'UTF-8' encoding to copy filtered resources.
 [INFO] skip non existing resourceDirectory /home/aishwarya/Downloads/tvm/jvm/core/src/main/resources
 [INFO]
 [INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ tvm4j-core ---
 [INFO] Changes detected - recompiling the module!
 [INFO] Compiling 34 source files to /home/aishwarya/Downloads/tvm/jvm/core/target/classes
 [INFO] /home/aishwarya/Downloads/tvm/jvm/core/src/main/java/org/apache/tvm/Module.java: Some input files use or override a deprecated API.
 [INFO] /home/aishwarya/Downloads/tvm/jvm/core/src/main/java/org/apache/tvm/Module.java: Recompile with -Xlint:deprecation for details.
 [INFO]
 [INFO] --- maven-resources-plugin:2.7:testResources (default-testResources) @ tvm4j-core ---
 [INFO] Using 'UTF-8' encoding to copy filtered resources.
 [INFO] skip non existing resourceDirectory /home/aishwarya/Downloads/tvm/jvm/core/src/test/resources
 [INFO]
 [INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ tvm4j-core ---
 [INFO] Changes detected - recompiling the module!
 [INFO] Compiling 6 source files to /home/aishwarya/Downloads/tvm/jvm/core/target/test-classes
 [INFO]
 [INFO] --- maven-surefire-plugin:2.7:test (default-test) @ tvm4j-core ---
 [INFO] Tests are skipped.
 [INFO]
 [INFO] --- maven-jar-plugin:3.0.2:jar (default-jar) @ tvm4j-core ---
 [INFO] Building jar: /home/aishwarya/Downloads/tvm/jvm/core/target/tvm4j-core-0.0.1-SNAPSHOT.jar
 [INFO]
 [INFO] --- maven-source-plugin:2.2.1:jar-no-fork (attach-sources) @ tvm4j-core ---
 [INFO] Building jar: /home/aishwarya/Downloads/tvm/jvm/core/target/tvm4j-core-0.0.1-SNAPSHOT-sources.jar
 [INFO]
 [INFO] --- maven-jar-plugin:3.0.2:jar (empty-javadoc-jar) @ tvm4j-core ---
 [WARNING] JAR will be empty - no content was marked for inclusion!
 [INFO] Building jar: /home/aishwarya/Downloads/tvm/jvm/core/target/tvm4j-core-0.0.1-SNAPSHOT-javadoc.jar
 [INFO]
 [INFO] --- maven-javadoc-plugin:2.9.1:jar (attach-javadocs) @ tvm4j-core ---
 [INFO] ------------------------------------------------------------------------
 [INFO] Reactor Summary for TVM4J Package - Parent 0.0.1-SNAPSHOT:
 [INFO]
 [INFO] TVM4J Package - Parent ............................. SUCCESS [ 0.846 s]
 [INFO] TVM4J Package - Core ............................... FAILURE [ 1.814 s]
 [INFO] TVM4J Package - Native Parent ...................... SKIPPED
 [INFO] TVM4J Package - Native Linux-x86_64 ................ SKIPPED
 [INFO] TVM4J Package - Full Parent ........................ SKIPPED
 [INFO] TVM4J Package - Full Linux-x86_64 .................. SKIPPED
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD FAILURE
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 3.034 s
 [INFO] Finished at: 2022-04-26T17:55:14+02:00
 [INFO] ------------------------------------------------------------------------
 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (attach-javadocs) on project tvm4j-core: MavenReportException: Error while creating archive: Unable to find javadoc command: The javadoc executable '/usr/lib/jvm/default-java/bin/javadoc' doesn't exist or is not a file. Verify the JAVA_HOME environment variable. -> [Help 1]
 [ERROR]
 [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
 [ERROR]
 [ERROR] For more information about the errors and possible solutions, please read the following articles:
 [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
 [ERROR]
 [ERROR] After correcting the problems, you can resume the build with the command
 [ERROR] mvn <args> -rf :tvm4j-core make: ***
 [Makefile:123: jvmpkg] Error 1

I have maven version: Apache Maven 3.6.3 openjdk version: openjdk 11.0.15


text:
Q: querySelector returns NULL I got a custom HTTP-500 error site from here. (codepen).
In the browser, this works as intended, at least when I'm watching the site at codepen.
When I copy the files to my IIS however, I get the error-message:
Uncaught TypeError: Cannot read property 'children' of null

Most basic example to reproduce on my machine is this:
<!Doctype HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>ASP 500 Error</title>
        <link rel="stylesheet" type="text/css" href="/error/style.css" />

Tested in IE and Chrome. Both work on codepen, neither does it locally.
I checked the references to the JS/CSS already and they work. On top of that, I tried to figure out if there are any 3rd party libs involved on codepens site, but it doesn't seem like it.


text:
Q: How do I reverse the order of two words in a string? I have a string like this:
$a = "Mike , Tree ";

I want to reverse it to "Tree, Mike".
Is there any function to do that?

A: Use the reverse function:
$reversed = join(",", reverse split(",", $string));

A: Split the string into two strings, flip them, and rejoin them.
Or, use a regex:
$a =~ s/(.+),(.+)/\2,\1/g;

A: If you are guaranteed the your string that you want to be reversed will be separated by commas then I would split the string at the comma and then go through the array it produces from the length of it to 0 and append it to an empty string.

A: Just for your problem.
$a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/;

[JJ@JJ trunk]$ perl -E '$a = "Mike , Tree "; $a =~ s/([A-Za-z]+)([^A-Za-z]+)([A-Za-z]+)/$3$2$1/; say $a;'
Tree , Mike


text:
Q: Change property of immutable type I have stored immutable types in a temporary CQRS read store (query/read side, in fact implemented by a simple List with abstraction access layer, I don't want to use a full blown document database at this point). These read stores contains items like the following:
public class SomeItem
{
    private readonly string name;
    private readonly string description;

    public SomeItem(string name, string description)
    {
        this.name = name;
        this.description = description;
    }

    public string Name
    {
        get { return this.name; }
    }

    public string Description
    {
        get { return this.description; }
    }
}

Now I want to change the Name and in a 2nd Command the Description.
These changes should keep the current state, which means for the example above:
// initial state
var someItem = new SomeItem("name", "description");

// update name -> newName
someItem = new SomeItem("newName", someItem.Description);

// update description -> newDescription
someItem = new SomeItem(someItem.Name, "newDescription");

This does look error prone to me if you have several properties... you have to manage keeping the current state. I could add something like Clone() to every type but I think/hope there is something better out there that performs well and is easy to use, I don't want to write much repetive code (lazy programmer). Any suggestions how to improve the code above? The SomeItem class needs to stay immutable (transported through several different threads).

A: Sadly, there's no simple way in C#. F# has the with keyword, and you could have a look at lenses, but it's all somewhat tedious in C#. The best I can give you is something like this:
class SomeItem
{
  private readonly string name;
  private readonly string description;

  public SomeItem(string name, string description)
  {
    this.name = name;
    this.description = description;
  }

  public SomeItem With
    (
      Option<string> name = null,
      Option<string> description = null
    )
  {
    return new SomeItem
      (
        name.GetValueOrDefault(this.name),
        description.GetValueOrDefault(this.description)
      );
  }
}

This allows you to do the updates like
var newItem = oldItem.With(name: "My name!");

I've used this approach with extension methods and T4s to great effect, but even when you write the code manually, it's reasonably reliable - if you add a new field, you must add it to the With as well, so it works quite well.
There's a few more approaches if you are willing to tolerate runtime code generation and reducing type safety, but that's kind of going against the grain IMO.

A: With C#9 we got the with operator for this purpose.
   public record Car
    {
        public string Brand { get; init; }
        public string Color { get; init; }
    }
    var car = new Car{ Brand = "BMW", Color = "Red" };
    var anotherCar = car with { Brand = "Tesla"};

With-expressions When working with immutable data, a common pattern is
to create new values from existing ones to represent a new state. For
instance, if our person were to change their last name we would
represent it as a new object that's a copy of the old one, except with
a different last name. This technique is often referred to as
non-destructive mutation. Instead of representing the person over
time, the record represents the person's state at a given time. To
help with this style of programming, records allow for a new kind of
expression; the with-expression:

News in C#9
NOTE
With operator is only supported by records.

Records At the core of classic object-oriented programming is the idea that an object has strong identity and encapsulates mutable state
that evolves over time. C# has always worked great for that, But
sometimes you want pretty much the exact opposite, and here C#'s
defaults have tended to get in the way, making things very laborious.

Recods in C#9

A: What you are looking for is commonly called the with operator:
// returns a new immutable object with just the single property changed
someItem = { someItem with Name = "newName" };

Unfortunately, unlike F#, C# does not have such an operator (yet?).
Other C# developers are missing this feature as well, which is why someone wrote a Fody extension to do exactly that:

*

*https://github.com/mikhailshilkov/With.Fody
Here's another approach, which implements an UpdateWith method manually but requires an Option<T> helper class. Luaan's answer describes this approach in more detail:

*

*Implementing F#-inspired "with" updates for immutable classes in C#

A: Simple solution
I also thought about this question. Record's are not suitable for my purposes, since it is necessary to interact with EF Core.
I suggest a simple and low-cost way:

*

*add a copy constructor to the class;

*Make properties that change during cloning available for initialization;

*clone an object with a change through the copy constructor with an initialization list:

var a = new SomeItem("name", "abracadabra");
var b = new SomeItem(a) {Description="descr"};

Simple code
var a = new SomeItem("name", "abracadabra");
var b = new SomeItem(a) {Description="descr"};

public class SomeItem
{
    private string name;
    private string description;

    public SomeItem(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public SomeItem(SomeItem another): this(another.Name, another.Description)
    {
    }

    public string Name
    {
        get => name;
        init => name = value;
    }

    public string Description
    {
        get => description;
        init => description = value;
    }
}

Extended solution
If the final type is not known at compile time, then this approach is easy to extend. Let's say there is a class "ValueObject" whose derived types we need to clone.
Note: I apologize for the incorrect translation in some places. English version obtained using google.translate
Additional code
using System.Linq.Expressions;
using Light.GuardClauses;
using JetBrains.Annotations;
using static DotNext.Linq.Expressions.ExpressionBuilder;

using ValueObject = Company.Domain....;

///
/// The plagiarizer creates a copy of the object with a change in its individual properties using an initializer
///
/// <remarks> The foreign object must define a copy constructor, and mutable members must support initialization </remarks>
public struct Plagiarist {
    ///
    /// Object to be copied
    ///
    private readonly object _alienObject;

    ///
    /// Type <see cref="_alienObject" />
    ///
    private Type _type => _alienObject.GetType();

    ///
    /// Object parsing Expression
    ///
    private readonly ParsingInitializationExpression _parser = new();

    public Plagiarist(object alienObject) {
        _alienObject = alienObject.MustNotBeNullReference();
        if (!CopyConstructorIs())
            throw new ArgumentException($"Type {_type.FullName} must implement a copy constructor");
    }

    ///
    /// Does the object we want to plagiarize have a copy constructor?
    ///
    /// <returns>True - there is a copy constructor, otherwise - false</returns>
    [Pure]
    private bool CopyConstructorIs() {
        return _type.GetConstructor(new[] { _type }) is not null;
    }

    ///
    /// Returns a copy of a foreign object with a change in its individual properties using an initializer
    ///
    /// <param name="initializer">
    /// <see cref="Expression" /> create an object with initialization of those fields,
    /// which need to be changed:
    /// () => new T() {Member1 = "Changed value1", Member2 = "Changed value2"}
    /// or <see cref="Expression" /> create an anonymous type with initialization of those fields
    /// that need to be changed:
    /// () => new {Member1 = "Changed value1", Member2 = "Changed value2"}
    /// </param>
    /// <returns></returns>
    [Pure]
    public object Plagiarize(Expression<Func<object>> initializer) {
        var (newValues, constructParam) = _parser.ParseInitialization(initializer);
        var constrCopies = _type.New(_alienObject.Const().Convert(_type));

        Expression plagiarist = (newValues.Count, constructParam.Count) switch {
            (> 0, _) => Expression.MemberInit(constrCopies, newValues.Values),
            (0, > 0) => Expression.MemberInit(constrCopies, ConstructorInInitializationList(constructParam).Values),
            _ => constrCopies
        };

        var plagiarize = Expression.Lambda<Func<object>>(plagiarist).Compile();

        return plagiarize();
    }

    [Pure]
    public Dictionary<string, MemberAssignment> ConstructorInInitializationList(
        Dictionary<string, Expression> constructorParameters) {
        Dictionary<string, MemberAssignment> initializer = new();
        const BindingFlags flagReflections = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public;
        var allProperties = _type.GetProperties(flagReflections);
        var allFields = _type.GetFields(flagReflections);

        foreach (var memberName in constructorParameters.Keys) {
            var property = allProperties.FirstOrDefault(s => s.Name ==memberName);
            var field = allFields.FirstOrDefault(s => s.Name == memberName);
            (MemberInfo member, Type memberType) = (property, field) switch {
                ({ }, _) => (property, property.PropertyType),
                (null, { }) => ((MemberInfo)field, field.FieldType),
                _ => throw new ArgumentException($"{_type.FullName} does not contain member {memberName}")
            };

            initializer[memberName] = Expression.Bind(member, constructorParameters[memberName].Convert(memberType));
        }

        return initializer;
    }

    ///
    /// Template "Visitor" for traversing the expression tree in order to highlight
    /// initialization expression and constructor
    ///
    private class ParsingInitializationExpression : ExpressionVisitor {
        private Dictionary<string, MemberAssignment>? _initializer;
        private Dictionary<string, Expression>? _initializerAnonym;

        ///
        /// Parses the expression tree and returns the initializer and constructor parameters
        ///
        /// <param name="initializer"><see cref="Expression" /> to parse</param>
        /// <returns> tuple of initializer and constructor</returns>
        public ParsedInitialization ParseInitialization(Expression initializer) {
            _initializer = new Dictionary<string, MemberAssignment>();
            _initializerAnonym = new Dictionary<string, Expression>();
            Visit(initializer);
            return new ParsedInitialization(_initializer, _initializerAnonym);
        }

        protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) {
            _initializer![node.Member.Name] = node;
            return base.VisitMemberAssignment(node);
        }

        protected override Expression VisitNew(NewExpression node) {
            foreach (var (member, value) in node.Members?.Zip(node.Arguments) ??
                                             Array.Empty<(MemberInfo First, Expression Second)>())
                _initializerAnonym![member.Name] = value;

            return base.VisitNew(node);
        }

        ///
        /// Type to return values from method <see cref="ParseInitialization" />
        ///
        /// <param name="Initializer"></param>
        /// <param name="ConstructorParameters"></param>
        public record struct ParsedInitialization(Dictionary<string, MemberAssignment> Initializer,
            Dictionary<string, Expression> ConstructorParameters);
    }
}

public static class ValueObjectPlagiarizer{
    ///
    /// Creates a copy of the object with a change in its individual properties using an initializer
    ///
    /// <param name="alien">Object to be plagiarized</param>
    /// <param name="initializer">
    /// <see cref="Expression" /> creating an object of type <typeparamref name="T" />
    /// with initialization of those fields that need to be changed:
    /// ob.Plagiarize(() => new T() {Member1 = "Changed value1", Member2 = "Changed value2"})
    /// or <see cref="Expression" /> create an anonymous type with initialization of those fields that need to be changed:
    /// ob.Plagiarize(() => new {Member1 = "Changed value1", Member2 = "Changed value2"})
    /// </param>
    /// <returns>plagiarism of the object</returns>
    public static object Plagiarize<T>(this ValueObject alien, Expression<Func<T>> initializer)
        where T : class {
        var bodyReduced = initializer.Convert<object>();
        var initializerReduced = Expression.Lambda<Func<object>>(bodyReduced, initializer.Parameters);

        return new Plagiarist(alien).Plagiarize(initializerReduced);
    }
}

Usages
If SomeItem is a descendant of ValueObject
ValueObject a = new SomeItem("name", "abracadabra");

// via type constructor
var b = (SomeItem)a.Plagiarize(()=>new SomeItem(null){Description="descr"});
// anonymous type
var c = (SomeItem)a.Plagiarize(()=>new{Description="descr"});

b.Description.Should().Be("descr"); //true
c.Description.Should().Be("descr"); //true

A: If what you want to do is (as you commented) update the name of an existing object, a readonly property might be bad design.
Otherwise if its really a new object you want to create, you might want your class to implement some interface with a 'Dispose' method.


text:
Q: Injecting a Resource into a Stateless Local EJB I have an @Local interface with an @Stateless implementation.
On the implementation is an @Resource(mappedName="java:/XXMail") javax.mail.Session.
It remains null though and isn't injected, but a JNDI lookup via an InitialContext works fine.
Any ideas what I can check or how I can debug this? Several of us have poured over this for a while without any luck. Apologies, I can't post code itself as it's on a closed network.

A: Although this certain issue might not be relevant any longer, the root problem and its solution may be valuable for others. In most cases the problem is caused by instantiating a new object of the implementating bean instead of using the proxy interface, like:
ObjectBean obj = new ObjectBean();

This will not trigger CDI and therfore all annotated resources will be null. Using the interface instead by looking up via JNDI or annotated resource will resolve the issue:
ObjectBeanInterface obj = new InitialContext().lookup("java:module/ObjectBean!org.mycompany.ObjectBeanInterface");


text:
Q: How to fix broken Windows update as files in Windows/Installer are removed? I made a mistake that removed files in C:\Windows\Installer and maybe some other hidden folders, in order to save disk space in C drive. But this action screwed Windows update, now the .net framework and some other SP updates are unable to either upgrade or un-install, due to unexpected errors of missing files...
Is there any chance that I can recover my system? To reinstall the whole OS is too costly...
Thanks
To add more info, I'm using windows server 2008 r2, installed .net framework, silverlight, visual studio and sql server 2008 r2.
The broken updates are several for .net framework, one for silverlight, one for visual studio, two SP for SQL server, one for office file validation.

A: I have solved broken .net framework updates by removing all version of it via a tool called '.NET FRAMEWORK CLEANUP TOOL', and solved more by install visual studio 2012.
I solved silverlight one via this link: http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_programs/error-c080fcdb9a28ldade0silverlightmsi-cannot-be/ac98ce14-a7c2-4f63-868b-c2f9145d0aaf
The other two main, vs2010sp1, sql server sp, are still left broken.


text:
Q: How to stop TCP Server from another Event in C# i am in the beginnning of building a small TCP Server.
Now i am stuck at the communication between two Events/Functions.
I got it work with Threads now.
But how can i close the Thread, and stop the Server?
It says it doesnt know client and server in the Button_stop Event.
The code in "Server" is the example code from microsoft, but that works.

My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace MTTCP
{
public partial class Form1 : Form
{
    //Declare Thread
    Thread Server_Thread;

    public Form1()
    {
        InitializeComponent();
    }

    private void Start_Click(object sender, EventArgs e)
    {
        //Start Backround Server Thread
        Server_Thread = new Thread(Server);
        Server_Thread.Start();
    }

    //Backround Server
    private void Server()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 80.
            Int32 port = 80;
            IPAddress localAddr = IPAddress.Parse("192.168.0.123");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                //Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                //Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    //Console.WriteLine("Received: {0}", data);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    //Console.WriteLine("Sent: {0}", data);
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            //Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }
        //Backround Server Ende

    }

    private void Stop_Click(object sender, EventArgs e)
    {
        //Here i want to stop the Thread an determine the Server

        client.Close(); //Does not work, doesnt know client
        server.Stop(); //Does not work, doesnt know server
    }
}
}

Regards
NetflixAndChill

A: It seems you are getting "client and server does not exist in the current context" error.
You have to change the scope of 'server' and 'client' variables to class-level to be able to access them in your Stop_Click eventhandler.
Regards,
Dileep.


text:
Q: How to extract all pages URL from a website using python 3? I want a list of all pages URL from a website. Following code does not return anything:
from bs4 import BeautifulSoup
import requests

base_url = 'http://www.techadvisorblog.com'
response = requests.get(base_url + '/a')
soup = BeautifulSoup(response.text, 'html.parser')

urls = []

for tr in soup.select('tbody tr'):
    urls.append(base_url + tr.td.a['href'])

A: The response from the backend is 406.
You can overcome that by specifying the user agent.
>>> response = requests.get(base_url + '/a', headers={"User-Agent": "XY"})

Python Requests HTTP Response 406
You can get the urls
>>> for link in soup.find_all('a'):
...     print(link.get('href'))
...
#content
https://techadvisorblog.com/
https://techadvisorblog.com
https://techadvisorblog.com/contact-us/
https://techadvisorblog.com/about-us/
https://techadvisorblog.com/disclaimer/
https://techadvisorblog.com/privacy-policy/
None
https://techadvisorblog.com/
https://techadvisorblog.com
https://techadvisorblog.com/contact-us/
https://techadvisorblog.com/about-us/
https://techadvisorblog.com/disclaimer/
https://techadvisorblog.com/privacy-policy/
None
https://techadvisorblog.com/
https://www.instagram.com/techadvisorblog
//www.pinterest.com/pin/create/button/?url=https://techadvisorblog.com/about-us/
https://techadvisorblog.com/contact-us/
https://techadvisorblog.com/
https://techadvisorblog.com/what-is-world-wide-web-www/
https://techadvisorblog.com/best-free-password-manager-for-windows-10/
https://techadvisorblog.com/solved-failed-to-start-emulator-the-emulator-was-not-properly-closed/
https://techadvisorblog.com/is-telegram-safe/
https://techadvisorblog.com/will-technology-ever-rule-the-world/
https://techadvisorblog.com/category/android/
https://techadvisorblog.com/category/knowledge/basic-computer/
https://techadvisorblog.com/category/games/
https://techadvisorblog.com/category/knowledge/
https://techadvisorblog.com/category/security/
http://Techadvisorblog.com/
http://Techadvisorblog.com
None
None
None
None
None
>>>

A: I am not sure why you are concatenating \a on the end of url as this re-directs to the about-us page. Also, I see no table/tr/td tags to work with on base url or about-us. Instead, if you meant to cycle through the two pages (or more) that are the pagination for the base url you can do this by testing for the presence of the rel attribute with value next. And yes, you need a valid User-Agent header.
import requests
from bs4 import BeautifulSoup as bs

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
}

page = 1
with requests.Session() as s:
    s.headers = headers
    while True:
        r = s.get(f'https://techadvisorblog.com/page/{page}/')
        soup = bs(r.content, 'lxml')
        print(soup.select_one('title').text)
        if soup.select_one('[rel=next]') is None:
            break
        page+=1


text:
Q: How does Sam know Quorra is an ISO? When they jump the freight train, Kevin Flynn starts to repair Quorra. This seems to be just a normal thing in repairing a program, but in the middle of doing so, Sam says is looking at the code which looks like some sort of digital DNA,

She's an ISO

How does he know that she is an ISO just by looking at something he obviously has never seen before?

A: The previous line was a bit of a giveaway.

Flynn: I've got to identify the damaged code. The sequencing is just enormously complex.
Sam: But didn't you write it?
Flynn: Some of it. The rest of it is just beyond me.

especially given that he's already talked about the ISOs emerging from chaos

Sam: And you created them?
Flynn: No. No. They manifested, like a flame.