text:
Q: Preserving new line in postgres column while inserting data in linux I am trying to insert  a row with a string column that contains new line character. The create table statement and insert query are given below.
create table stringtest(id int, inputstr character varying(200));

insert into stringtest values(1,'Name : NOC\r\n\r\nDetail : Detail');

The insert query is executed properly. However when the same row is fetched(when the postgres is in linux), the value of inputstr is not displayed with new line instead it is displayed as
 id |                     inputstr
----+---------------------------------------------------
  1 | Name : NOC\r\n\r\nDetail : Detail

While if we do the same in the windows, we get the resultset as desired as provided below
ngnms=# select * from stringtest;
 id |          inputstr
----+----------------------------
  1 | Site Name : NOC\r         +
    | \r                        +
    | Device Detail : agentdname
(1 row)

what should be done to get the result as desired with the new line instead of escape characters
Point to be added is if the same row is inserted using copy, the new line is preserved properly

A: I have fixed it by including E before the string with line feed as below
insert into stringtest values(1,E'Name : NOC\r\n\r\nDetail : Detail');


text:
Q: How to organize elements (pieces of Tetris) recursively I'm learning recursion but I need a reference on how to start making the algorithm. I need to organize blocks to use all the pieces, with the max possible fill of the board. Thanks to all.

A: Recursion has two main ideas, the first is that at each step the problem (so in this case the board) you are solving the problem should get smaller. The second important idea is that each step is the same.
So in this case it would be that you place a piece and then call the function again on the board now with the placed piece removed. Lets dive into them a little bit more.

*

*Each time you place a piece and call the function the number of locations you can place a piece is reduced.

*Every time you call the function again, you are still just trying to place tiles. So the problem stays consistent despite the problem space being smaller.

Hope this helps!

A: Here is a rather naive implementation of this algorithm to help you get started.
It is looking for a perfect solution (where the board is entirely filled) and will exit as soon as it finds one. This will work as expected for your example board, but it may run forever with other boards that do not have a simple perfect solution, or no perfect solution at all.
A better algorithm would:

*

*Look for the best solution for any board (not just the perfect one)

*Use more heuristics to speed up the search

The only refinement in this algorithm is the use of a hash table to avoid visiting the same board twice, when two different move combinations produce the same configuration.
Each row of the board is represented as a byte and each piece is represented as 2x2 bits.

var b = [
      // initial board
      0b00000000,
      0b00000000,
      0b00000100,
      0b00000000,
      0b00000000,
      0b00000000,
      0b00000000,
      0b00000000
    ],
    piece = [
      // bitmasks of pieces as [ top_bitmask, bottom_bitmask ]
      [ 0b11, 0b01 ], [ 0b11, 0b10 ], [ 0b01, 0b11 ], [ 0b10, 0b11 ]
    ],
    // hash table of visited boards
    hash = {},
    // statistics
    node = 0, hit = 0;

function solve(sol) {
  var x, y, p, s;

  // compute hexadecimal key representing the current board
  var key =
      ((b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)) >>> 0).toString(16) + '-' +
      ((b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24)) >>> 0).toString(16);

  node++;

  if(hash[key]) {
    // abort immediately if this board was already visited
    hit++;
    return false;
  }
  if(key == 'ffffffff-ffffffff') {
    // return the current solution if the board is entirely filled
    return sol;
  }

  // save board in hash table
  hash[key] = true;

  // for each position and each type of piece ...
  for(y = 0; y < 7; y++) {
    for(x = 0; x < 7; x++) {
      for(p = 0; p < 4; p++) {
        // ... see if we can insert this piece at this position
        if(!(b[y] & (piece[p][0] << x)) && !(b[y + 1] & (piece[p][1] << x))) {
          // make this move
          b[y]     ^= piece[p][0] << x;
          b[y + 1] ^= piece[p][1] << x;

          // add this move to the solution and process recursive call
          s = solve(sol.concat(x, y, p));

          // unmake this move
          b[y]     ^= piece[p][0] << x;
          b[y + 1] ^= piece[p][1] << x;

          // if we have a solution, return it
          if(s) {
            return s;
          }
        }
      }
    }
  }
  return false;
}

function display(sol) {
  var n, x, y, html = '';

  for(n = 0; n < 64; n++) {
    html += '

';
  }
  $('#container').html(html);

  for(n = 0; n < sol.length; n += 3) {
    for(y = 0; y < 2; y++) {
      for(x = 0; x < 2; x++) {
        if(piece[sol[n + 2]][y] & (1 << x)) {
          $('.cell').eq(7 - sol[n] - x + (sol[n + 1] + y) * 8)
            .addClass('c' + sol[n + 2]);
        }
      }
    }
  }
}

setTimeout(function() {
  display(solve([]));
  console.log(node + ' nodes visited');
  console.log(hit + ' hash table hits');
}, 500);
#container { width:160px; height:160px }
.cell { width:19px; height:19px; margin:1px 1px 0 0; background-color:#777; float:left }
.c0 { background-color:#fb4 }
.c1 { background-color:#f8f }
.c2 { background-color:#4bf }
.c3 { background-color:#4d8 }

Searching...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install Semantic ui for Next.js
I have one problem here and cant solve it. I want to install Semantic ui on Next.js application via npm but it's impossible please help me.
if u have some ideas please help me
npm install semantic-ui

I tried this one but nothing changes.

A: I use semantic-ui-react in my next.js project and I like to use my own theme. Follow the instructions below to get going.
First and foremost run npm install --save-dev semantic-ui. Soon you will see an interactive prompt. Answer questions presented the following way.

*

*Set-up Semantic UI - Choose 'Express (Set components and output folder)'

*We detected you are using NPM Nice! Is this your project folder? - Choose 'Yes'

*Where should we put Semantic UI inside your project? Hit return (This will put a directory named 'semantic' in root)

*What components should we include in the package? This is upto you. Check the ones you need and uncheck the ones you don't.

*Should we set permissions on outputted files? Choose 'No'

*Do you use a RTL (Right-To-Left) language? Pick your favourite option

*

*Where should we output Semantic UI? Write a custom path in your terminal ../static/semantic/dist
Now we are going to need gulp to run compilation tasks to build your theme.css under dist/ directory that you will use in your project.
Run yarn add --dev gulp
and add the following to your package.json under "scripts" like this
{
  "dependencies": {
    "next": "^7.0.2",
    "react": "^16.6.3",
    "react-dom": "^16.6.3"
  },
  "scripts": {
    "dev": "next",
    "build-semantic": "cd semantic && gulp build-css build-assets",
    "watch-semantic": "cd semantic && yarn run build-semantic && gulp watch"
  },
  "devDependencies": {
    "semantic-ui": "^2.4.2"
  }
}

Now if you run yarn watch-semantic, gulp will compile source files and create a dist/ under semantic/.  Under dist/ you will see semantic.min.css
We are just about done. Now you have to include this .css in page/component that is shared by all pages or components. Fortunately, next.js has a solution.
_document.js (https://nextjs.org/docs/#custom-document)
Create _document.js under pages/ and include your recently created semantic.min.css like below.
import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <html>
        <Head>
          <link
            href="/static/semantic/dist/semantic.min.css"
            rel="stylesheet"
          />
        </Head>
        <body className="custom_class">
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

A: If you want to do the following in _app.js:
import 'semantic-ui-css/semantic.min.css'

You will need: https://github.com/zeit/next-plugins/tree/master/packages/next-css.
Then, you can follow the advice I found here: https://github.com/zeit/next-plugins/issues/432.
Specifically, see antonioOrtiz 24 Mar comment.

A: There's a nice starter project that uses Next.js + Fomantic-UI + Styled Components.
https://github.com/skydiver/nextjs-semantic
For Semantic-UI version, check out v1.1.0 branch.
https://github.com/skydiver/nextjs-semantic/tree/v1.1.0

A: Another alternative I haven't seen mentioned in the comments yet:
Create a layout wrapper around your pages and import there the library CSS from the CDN.
import Head from 'next/head';

const Layout = () => (
    <>
        <Head>
            <link href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css" rel="stylesheet" />
        </Head>
        {children}
    </>
);

export default Layout;

And in your pages:
import Layout from '@components/Layout';

const AboutPage = () => (
        <Layout>
            <article>
               I am the about page
            </article>
        </Layout>
);

export default AboutPage;

It will allows to do some quick tests without having to install any additional packages.


text:
Q: Vector editor Adobe Flash CC alternatives I'm looking some vector editing tool which can allow me do next drawing:
https://youtu.be/nbyqhru41co
(I made this sketch in 2 minutes with Adobe Flash CC)
Requirements:

*

*Auto snapping - cursor is snapped to line ending or segment center;

*Easy select part of object - select side of square with one click, select big object with double click, select everything in rectangle selection;

*Auto detect lines intersection;

*Layers support.

Optional requirements:

*

*OS Windows;

*Free or OpenSource.

I've tried Inkscape but it's hard to use. Can't find how to select part of square, how to detect lines intersection. Can't understand object and path concepts and why do I need to convert one to another?


text:
Q: Квадратный корень из числа, записанного в текстовом файле Необходимо создать программу, которая будет читать число из файла и вычислять корень из этого числа и записывать результат в новый текстовый файл. Проблема заключается в том, что выводится неправильный ответ, подскажите в чем ошибка
 using (StreamReader sr = new StreamReader("file.txt"))
        {
            string numbers = sr.ReadLine();

            int countOfElements;
            int sqrtOfElement = 0;

            String[] number = numbers.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            countOfElements = numbers.Length;

            for (int count = 0; count < countOfElements; count++)
            {
                sqrtOfElement += Convert.ToInt32(Math.Sqrt(numbers[count]));
            }

            File.WriteAllText("result.txt", sqrtOfElement.ToString());

            Console.WriteLine(sqrtOfElement);

            Console.ReadKey();
        }

Если записать в текстовом файле число 9, то в результате получается 8 вместо 3


text:
Q: How To Make 'Submit' Button Refresh Page? On my website I have a 'Contact Us' form.
Currently, I am using a php form to have the information that has been filled out on the form to be e-mailed to my e-mail.
I wanted an echo message to come up once someone clicks on submit, but instead it's going to another page with the message there.
I just want the page to refresh.
This is the PHP Code:
     <?php

   //echo $emailBody;
   sendEmail();

 function sendEmail(){
 global $emailBody, $name, $from, $fromName, $templateFile, $to, $subject;

     $headers  = "MIME-Version: 1.0" . "\r\n";
     $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
     $headers .= "Reply-To: ". $from . "\r\n";
     $headers .= "From: ". $from . "\r\n";
     $headers .= "Return-Path: ".$from;

     if (!mail($to, $subject, $emailBody, $headers)) {

    } else {

    echo "Your Message has been sent!we will contact back you in a short moment!";
    }

}

 ?>

A: PHP will always send you a new page because it is a server side language. In order for this code to be executed when a user clicks the button and then the results shown to the user, the request must be sent to the server, executed, and then sent back to the user. The only way you can 'refresh' a page like you are requesting is to use a client side language such as javascript.
It is like this: When user clicks the submit button they are requesting that PHP process the request. This can only take place on the server. Because the request goes from user to server and then back to user, you will always get a new page.

A: Need a little more code, but typically when doing something like this, you would have the form submit back to iself and at the top of the php, do some isset(-form variable -) checking, if they are filled out then you can enter a function to process from there and subsequently echo a message to the user indicating success/failure.

A: I'd use:

<meta http-equiv="refresh" content="1" />

You can also specify this with a header (the meta-refresh only emulates this header):
header('Refresh: 1');

It is also nice to leave the user a message such as:

If this page doesn't automatically refresh in one second click here.

A: change your action
<form action="This is where your webpage goes" method="POST">

so this will send your page to google:
<form action="http://google.com" method="POST">

if you remove the action, it will reload the current page, like this:
<form method="POST">

just put your php in the same page as your <form>.
like the following
<?php

if($_POST['submit'] == 'send'){

     sendEmail();

     function sendEmail(){
     global $emailBody, $name, $from, $fromName, $templateFile, $to, $subject;

         $headers  = "MIME-Version: 1.0" . "\r\n";
         $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
         $headers .= "Reply-To: ". $from . "\r\n";
         $headers .= "From: ". $from . "\r\n";
         $headers .= "Return-Path: ".$from;

        if (!mail($to, $subject, $emailBody, $headers)) {

        } else {
           echo "Your Message has been sent!we will contact back you in a short moment!";
        }

    }
}

//For that to work your button needs to be like this
?>
<form method="POST">

    <input type="submit" name="submit" value="send" />
</form>

A: before you echo you can redirect to the source page with the message that you want to show up there
for example
if (!mail($to, $subject, $emailBody, $headers)) {

    } else {
  $myMsg="Your Message has been sent!we will contact back you in a short moment!";
  header('location: yourpage');
}

and in your page you can check out if there is any message like this
if(isset($myMsg))
{
 echo $myMsg; // in the place & style that you want
}


text:
Q: error: remote unpack failed: eof before pack header was fully read Before that I got a problem error: object file is empty cause my laptop sunddenly turn off. I was fixed with this. My local repo was fixed and I try to pull and push to remote master. But I have a problem like this
$ git push -u origin master
Counting objects: 26, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (22/22), done.
fatal: unable to read c779d43453f63d871ba2a079b79f04558d9b0920
error: remote unpack failed: eof before pack header was fully read
error: failed to push some refs to 'git@bitbucket.org:xxxx/xxxx.git'

How to fix my remote repo? I can't push my new commit cause broken remote repo
How to fix unable to read c779d43453f63d871ba2a079b79f04558d9b0920 on remote repo?

A: It happened for me on macOS Big Sur and upgrading my git version fixed it. Initial version was 2.23.0, upgraded to git version 2.29.2.

A: git fsck

did the trick and solved it for me

A: I had the same problem yesterday, my laptop shut down unexpectedly. So I had to re-create git.
First of all, remove the .git folder from your directory.
rm -rf .git

Then create renew git.
git init

All the tracking will become new, so you have to commit all the new changes and add your remote repository
git remote add origin <repo URL>

If for example, you were on the "development" branch. Go ahead create a development branch
git branch development && git checkout development

Now after switching to the development branch, pull from the remote branch.
git pull origin development --allow-unrelated-histories

You may face conflicts, resolve them and you are good to go.

A: Your local repository isn't fixed, because this message:

fatal: unable to read c779d43453f63d871ba2a079b79f04558d9b0920

came from your own Git, while it was trying to package data to send to the remote.  (The way to know this is that it's not prefixed by remote:.)  The remaining errors:

error: remote unpack failed: eof before pack header was fully read
error: failed to push some refs to 'git@bitbucket.org:xxxx/xxxx.git'

are consequences of this.
This problem has not affected the other repository in any way, so you can make a new clone of the other repository and do whatever you can to extract useful data from your not-quite-fixed repository to add to the new (good) clone.

A: It can be due to comparatively large size/number of files in the commit. When tried with zipping, it worked for me

A: I'm on a shared hosting and I had the same problem while trying to push master for the first time.
But this did the trick:
git config --global pack.windowMemory "100m"
git config --global pack.packSizeLimit "100m"
git config --global pack.threads "1"

A: I had this occur for me in a number of repos, I eventually traced it back to the repos being stored inside of my Dropbox and "selective sync" being applied. As a result the .git folder wasn't fully available locally.
Going into the folder in finder and selecting selective sync > local fixed it.
The parent folder was marked to be synced, but Dropbox seems to assume that hidden folders probably aren't important.

A: I had a similar error with git 2.19.0 which was fixed by updating to git 2.20.1. I believe in my case git crashed while trying to compress a specific object (it only got to "Compressing objects: 31%") and then the server returned that error due to the sending process having crashed.
I hope this helps someone.

A: Another way this error can occur is when working with Git submodules and trying to push to the remote (even with --force) when the local repository has not pulled yet the newer references from the remote.
The solution for this use case is to update the submodule(s) like so:
git submodule update --remote

In this case, performing git fsck will also result in an error (commit hash cut off for brevity):
$ git fsck
Checking object directories: 100% (256/256), done.
Checking objects: 100% (3628/3628), done.
error: refs/remotes/origin/some/branch: invalid reflog entry 1c857


text:
Q: MikroTik and c# API: get radio-name with ':put' command I have an issue. I want to get radio-name through the C# api for winbox. In winboxs terminal works :put [/interface wireless get [/interface wireless find default-name=wlan1] radio-name] command, but not in C# api. I rode that, in api i can't uses [ ] marks, but i dont know how it write without it. I tried like this:
mikrotik.Send("/put ", true);
mikrotik.Send(".system identity get name", true);
foreach (string h in mikrotik.Read())
    {
         mkResult += h;
    }

l_identify.Text = mkResult;

but its doesn't work. Everytime i get this:
!trap=category=0=message=no such command or directiory (put [)!trap=message=no such command prefix!done
Please help :<
PS: Sorry for my English :P

A: You are sending incorrect commands to the device.
You need to use this:
/interface/wireless/print
=.proplist=radio-name
?default-name=wlan1

.proplist contains list of fields to be returned, ?default-name=wlan1 is a condifion for filtering.
You can find more about Mikrotik API syntax in the official Wiki.


text:
Q: three.js: camera changes position, but it doesn't show I have a program where camera.position.[x|y|z] changes according to mouse position. This is verified by this console output:

However, the rendering of the object at which the camera is looking, doesn't change. It stands still, as can be seen here:
https://dl.dropbox.com/u/2070405/stackoverflow2/index.html
How do I best approach debugging such behavior?
The program consists of index.html, js/main.js, js/myLibs/dragPanControls.js*, js/require.js, js/libs/three.js/build/three.js
This is main.js:
// CONFIGURE require.js BEFORE LOADING MODULES:

requirejs.config({
    shim: {
        'libs/three.js/build/three': {
            deps: [],
            exports: 'three' //'three' will not be accessible, but any values that three.js writes to the global object will become available to me if I import 'three'.
            /*init: function () {
                // if I want 'three' to actually refer to something, I can do so by returning whatever I want it to refer to, in this init function
                console.log("init three. Is THREE available? ", THREE);
                return this;
            }*/
        }
    }
});

// NOW START LOADING MODULES:

require(["myLibs/dragPanControls", "libs/three.js/build/three", "myLibs/testlib"], function(DPC, three, testlib) {
    console.log("Function call called after all modules are loaded and accessible");

// HELLO WORLD EXAMPLE:

    var camera, scene, renderer;
    var geometry, material, mesh;

    init();
    animate();

    function init() {

        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
        camera.position.z = 1000;

        scene = new THREE.Scene();

        geometry = new THREE.CubeGeometry(200, 200, 200);
        material = new THREE.MeshBasicMaterial({
            color: 0xff0000,
            wireframe: true
        });

        mesh = new THREE.Mesh(geometry, material);
        scene.add(mesh);

        renderer = new THREE.CanvasRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);

        document.body.appendChild(renderer.domElement);

        console.log("DPC? ", DPC);
        console.log("testlib.success? ", testlib.success);
        //console.log("DragPanControls? ", DragPanControls);
        console.log("DPC.DragPanControls? ", DPC.DragPanControls);
        cameraControls  = new DPC.DragPanControls(camera);

    };

    function animate() {

        // note: three.js includes requestAnimationFrame shim
        requestAnimationFrame(animate);

        //mesh.rotation.x += 0.01;
        //mesh.rotation.y += 0.02;

        cameraControls.update();

        console.log("camera.position.x: ", camera.position.x);

        renderer.render(scene, camera);

    };

});

This is js/myLibs/dragPanControls.js:
/** @namespace */
define(["../libs/three.js/build/three"],
    function () {

        // Setup work:

        var DragPanControls;

        DragPanControls = function(object, domElement)
        {
            console.log("drapancontrols kan finde THREE? ", THREE);

            this._object    = object;
            this._domElement= domElement || document;

            // parameters that you can change after initialisation
            this.target = new THREE.Vector3(0, 0, 0);
            this.speedX = 0.03;
            this.speedY = 0.03;
            this.rangeX = -40;
            this.rangeY = +40;

            // private variables
            this._mouseX    = 0;
            this._mouseY    = 0;

            var _this   = this;
            this._$onMouseMove  = function(){ _this._onMouseMove.apply(_this, arguments); };
            this._$onTouchStart = function(){ _this._onTouchStart.apply(_this, arguments); };
            this._$onTouchMove  = function(){ _this._onTouchMove.apply(_this, arguments); };

            this._domElement.addEventListener( 'mousemove', this._$onMouseMove, false );
            this._domElement.addEventListener( 'touchstart', this._$onTouchStart,false );
            this._domElement.addEventListener( 'touchmove', this._$onTouchMove, false );
        }

        DragPanControls.prototype.destroy   = function()
        {
            this._domElement.removeEventListener( 'mousemove', this._$onMouseMove, false );
            this._domElement.removeEventListener( 'touchstart', this._$onTouchStart,false );
            this._domElement.removeEventListener( 'touchmove', this._$onTouchMove, false );
        }

        DragPanControls.prototype.update    = function(event)
        {
            this._object.position.x += ( this._mouseX * this.rangeX - this._object.position.x ) * this.speedX;
            this._object.position.y += ( this._mouseY * this.rangeY - this._object.position.y ) * this.speedY;
            this._object.lookAt( this.target );

            //console.log("this._mouseX: ", this._mouseX);
            //console.log("this.rangeX: ", this.rangeX);

            //console.log("this._object.position.x: ", this._object.position.x);
            //console.log("this._object.position.y: ", this._object.position.y);
        }

        DragPanControls.prototype._onMouseMove  = function(event)
        {
            this._mouseX    = ( event.clientX / window.innerWidth ) - 0.5;
            this._mouseY    = ( event.clientY / window.innerHeight) - 0.5;
        }

        DragPanControls.prototype._onTouchStart = function(event)
        {
            if( event.touches.length != 1 ) return;

            // no preventDefault to get click event on ios

            this._mouseX    = ( event.touches[ 0 ].pageX / window.innerWidth ) - 0.5;
            this._mouseY    = ( event.touches[ 0 ].pageY / window.innerHeight) - 0.5;
        }

        DragPanControls.prototype._onTouchMove  = function(event)
        {
            if( event.touches.length != 1 ) return;

            event.preventDefault();

            this._mouseX    = ( event.touches[ 0 ].pageX / window.innerWidth ) - 0.5;
            this._mouseY    = ( event.touches[ 0 ].pageY / window.innerHeight) - 0.5;
        }

        // Return module:
        return {
            DragPanControls: DragPanControls
        };
    }
);

*kindly lended from jeromeetienne

A: You are using code you copied from the net that was designed to work with an older version of the library.
Instead, use a any one of a number of camera controllers available in the three.js examples/js/controls directory. For example:
controls = new THREE.OrbitControls( camera );

These controls are not part of the library as of r.52, so you will have to include the source explicitly.
Here is a Fiddle that shows the use of a camera controller: http://jsfiddle.net/WV49w/3/


text:
Q: Change the style of the table of contents in appendix This question was asked in the StackOverflow Russian segment, but was not answered. The question was translated automatically with some corrections, I hope I can get an answer to it here.
I am doing my graduation thesis. At the end of the thesis, there should be appendixes that must be contained in a certain way, in contrast to the thesis itself, an approximate form:
Table of contents

1 Chapter name ......page
  1.1 Section name ......page
     1.1.1 Subsection name ......page
Appendix А ......page
Appendix B ......page

That is:

*

*If the appendix has sections - they should not be displayed in toc

*Appendix titles shouldn't show up either in toc

I tried to highlight the minimum working code that shows the problem:
\documentclass[fontsize=14bp,a4paper]{scrreprt}

% Подключение пакетов
%===================================================
\usepackage{polyglossia}    %для русского языка
\usepackage[left=25mm, right=15mm, top=20mm, bottom=20mm, footskip=10mm]{geometry} %задаёт поля документа
\usepackage{tocloft} %пакет для оформления оглавления
\usepackage{titlesec} %пакет для оформления заголовков
\usepackage[nottoc]{tocbibind} %добавление списка источников в оглавление
\usepackage[titletoc]{appendix} %добавление приложений в оглавление

% Установка параметров для документа
%===================================================
\setdefaultlanguage[forceheadingpunctuation=false]{russian}  % устанавливает главный язык документа, опция - убирает последнюю точку в нумерации заголовков
\setotherlanguage{english} % объявляет второй язык документа
\pagestyle{plain} %номера страниц будут печататься снизу и при этом колонтитулов не будет
\defaultfontfeatures{Ligatures={TeX}, Renderer=Basic}
\setmainfont{Liberation Serif}
\setsansfont{Liberation Serif}
\setmonofont{Liberation Mono}
\parindent=1.25cm %красная строка

\renewcaptionname{russian}{\contentsname}{\normalsize \MakeUppercase{Содержание}} %заголовок оглавления
\renewcaptionname{russian}{\appendixname}{Приложение} %заголовок приложений
\renewcommand{\cftchapleader}{\cftdotfill{\cftdotsep}} % заполнение точками Глав в оглавлении

%параметры заголовков разделов (глав)
\titleformat{\chapter}[hang]{\normalsize\bfseries}{\thechapter~}{0pt}{\thispagestyle{empty}\MakeUppercase}
\titlespacing{\chapter}{\parindent}{0bp}{2\baselineskip}
%параметры заголовков подразделов (секций)
\titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
\titlespacing{\section}{\parindent}{\baselineskip}{\baselineskip}
\titleformat{\subsection}[hang]{\normalsize\bfseries}{\thesubsection~}{0pt}{}
\titlespacing{\subsection}{\parindent}{\baselineskip}{\baselineskip}

\begin{document}
    \begin{titlepage}
        Титульный лист
    \end{titlepage}

    \tableofcontents{}
    \thispagestyle{empty}
    \clearpage

    \chapter{Первая}
        \section{Первый}
            \subsection{первый}

    \chapter{Вторая}
        \section{Второй}
            \subsection{второй}

    \begin{appendices}
        \titleformat{\chapter}[display]{\normalsize\bfseries}{\centering\appendixname~\thechapter}{0pt}{\centering\thispagestyle{empty}\MakeUppercase}
        \titlespacing{\chapter}{\parindent}{0bp}{\baselineskip}
        \titleformat{\section}[hang]{\normalsize\bfseries}{\thesection~}{0pt}{}
        \titlespacing{\section}{0bp}{0bp}{\baselineskip}

        \chapter{Первое приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}

        \chapter{Второе приложение}
            \section{Первый}

            \section{Второй}

            \section{Третий}
    \end{appendices}
\end{document}

I found ~3 solutions to this issue, but none of them work:

*

*Command \addtocontents{toc}{\setcounter{tocdepth}{0}} - the compiler throws an error (and a similar solution is to declare a separate command for this)

*tocvsec2 package with \settocdepth{chapter} command - just doesn't work, completely ignored

There are suspicions that there are some conflicts - therefore, none of the methods is not working. As for removing headings from the content, I also did not find any solution, but I suspect that it needs to be substituted in the appendices environment. I also searched in the documentation of the tocloft package, which I use.
Distribution: TeXLive
Compiler: XeLaTeX

A: Do not use packages tocloft, titlesec, tocbibind and appendix together with a KOMA-Script class.
Here is a suggestion without these packages:
\documentclass[
  fontsize=14bp,
  %a4paper,% default
  appendixprefix,% use prefix for appendix chapters
  numbers=noenddot
]{scrreprt}

\KOMAoption{toc}{%
  listof,% LoF and LoT etc. get unnumbered ToC entries
  bibliography,% bibliography gets unnumbered ToC entry
  index,% index gets unnumbered ToC entry
  chapterentrywithdots% dots between chapter heading and page number in ToC
}

% Подключение пакетов
%===================================================
\usepackage{polyglossia}    %для русского языка
\usepackage[left=25mm, right=15mm, top=20mm, bottom=20mm, footskip=10mm]{geometry} %задаёт поля документа

% Установка параметров для документа
%===================================================
\setdefaultlanguage[forceheadingpunctuation=false]{russian}  % устанавливает главный язык документа, опция - убирает последнюю точку в нумерации заголовков
\setotherlanguage{english} % объявляет второй язык документа
\pagestyle{plain} %номера страниц будут печататься снизу и при этом колонтитулов не будет
\defaultfontfeatures{Ligatures={TeX}, Renderer=Basic}
\setmainfont{Liberation Serif}
\setsansfont{Liberation Serif}
\setmonofont{Liberation Mono}

%\parindent=1.25cm %красная строка
\newlength{\myparindent}
\setlength{\myparindent}{1.25cm}
\setparsizes{\myparindent}{0pt}{0pt plus 1fil}

\renewcaptionname{russian}{\contentsname}{Содержание} %заголовок оглавления
\renewcaptionname{russian}{\appendixname}{Приложение} %заголовок приложений

%параметры заголовков разделов (глав)
\RedeclareSectionCommand[
  font=\normalfont\normalsize\bfseries,
  beforeskip=0bp,
  afterskip=2\baselineskip,
  innerskip=0bp
]{chapter}
\renewcommand{\chapterpagestyle}{empty}
\makeatletter
\renewcommand{\chapterlinesformat}[3]{%
  \@hangfrom{\hskip\myparindent #2}{\MakeUppercase{#3}}%
}
\makeatother
\renewcommand{\chapterlineswithprefixformat}[3]{%
  #2\MakeUppercase{#3}%
}
\renewcommand{\chapterformat}{\chapappifchapterprefix{\ }\thechapter~}

%параметры заголовков подразделов (секций)
\RedeclareSectionCommands[
  font=\normalfont\normalsize\bfseries,
  beforeskip=\baselineskip,
  afterskip=\baselineskip,
  indent=\myparindent,
  afterindent=false
]{section,subsection}
\renewcommand{\sectionformat}{\thesection~}
\renewcommand{\subsectionformat}{\thesubsection~}

\newcommand\originalappendix{}
\let\originalappendix\appendix
\renewcommand{\appendix}{%
  \originalappendix
  \renewcommand{\raggedchapter}{\centering}%
  \RedeclareSectionCommand[afterskip=\baselineskip]{chapter}%
  \RedeclareSectionCommand[beforeskip=0bp,indent=0bp]{section}%
  \addtocontents{toc}{\protect\value{tocdepth}=\chaptertocdepth}% appendix sections etc. not shown in ToC
  \renewcommand\addchaptertocentry[2]{%
    \addtocentrydefault{chapter}{}{\appendixname~##1}%
  }% appendix titles not shown in ToC
}

\begin{document}
\begin{titlepage}
  Титульный лист
\end{titlepage}
\tableofcontents
\chapter{Первая}
  \section{Первый}
    \subsection{первый}
\chapter{Вторая}
  \section{Второй}
    \subsection{второй}

\appendix
\chapter{Первое приложение}
  \section{Первый}
  \section{Второй}
  \section{Третий}
\chapter{Второе приложение}
  \section{Первый}
  \section{Второй}
  \section{Третий}
\end{document}


text:
Q: Headings with a hanging subhead I use this piece of code to add a subhead (usually a quick reference) in my notes:
\newcommand{\mysection}[2]{\section[#1]{#1\\*[.6ex]\normalsize\textit{#2}}}

I'd like to make the subtitle hanging from the section number, which for sections I have managed to do with
\newcommand{\mysection}[2]
  {\section[#1]{#1\\*[.6ex] \normalsize\textit{\hphantom{\Huge\thesection}#2}}}
  % I'm quite sure there is a cleaner way.

but this approach doesn't work with subsections for none of the sizes of the phantom number properly aligns the subhead.
Should I use a box instead of the \hphantom?
N.B. I use
 \documentclass[twoside,fleqn]{scrartcl}
 \setkomafont{disposition}{\normalcolor\bfseries}

Edit
@karlkoeller Your code works. I've added a subtitle referring to the Wikipedia to your MWE, it spits out a text that is a tiny little bit out of alignment (I've cut out the numbers):

But I guess it is because of the italics.

A: The right amount of spacing for the section (in scrartcl class) is given by
\hphantom{\thesection\enskip}

typeset in upright \Large characters.
So your definition for \mysection is wrong, and should be instead:
\newcommand{\mysection}[2]
  {\section[#1]{#1\\*[.6ex]\Large\textup{\hphantom{\thesection\enskip}}\normalsize\textit{#2}}}

A similar \mysubsection command can be defined, remembering that for a subsection the amount of spacing is given by
\hphantom{\thesubsection\enskip}

typeset in upright \large characters:
\newcommand{\mysubsection}[2]
  {\subsection[#1]{#1\\*[.4ex]\large\textup{\hphantom{\thesubsection\enskip}}\small\textit{#2}}}

The following MWE
\documentclass[twoside,fleqn]{scrartcl}
 \setkomafont{disposition}{\normalcolor\bfseries}

\newcommand{\mysection}[2]
  {\section[#1]{#1\\*[.6ex]\Large\textup{\hphantom{\thesection\enskip}}\normalsize\textit{#2}}}

\newcommand{\mysubsection}[2]
  {\subsection[#1]{#1\\*[.4ex]\large\textup{\hphantom{\thesubsection\enskip}}\small\textit{#2}}}

\begin{document}

\mysection{A section}{A section subtitle}

\mysubsection{A subsection}{A subsection subtitle}

\end{document}

gives the desired result

For references, see p.99 of the KOMA-Script manual

The original
  definitions for the KOMA-Script classes are:
\newcommand*{\sectionmarkformat}{\thesection\autodot\enskip}
\newcommand*{\subsectionmarkformat}{\thesubsection\autodot\enskip}

In your case, \autodot produces no spacing since you are not using the option numbers=enddot or equivalent.


text:
Q: AJAX call fails in phonegap app I have an error like "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.localhost:56891' is therefore not allowed access." and my code look like this:
 $.ajax({
 url: 'http://192.168.4.12:90/api/gps',
 type: "GET",
 dataType: "json",
 success: function (data) {
 alert("success");
 },
 error: function (xhr, type) {
 alert("Error connecting to the servers");
 }
 }, 'json');

I have a WebApi project on localhost and i put in IIS, and it returns my json ok if i put the link in a web browser,but in the phonegap project always falls. I put
<access origin="*"/>  in config.xml, but is the same error.
If someone can help me please, because i'm looking for two weeks for an solution and nothing works.

A: You can try 'jsonp' instead of 'json' for the data type.


text:
Q: counting related fields in two tables I have these two tables.
foo
+----+--------+
| id | letter |
| 1  | A      |
| 2  | B      |
| 3  | C      |
| 4  | D      |
+----+--------+

bar
+----+------+--------+--------+
| id | name | foo_id | status |
| 1  | fox  | 1      | 1      |
| 2  | cat  | 1      | 0      |
| 3  | dog  | 3      | 1      |
| 4  | bird | 5      | 1      |
| 5  | cow  | 5      | 0      |
+----+------+--------+--------+

Now, I want to count the occurrences of the letter in the bar table with only status equals 1
So LEFT JOIN states
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
This is the result I want.
+--------+-------+
| letter | count |
| A      | 1     |
| B      | 0     |
| C      | 1     |
| D      | 0     |
| E      | 1     |
+--------+-------+

What I have tried so far.
SELECT letter, count(foo_id) AS count
FROM foo f LEFT JOIN bar b on f.id = b.foo_id
GROUP BY letter

I know my query is wrong because it does not filter the status with 1. But when I try to add WHERE status = 1 to my query. Seems off.
What should be the query to achieve my desired result?

A: You need to add your filter to the join predicate:
SELECT letter, count(foo_id) AS count
FROM   foo f
       LEFT JOIN bar b
         ON f.id = b.foo_id
         AND b.status = 1
GROUP BY letter;

Putting it in the where clause will effectively turn your left join into an inner join, because where there is no match in bar, you will end up with WHERE NULL = 1, which is not true, so this record from foo will not be returned.


text:
Q: Hadoop 2.7.3 Java Runtime error - core-site.xml not found When running the hdfs dfs -mkdir /abc I get the following error.
Exception in thread "main" java.lang.RuntimeException: core-site.xml not found
at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:2577)
at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:2503)
at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:2409)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1144)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:1116)
at org.apache.hadoop.conf.Configuration.setBoolean(Configuration.java:1454)
at org.apache.hadoop.util.GenericOptionsParser.processGeneralOptions(GenericOptionsParser.java:319)
at org.apache.hadoop.util.GenericOptionsParser.parseGeneralOptions(GenericOptionsParser.java:485)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:170)
at org.apache.hadoop.util.GenericOptionsParser.<init>(GenericOptionsParser.java:153)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:64)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
at org.apache.hadoop.fs.FsShell.main(FsShell.java:372)

the path to my core-site.xml is /usr/local/hadoop/etc/hadoop/core-site.xml.
How to fix this error?

A: Can you try to set the below variable in ~/.bash_profile or at the start of the script.
export HADOOP_CONF_DIR=**location of your hadoop in local**

like (/home/hadoop/hadoop-2.7.3/etc/hadoop )
You can also look into the below link :
https://community.cloudera.com/t5/Storage-Random-Access-HDFS/RuntimeException-running-the-hdfs-command-core-site-xml-not/td-p/28224


text:
Q: Training a model on samples with both correct and wrong (non-noise) labels When we train a model, we usually use pairs of $(x_n,\ label_n)$ as training data. In my case, I have pairs of $(x_n, \ label_n)$ and also pairs of $(x_n,\ wrong\_label_n)$, where both $label$ and $wrong\_label$ come from the same set of labels. Note: the wrong labels are known, not noise.
Is there any way to train on samples with known wrong and correct labels instead of training on correct labels only? Maybe a modified loss function I can use? I don't really mind what kind of model it works for (regressions, CART, ANNs etc).

A: It's a good question. There are similar works in the field of clustering (aka constrained clustering, where you provide "must link" and "cannot link" connections as input to the algorithm), but I'm not aware of anything along these lines for classification using neural networks.
As a first attempt, I would probably do something along these lines:
First, convert your labels to the format $([true\_labels], [false\_labels])$. For example, if I do animal classification:

*

*Image1, which I know is of a cat, would be labeled $([cat], [])$

*Image2, which I'm sure is not a whale would be $([], [whale])$

I would then adapt the loss function appropriately. For example, standard 0-1 loss could be extended to this case by paying a penalty of 1 for either of the two following scenarios: Either classifying an animal differently than its' true label (classifying Image1 as whale) or classifying an animal to be a something which I know is not the true label (classifying Image2 to be a whale).
For example, in the simple case in which we allow a single label for each case (true label and false label), then the regular 0-1 loss, $\sum _{x,y} {1[h(x)\neq y ]} $, will become:
$\sum _{x,y=(y_{true},y_{false})} {1[h(x)\neq y_{true} \lor h(x)=y_{false}]} $

A: The key is to notice that your problem is equivalent to machine learning with overlapping classes.
Given item $x_n$ and information that it does not belong to class $L_i$, notice that
$x_n \notin L_i \iff x_n \in (L \setminus L_i)$
and, for another class $L_j$,
$L_i \cap L_j = \emptyset \Rightarrow L_j \in (L \setminus L_i)$
so
$x_n \in L_j, x_n \notin L_i \Rightarrow x_n \in L_j \subseteq (L \setminus L_i)$
You can thus define $L'_i:= L \setminus L_i$. These new classes work just like regular classes, and can contain the regular classes defined earlier.
Unfortunately, this does not mean that the classification is hierarchical (which would simplify matters), since for two classes $L'_i$ and $L'_j$ these classes might have a non-zero intersection. Consider $x_1, x_2 \notin L_1$ and $x_2, x_3 \notin L_2$. Then, $L'_1$ and $L'_2$ overlap, but one is not contained in the other.
I don't know much about ML with overlapping classes; I know the problem is considered to be tough and that there are definitely publications on this. Search for multi-label classifications (e.g. the mldr package in R). Hope this helps.


text:
Q: How to return files with a specific file type only? This is my code:
import os

def read_file(path):
    name_file = os.listdir(path)
    return name_file

path = "/home/ich/Schreibtisch/fotki"
print(read_file(path))

This returns only all files in a folder in a list. But I want them to end with ".jpg". There are many files in the folder (.jpg, .txt, ...), but I want that only the .jpg files.

A: Do this with os.listdir and .endswith
import os

path = "/home/ich/Schreibtisch/fotki"

for file in os.listdir(path):
    if file.endswith(".jpg"):
        print(os.path.join(path, file))


text:
Q: opencv python image dithering i wrote a code for image dithering in python , it is working well for some images but for some it is generating unnecessary colors in the white regions .
#IMAGE DITHERING BASED ON Floyd-Steinberg METHOD
#author : bharath kotari
#date :18-1-2018

import cv2
import numpy as np

def set_pixel(im,x,y,new):
    im[x,y]=new

def quantize(im):
    for y in range(0,height-1):
        for x in range(1,width-1):
            old_pixel=im[x,y]
            if old_pixel<127:
                new_pixel=0
            else:
                new_pixel=255
            set_pixel(im,x,y,new_pixel)
            quant_err=old_pixel-new_pixel
            set_pixel(im,x+1,y,im[x+1,y]+quant_err*w1)
            set_pixel(im,x-1,y+1, im[x-1,y+1] +  quant_err*w2 )
            set_pixel(im,x,y+1, im[x,y+1] +  quant_err * w3 )
            set_pixel(im,x+1,y+1, im[x+1,y+1] +  quant_err * w4 )

    return im

img=cv2.imread("/home/user/Downloads/blender_images/truck.jpg")
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2=img.copy()
width,height,z=img.shape
w1=7/16.0
#print w1
w2=3/16.0
w3=5/16.0
w4=1/16.0
blue=img[:,:,0]
blue=quantize(blue)
green=img[:,:,1]
green=quantize(green)
red=img[:,:,2]
red=quantize(red)
gray1= quantize(gray)

image = cv2.merge((blue, green, red))
cv2.imshow('original',img2)
cv2.imshow('merged',image)
cv2.imshow('gray',gray1)
cv2.waitKey(0)

attaching image for reference ..
how to eliminate those big dots in the top right region ..
thankYou.

A: The spots happen because of integer overflow.
cv2.imread() represents image using unsigned 8 bit integer (see numpy.uint8), which have a max value of 255 and start over from zero if that value is passed. For example: 255 + 50 = 49. This happen in your code when adding in the errors.
There are several methods to avoid this. The simplest would be to make sure your values don't go over 255.


text:
Q: React native calendar show current week only Code:

 <CalendarPicker
                    minDate={minDate}
                    weekdays={['Su', 'M', 'T', 'W', 'Th', 'F', 'S']}
                    todayBackgroundColor="#979797"
                    selectedDayColor='#ff6c19'
                    selectedDayTextColor='#FFFFFF'
                     textStyle={{
                       fontFamily: 'HelveticaNeue',
                       color: 'rgb(96,96,96)'
                     }}
                  />
    </View>

import CalendarPicker from 'react-native-calendar-picker'
I have implemented CalendarPicker in my project.It is working fine.CalendarPicker shows all days from current month.How do i change CalendarPicker to show current week only?any help will be appricated.thanks in advance


text:
Q: amcharts export.js conflict with prototype.js? I am using amcharts to create charts. I am also using prototype.js to dynamically fetch dataProvider for the charts. But when I try to download the chart using the export capabilities of amCharts, I get following error:
Cannot read property '_calcWidth' of undefined
Now, when I remove the prototype.js script and then perform the download again, then it runs okay.
here is the download function:
 //charts[] contains all the amcharts.
 function downloadReport() {
    // iterate through all of the charts and prepare their images for export
    var images = [];
    var pending = charts.length;
    for (var i = 0; i < charts.length; i++) {
        var chart = charts[i];
        var content = [];
        chart.export.capture({}, function () {
            var dataArray = this.toArray({
                withHeader: true
            });
            var columns = dataArray[0].length;
            var columnWidths = (Array(columns).join("auto,") + "*").split(","); // ["auto", ... "*"]
            //
            // EXTRA LOGS TO CHECK THE NUMBER OF COLUMNS (ALL SHOULD BE THE SAME)
            console.log("header: ", columns);
            console.log("widths: ", columnWidths.length);
            for (var i2 = 0; i2 < dataArray.length; i2++) {
                console.log("columns: ", dataArray[i2].length);
            }

            // GENERATE IMAGE
            this.toJPG({}, function (data) {

                // ADD IMAGE
                content.push({
                    "image": data,
                    "fit": [523.28, 769.89] // A4 Dimensions less 20px because of the page margins
                });

                // ADD TABLE
                content.push({
                    layout: 'headerLineOnly',
                    margin: [0, 20, 0, 0], // [left, top, right, bottom]
                    table: {
                        headerRows: 1,
                        widths: columnWidths,
                        body: dataArray
                    }
                });

                pending--;
                if (pending === 0) {
                    // all done - construct PDF
                    chart.export.toPDF({
                        content: content
                    }, function (data) {
                        this.download(data, "application/pdf", "NPGroupReportDeck_LNIndiaTracker.pdf");
                    });

                    // ADD PAGE BREAK
                } else {
                    content[content.length - 1].pageBreak = "after";
                }
            });
        });
    }
}

A: I contacted the amchart support team, and they told me that in their next release, this problem will be fixed. All we have to do is just wait. :)


text:
Q: Why does GetThreadTimes return I'm attempting to measure the time spent in a thread for progress reporting purposes, but I'm getting very strange results from from the GetThreadTimes system call. Given the following program (compiled in VS 2013, targeting .NET 4.5):
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace ThreadTimingTest
{
    class Program
    {
        static Stopwatch _wallClockTimer;

        static System.Timers.Timer _timer = new System.Timers.Timer();

        private static Thread _thread;
        private static IntPtr _threadHandle;

        static void Main(string[] args)
        {
            _timer = new System.Timers.Timer();
            _timer.Elapsed += (s, e) =>
            {
                System.Runtime.InteropServices.ComTypes.FILETIME start, end, rawKernelTime, rawUserTime;

                GetThreadTimes(_threadHandle, out start, out end, out rawKernelTime, out rawUserTime);

                //ref: http://stackoverflow.com/a/6083846
                ulong uLow = (ulong)rawKernelTime.dwLowDateTime;
                ulong uHigh = (uint)rawKernelTime.dwHighDateTime;
                uHigh = uHigh << 32;
                long kernelTime = (long)(uHigh | uLow);

                uLow = (ulong)rawUserTime.dwLowDateTime;
                uHigh = (uint)rawUserTime.dwHighDateTime;
                uHigh = uHigh << 32;
                long userTime = (long)(uHigh | uLow);

                Debug.WriteLine("Kernel time: " + kernelTime);
                Debug.WriteLine("User time: " + userTime);
                Debug.WriteLine("Combined raw execution time: " + (kernelTime + userTime));

                long elapsedMilliseconds = (kernelTime + userTime) / 10000; //convert to milliseconds: raw timing unit is 100 nanoseconds
                Debug.WriteLine("Elapsed thread time: " + elapsedMilliseconds + " milliseconds");

                Debug.WriteLine("Wall Clock Time: " + _wallClockTimer.ElapsedMilliseconds + " milliseconds");

            };

            _timer.Interval = 1000;

            _wallClockTimer = new Stopwatch();

            Debug.WriteLine("Starting...");
            RunTest();

            Debug.WriteLine("Ended.");
        }

        public static void RunTest()
        {
            _thread =
                new Thread
                (
                    () =>
                    {
                        _threadHandle = GetCurrentThread();
                        Stopwatch sw = Stopwatch.StartNew();

                        while (sw.ElapsedMilliseconds < 3000)
                        {
                            int i = 1 + 2;
                        } //do busy-work for 3 seconds

                        sw.Stop();
                    }
                );

            _timer.Start();

            _thread.Start();a

            _wallClockTimer.Start();

            _thread.Join();
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool GetThreadTimes(IntPtr hThread,
            out System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpExitTime,
            out System.Runtime.InteropServices.ComTypes.FILETIME lpKernelTime, out System.Runtime.InteropServices.ComTypes.FILETIME lpUserTime);

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentThread();
    }
}

I get the following output:
Starting...
Kernel time: 0
User time: 0
Combined raw execution time: 0
Elapsed thread time: 0 milliseconds
Wall Clock Time: 1036 milliseconds
Kernel time: 0
User time: 0
Combined raw execution time: 0
Elapsed thread time: 0 milliseconds
Wall Clock Time: 2036 milliseconds
The thread '<No Name>' (0x191c) has exited with code 0 (0x0).
Ended.

I would expect GetThreadTimes to report something other than zero for the thread times: why is zero reported?

A: After making a couple simple mods to your code based on the link provided by Hans, valid times are displayed.
Adding a few interop declarations:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
    IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
    uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);

[Flags]
public enum DuplicateOptions : uint
{
    DUPLICATE_CLOSE_SOURCE = (0x00000001), // Closes the source handle. This occurs regardless of any error status returned.
    DUPLICATE_SAME_ACCESS = (0x00000002),  // Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.
}

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

then modifying how the handle is assigned:
//_threadHandle = GetCurrentThread();       <-- previous assignment
IntPtr processHandle = GetCurrentProcess();
bool result = DuplicateHandle(processHandle, GetCurrentThread(), processHandle, out _threadHandle, 0, false, (uint) DuplicateOptions.DUPLICATE_SAME_ACCESS);

produces the following result:
Starting...
Kernel time: 0
User time: 10000000
Combined raw execution time: 10000000
Elapsed thread time: 1000 milliseconds
Wall Clock Time: 1006 milliseconds
Kernel time: 0
User time: 20000000
Combined raw execution time: 20000000
Elapsed thread time: 2000 milliseconds
Wall Clock Time: 2004 milliseconds
Kernel time: 0
User time: 30000000
Combined raw execution time: 30000000
Ended.
Elapsed thread time: 3000 milliseconds
Wall Clock Time: 3045 milliseconds

EDIT:
Recently a great deal of effort has been given to handling too many threads that are created for a given system.  Let's say you have a quad processor, and 20+ threads all want to run.  Threads have a fairly large cost with respect to startup, kernel management, memory (they have their own stack), etc.  The system may actually be slower (juggling contexts and scheduling) than if the thread count were to be reduced.  So in .NET, libraries like TPL were created (allowing the developer to manage tasks, not threads).  This allows the CLR to balance the appropriate thread count to the target system.  But in your case (where you explicitly create a managed thread), there is nearly always a 1 to 1 relationship with native threads.
Hope this helps.


text:
Q: Переключатель на CSS3 Как сделать такой переключатель на CSS3?

A: Вот тут есть код.

body {
  color: #151B25;
  background-color: #2C4159;
}

.form {
  position: absolute;
  top: 50%;
  left: 50%;
  height: 100px;
  padding: 10px 0;
  width: 260px;
  transform: translate3d(-50%, -50%, 0);
}

.form:before {
  content: '';
  position: absolute;
  top: 0;
  left: -5px;
  height: 100%;
  width: 120px;
  background-color: #243548;
  border-radius: 50%;
  box-shadow: 75px 0 0 #243548, 150px 0 0 #243548;
}

.form:after {
  content: '';
  position: absolute;
  top: -94px;
  left: 70px;
  height: 100%;
  width: 120px;
  background-color: #2C4159;
  border-radius: 50%;
  box-shadow: 0 188px 0 #2C4159;
}

.form input {
  position: absolute;
  left: -9999px;
}

.bubble {
  position: absolute;
  z-index: 2;
  top: 50%;
  left: 50%;
  height: 100px;
  width: 100px;
  transform: translate3d(-75%, -50%, 0);
  margin-left: -50px;
  background: #BBBBBB;
  border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
  border-right: 0px solid #BBBBBB;
  border-left: 0px solid #BBBBBB;
  animation: toggle-reverse 2s 1;
}

#bubble:checked+.bubble {
  animation: toggle 2s 1;
  transform: translate3d(75%, -50%, 0);
  background: #3CCC97;
}

.bubble:after {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -15px;
  margin-left: -2px;
  height: 30px;
  width: 4px;
  background: #fff;
  left: 50%;
  transform: rotate(45deg);
  border-radius: 2px;
  transition: 500ms ease all 1.25s;
}

.bubble:before {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -15px;
  margin-left: -2px;
  height: 30px;
  width: 4px;
  background: #fff;
  left: 50%;
  transform: rotate(-45deg);
  border-radius: 2px;
  transition: 500ms ease all 1.25s;
}

#bubble:checked+.bubble:after {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -15px;
  margin-left: 5px;
  height: 30px;
  width: 4px;
  background: #fff;
  left: 50%;
  transform: rotate(225deg);
  border-radius: 2px;
}

#bubble:checked+.bubble:before {
  content: '';
  position: absolute;
  top: 50%;
  margin-top: -7px;
  margin-left: -10px;
  height: 20px;
  width: 4px;
  background: #fff;
  left: 50%;
  transform: rotate(-215deg);
  border-radius: 2px;
}

@keyframes toggle {
  0% {
    transform: translate3d(-75%, -50%, 0);
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    background: #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 100px;
  }
  20% {
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform: translate3d(-75%, -50%, 0);
    height: 100px;
  }
  40% {
    border-left: 0 solid #BBBBBB;
    border-radius: 35% 65% 65% 35% / 50% 50% 50% 50%;
    height: 90px;
  }
  50% {
    transform: translate3d(0%, -50%, 0);
    border-right: 25px solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    background: #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 90px;
  }
  75% {
    border-left: 25px solid #3CCC97;
    border-color: #3CCC97;
    background: #3CCC97;
    border-radius: 65% 35% 35% 65% / 50% 50% 50% 50%;
    height: 90px;
  }
  100% {
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform: translate3d(75%, -50%, 0);
    height: 100px;
    width: 100px
  }
}

@keyframes toggle-reverse {
  0% {
    transform: translate3d(75%, -50%, 0);
    background: #3CCC97;
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 100px;
  }
  20% {
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform: translate3d(75%, -50%, 0);
    height: 100px;
  }
  40% {
    border-right: 0 solid #3CCC97;
    border-radius: 65% 35% 35% 65% / 50% 50% 50% 50%;
    height: 90px;
  }
  50% {
    transform: translate3d(0%, -50%, 0);
    border-left: 25px solid #3CCC97;
    border-right: 0 solid #3CCC97;
    background: #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 90px;
  }
  75% {
    border-right: 25px solid #BBBBBB;
    border-color: #BBBBBB;
    background: #BBBBBB;
    border-radius: 35% 65% 65% 35% / 50% 50% 50% 50%;
    height: 90px;
  }
  100% {
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform: translate3d(-75%, -50%, 0);
    height: 100px;
    width: 100px
  }
}

  <input type="checkbox" id="bubble" />

Анимация тоже есть, осталось прикрепить JS.

A: body{
    color: #151B25;
    background-color: #2C4159;
}
.form {
    position: absolute;      top: 50%;      left: 50%;      height: 100px;
    padding: 10px 0;
    width: 260px;
    transform: translate3d(-50%,-50%,0);
}
.form:before {
    content: '';
    position: absolute;
    top: 0;
    left: -5px;
    height: 100%;
    width: 120px;
    background-color: #243548;
    border-radius: 50%;
    box-shadow: 75px 0 0 #243548, 150px 0 0 #243548;
}
.form:after {
    content: '';
    position: absolute;
    top: -94px;
    left: 70px;
    height: 100%;
    width: 120px;
    background-color: #2C4159;
    border-radius: 50%;
    box-shadow: 0 188px 0 #2C4159;
}

.form input {
    position: absolute;
    left: -9999px;
}
.bubble{
  position:absolute;
  z-index:2;
  top:50%;
  left:50%;
  height:100px;
  width:100px;
  transform:translate3d(-75%,-50%,0);
  margin-left:-50px;
  background:#BBBBBB;
  border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
  border-right: 0px solid #BBBBBB;
  border-left: 0px solid #BBBBBB;
  animation: toggle-reverse 2s 1;
}
#bubble:checked + .bubble{
  animation: toggle 2s 1;
  transform:translate3d(75%,-50%,0);
 background: #3CCC97;
}
.bubble:after {
    content: '';
    position: absolute;
    top: 50%;
    margin-top: -15px;
    margin-left: -2px;
    height: 30px;
    width: 4px;
    background: #fff;
    left: 50%;
    transform: rotate(45deg);
    border-radius: 2px;
    transition: 500ms ease all 1.25s;
}
.bubble:before {
    content: '';
    position: absolute;
    top: 50%;
    margin-top: -15px;
    margin-left: -2px;
    height: 30px;
    width: 4px;
    background: #fff;
    left: 50%;
    transform: rotate(-45deg);
    border-radius: 2px;
    transition: 500ms ease all 1.25s;
}

#bubble:checked + .bubble:after {
    content: '';
    position: absolute;
    top: 50%;
    margin-top: -15px;
    margin-left: 5px;
    height: 30px;
    width: 4px;
    background: #fff;
    left: 50%;
    transform: rotate(225deg);
    border-radius: 2px;
}
#bubble:checked + .bubble:before {
    content: '';
    position: absolute;
    top: 50%;
    margin-top: -7px;
    margin-left: -10px;
    height: 20px;
    width: 4px;
    background: #fff;
    left: 50%;
    transform: rotate(-215deg);
    border-radius: 2px;
}
@keyframes toggle {
    0%   {
    transform:translate3d(-75%,-50%,0);
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    background:#BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 100px;
    }
    20% {
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform:translate3d(-75%,-50%,0);
    height: 100px;
    }
    40%  {
    border-left: 0 solid #BBBBBB;
    border-radius: 35% 65% 65% 35% / 50% 50% 50% 50%;
    height: 90px;
    }
    50%  {
    transform:translate3d(0%,-50%,0);
    border-right: 25px solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    background:#BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 90px;
    }
    75%  {
    border-left: 25px solid #3CCC97;
    border-color:#3CCC97;
    background: #3CCC97;
    border-radius: 65% 35% 35% 65% / 50% 50% 50% 50%;
    height: 90px;
    }
    100% {
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform:translate3d(75%,-50%,0);
    height: 100px;
    width:100px
    }
}

@keyframes toggle-reverse {
    0%   {
    transform:translate3d(75%,-50%,0);
    background: #3CCC97;
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 100px;
    }
    20% {
    border-right: 0 solid #3CCC97;
    border-left: 0 solid #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform:translate3d(75%,-50%,0);
    height: 100px;
    }
    40%  {
    border-right: 0 solid #3CCC97;
    border-radius: 65% 35% 35% 65% / 50% 50% 50% 50%;
    height: 90px;
    }
    50%  {
    transform:translate3d(0%,-50%,0);
    border-left: 25px solid #3CCC97;
    border-right: 0 solid #3CCC97;
    background: #3CCC97;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    height: 90px;
    }
    75%  {
    border-right: 25px solid #BBBBBB;
    border-color:#BBBBBB;
    background:#BBBBBB;
    border-radius: 35% 65% 65% 35% / 50% 50% 50% 50%;
    height: 90px;
    }
    100% {
    border-right: 0 solid #BBBBBB;
    border-left: 0 solid #BBBBBB;
    border-radius: 50% 50% 50% 50% / 50% 50% 50% 50%;
    transform:translate3d(-75%,-50%,0);
    height: 100px;
    width:100px
    }
}

<input type="checkbox" id="bubble" />


text:
Q: How to customize a PHP url token with a defined variable in a python script? I am getting a TypeError: cannot concatenate 'str' and 'int' objects when i want to customise the url token where "id" is needed.
In place of one single result returned by a single id (say 303) i want to have the result for all the ids declared in the variable "station" retrieved from another url.
the code is as follows:

import urllib2
import json

#assign the url
url="http://ewodr.wodr.poznan.pl/doradztwo/swd/swd_api.php?dane={%22token%22:%22pcss%22,%22operacja%22:%22stacje%22}"

# open the url
json_obj= urllib2.urlopen(str(url))
output= json.load(json_obj)
station_res= output ['data'] ['features']
for item in station_res:
 station= item['id']
url1="http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}" +str(station)
 json_obj2= urllib2.urlopen(str(url1))
 output2= json.load(json_obj2)
 for item2 in output2 ['data']:
  print item2

I tried to put "stations" as a string in the "url1" but it still doesn't recognise the url and returns an error:
Traceback (most recent call last):
    `File "stations.py", line 23, in <module>`
        `for item2 in output2 ['data']:`

KeyError: 'data'

A: Try with:
station= item ['id']
url1="http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}" +str(station)

You are trying to join an String with an Integer, what generate this error.

A:

url1 = 'http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:' + str(station) + '}'

This solved my problem.


text:
Q: Individual level random effect for over dispersion In glms we can use a quassipoison fudge factor to account for over dispersion in our poisson models.
In glmms we can add an individual level random effect (e.g. id) for each row in data.frame to account for over dispersion. i.e.
glmer(y ~ x + (1|group) + (1|id), family = poisson)

Can someone give me a feel for how this individual level random effect deals with over dispersion?

A: If your concern is for whether this method is adequate, a recent simulation paper on PeerJ "Using observation-level random effects to model overdispersion in count data in ecology and evolution" indicates that individual-level random effects works well but do have limitations.  In the abstract the author states:
"This work suggests use of observation-level random effects provides a simple and robust means to account for overdispersion in count data, but also that their ability to minimise bias is not uniform across all types of overdispersion and must be applied judiciously."
I believe Bolker does some comparisons of different ways to deal with overdispersion here and works through the classic Grouse Tick data of Elston et al.


text:
Q: Visualforce Remote Objects Related List Query Does anyone know how to or if it is possible to pull data from the related list of an object using Remote Objects? I can query the object's related list without error however it is undefined and I cannot seem to find references on this in the documentation.

A: Bit late to the party, but as far as I can tell (and from experimenting) you can only query fields on the object itself. This means to get related information you then have to make subsequent calls to those objects filtering by the lookup Id.
This is a snippet of code I've been using (note I'm using UnderscoreJS to help out a little).
// Client id is my JS name for the ContactId field
var clientIds = _.uniq(events.map(function(e) { return e._Client; }));
clientIds = _.reject(clientIds, function(c) { return !c; });

if(clientIds.length === 0)
{
    success(events);
    return;
}

// this method perforces a remote object query on contact
self.loadClientsById(clientIds, function(clients)
{
    var mapped = events.map(function(e)
    {
        for(var i = 0; i < clients.length; i++)
            if(clients[i].Id === e._Client)
            {
                e._Client = clients[i];
                break;
            }

        return e;
    });

    // now mapped is an array of events, where each has a contact object
    // contained within it under the _Client property;
    doSomeCallback(mapped);
});


text:
Q: Define the function $g: \mathbb{N} \times \mathbb{N} \rightarrow \mathbb{N}$ by the rule $g((m,n)) = (2^n)(3^m)$. Prove one to one For this one you can also provide a counter example but I could not come up with one. So I started to set up a proof to it but I realized after a bit of algebraic steps I found out that I have 4 variables in my equation that I need to prove are always equal. For example,
$n_1 = n_2$
and
$m_1 = m_2$
But of course I can't do that in one equation so I am kind of lost on how to prove one-to-one on this one. OR if there is a counter-example that I have overlooked.
Edit: Yes one-to-one is injective

A: So, a one-to-one function is basically a function which doesn't map distinct elements in the domain ($\mathbb{N}$ $\times$ $\mathbb{N}$ in our case) to the same element in the range ($\mathbb{N}$ in our case). Mathematically, this translates to
$g(m_{1}$,$n_{1})$ = $g(m_{2}$,$n_{2})$ $\Rightarrow$ ($m_{1}$,$n_{1}$) = ($m_{2}$,$n_{2}$ ).
So, assuming the above, we get the equation ($2^{n_{1}}$)($3^{m_{1}}$) = ($2^{n_{2}}$)($3^{m_{2}}$)  $\Rightarrow$ ($2^{n_{1}- n_{2} }$) = ($3^{m_{2}- m_{1} }$) (and you can divide by the powers of 2,3 since they are never going to be 0) and then its straightforward to show that the only case when the above equation is satisfied is when $n_{1}$ = $n_{2}$ and $m_{1}$ = $m_{2}$.
Hence, proving your claim.


text:
Q: Convert from nvarchar to decimal and filter by range I would like to perform a query on these string values:
Record ID / Value
1 / 10.5
2 / 12
3 / 8
4 / 19.25
5 / 16.4
6 / 14

The value column is a nvarchar column. I would like to filter the results between two string values inserted by users (for example 10 and 15). I tried to use:
SELECT Value
FROM Table
WHERE CONVERT(decimal(10, 2), Value)
    BETWEEN CONVERT(decimal(10, 4), '10')
    AND CONVERT(decimal(10, 4), '15')

But I have the following error:
Error converting data type nvarchar to numeric.

What is wrong with the data types?

A: You could use TRY_CONVERT (SQL Server 2012 and newer):
SELECT Value
FROM Table
WHERE TRY_CONVERT(decimal(10, 2),Value) BETWEEN TRY_CONVERT(decimal(10, 4), '10')
                                            AND TRY_CONVERT(decimal(10, 4), '15')

Better approach is to add computed column:
CREATE TABLE tab(
   value VARCHAR(100),
   value_as_decimal AS (TRY_CONVERT(decimal(10, 2),Value)) PERSISTED
);

CREATE INDEX tab_ix ON tab(value_as_decimal) INCLUDE(Value);

SELECT Value
FROM Table
WHERE value_as_decimal BETWEEN TRY_CONVERT(decimal(10, 4), '10')
                           AND TRY_CONVERT(decimal(10, 4), '15');

DBFiddle Demo
Ideal solution is to store value as DECIMAL(10,4) and forget about casting.


text:
Q: Triggering function when clicking generated objects javascript I have this code to generate random objects in a specific canvas
i want  to make those objects clickable so if i click on one of the objects i trigger a function im not really good with javascript so i need some help
here is the code
function spawnRandomObject() {

    var t ;

    if (Math.random() < 0.50) {
        t = "red";
    } else {
        t = "yellow";
    }

    var object = {
        type: t,
        x: Math.random() * (canvas.width - 30) + 15,
        y: spawnLineY,
    }

    objects.push(object);
}```

A: To add an event listener you should have a HTML element like so:

Click this Object

Then in your script file you assign that element to a variable and attach an event listener to it.
let object = document.getElementById('clickable-object');

object.addEventListener('click', function() {
    console.log('This object has been clicked');
}

In order for your javascript to be able to interact with the html you need to include your js file in the html file.


text:
Q: Oracle Sql Developer - Query Results won't export when using LISTAGG function I'm currently working on a project and I'm using my company's Oracle SQL Developer. It's version 1.5.5 if that means anything.
Long story should, I'm trying to export my SQL Results to a CSV, but when I click csv, the export wizard doesn't show up.
When I remove the ListAgg, then it suddenly pops up and everything works as usual.
Is this a version issue or something? Are there any work arounds? The TLDR query is below:
LISTAGG( (a.subj || ' ' || a.crse_num || ' ' || a.section), ', ')
 WITHIN GROUP ( ORDER BY a.subj ) ) AS IP_Courses

Everything works normal when I remove the ListAgg ( as well as the concatenation) but when I introduce ListAgg, nothing wants to export. :(


text:
Q: Frequency List (ArrayList or LinkedList) with items over 700,000 I have a list which contains elements of Person data type. What would be the best way and less consumption of time, to find the frequency of each element in the list.
The following things I have tried, results in time beyond 10min on i7, 8GB
    ArrayList<String> frequent = new ArrayList<>();

    for (Person E: myList2)
    {
        int frequency = 0;
        //int frequency = Collections.frequency(myList2, E);

        for (Person e : myList2)
        {
            if (E.getPassName().equals(e.getPassName()))
                frequency++;
        }
        if (frequency >= times)
            frequent.add(E.getPassName());
    }

Also, the Collections always results to the VALUE 1, even if there are duplicates in the LinkedList.

A: Use a Map<Person, Integer> to store the frequency:
Map<Person, Integer> frequency = new HashMap<Person, Integer>();

for (Person person: myList2) {
    if (frequency.containsKey(person)) {
        frequency.put(person, frequency.get(person) + 1);
    } else {
        frequency.put(person, 1);
    }
}

or a Map<Person, AtomicInteger> (Since that's a mutable type, it just makes the task of incrementing frequency easier):
for (Person person: myList2) {
   frequency.putIfAbsent(person, new AtomicInteger(0));
   frequency.get(person).incrementAndGet();
}

A: You algorithm is O(n^2). This is bad. Using Collections.frequency won't fix that, it just loops over the passed in Collection checking for equals. Don't use that either.
Use a Map, in Java 8:
final Map<Person, Integer> count = myList2.stream()
        .collect(HashMap::new, (map, i) -> {
    map.merge(i, 1, Integer::sum);
}, HashMap::putAll);

Java 7:
final Map<Person, Integer> count = new HashMap<>();
for (final Person person : myList2) {
    final Integer c = count.get(person);
    if (c != null) {
        count.put(person, c + 1);
    } else {
        count.put(person, 1);
    }
}

The advantage of Java 8 method is that with one change (stream() -> parallelStream()) the loop will become multi-threaded.
NB This relies on correctly implemented equals() and hashCode() methods in the Person class. Assuming passName is an instance variable of Person, something like:
@Override
public int hashCode() {
    int hash = 3;
    hash = 89 * hash + Objects.hashCode(this.passName);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Person other = (Person) obj;
    if (!Objects.equals(this.passName, other.passName)) {
        return false;
    }
    return true;
}


text:
Q: Number of sorted elements (permutations), in all possible permutations of a list Given an array, say, arr = [5, 5, 4, 4, 2, 1], how can I find, of all possible permutations of this array, the number of permutations which are same like the original array itself (assuming the original array is always sorted in descending order). In this sample case, there will be 4 permutations equal to the original array. Well that's what I get using itertools.permutations in python. Anyone with something faster? I will be most grateful. Following is my so slow python code.
from itertools import permutations

arr = sorted(map(int, (raw_input().split())), reverse = True)

perms = permutations(n,len(arr))

cnt = 0;

for i in perms:
    if list(i) == arr: print i; cnt += 1
print cnt

A: Say your array is size n and the repetitions are r1, r2, ..., rk, so that sum(ri) = n. Then the answer is the product of the factorials of the repetitions.
e.g., for arr = [5, 5, 4, 4, 2, 1], we get r = [2, 2, 1, 1], and an answer of 2! * 2! * 1! * 1! = 4

A: You can get the product of the factorials of the lengths of all same-value subsequences:
from itertools import groupby
from functools import reduce
from math import factorial
from operator import mul
print(reduce(mul, map(lambda t: factorial(sum(1 for i in t[1])), groupby(arr))))

This outputs: 4

A: For N elements, the number of possible permutation is N!
If you have in example [5, 5, 5, 4, 1], there is 3! permutations where the array is the same.
I'd loop the array and store in a associated array the value and the number of that value was met.
Pseudo-code :
firstArray = [5, 5, 4, 4, 2, 1]
doubleArray = []

for each item in firstArray:
    if item is in doubleArray keys:
        doubleArray[item]++
    else:
        doubleArray[item] = 1

result = 1
for each elem in doubleArray:
    result *= fact(elem)

print "There is " + elem + " permutations possible where the original array remains the same"


text:
Q: Objective-C - Show avatar picture from XMPPvCardAvatarModule in XEP 153? I'm developing an iphone app with XMPP.
I'm trying to print the images of the logged in users in the chat room. This is the code I have.
XMPPvCardAvatarModule *avatar = [[XMPPvCardAvatarModule alloc]initWithvCardTempModule:[[self appDelegate]xmppvCardTempModule]];
XMPPJID *jidUser = [XMPPJID jidWithString:key];
NSData *foto = [[NSData alloc]initWithData:[avatar photoDataForJID:jidUser]];UIImage *pic = [UIImage imageWithData:fotoData];
UIImageView *picVista = [[UIImageView alloc] initWithImage:pic];

[self.commentsGente addSubview:picVista];

But that NSData is always 0KB, so there's obviously no image. How to do this?

A: NSData *photoData = [[[self appDelegate] xmppvCardAvatarModule]photoDataForJID:user.jid];

UIImageView *picVista;
picVista.image = [UIImage imageWithData:photoData];

try this it works fine for me


text:
Q: Error to put pdf files with MS Graph API SharePoint I use the MS Graph API to upload local files in a SharePoint.
It works well with Word or Text files. I can upload them in the SharePoint
I can also upload Pdf files but i cannot open the Pdf correctly in SharePoint: "No preview is available for this file".
Of course, it opens normally if i upload manually the Pdf in the SharePoint.
Based on what i read on internet, it looks to be an encoding issue but i cannot make it work.
How to upload pdf file to Sharepoint site using MicrosoftGraph
I use this request:
PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content
Ex: Invoke-WebRequest -Method PUT -Uri "https: XXX sharepoint-online/v1/sites/siteid/drive/items/parentid:/PDFfile:/content" -Headers @{'APIKEY'='XXX';'Content-Type'='multipart/form-data';'Accept'='application/json';'Authorization'="Bearer accesstoken"}  -InFile $pathtopdffile
Any help/advise please ?


text:
Q: Debugging a potential integer overflow when using a batch submission system? so here is my problem. I understand it is not a very well-asked question but that's part of the reason why I'm asking: how to even go about looking for help here?
So I run some piece of code written in Python. The main process spawns a few other processes using the multiprocessing module. Once these processes finish, they send their results over a pipe to the main process. What they send is basically some numpy arrays and floats.
There is also an input data set that varies in size and that is split into chunks and given to each of the worker processes. For small to moderate sizes everything works fine. When the number of data points is on the order of 1,000,000 however, something breaks down.
Before I paste the error message let me also add, that I run it all on a system that's using a PBS scheduler. That's why I find it hard to debug it: I cannot just use pdb and also it takes several hours before the error is produced.
Anyway, here is the error message, could you give me any hints how to go about fixing it? What can be wrong? Or what more information should I include in this question?
Process Process-4:
Traceback (most recent call last):
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/process.py", line 249, in _bootstrap
    self.run()
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/glade/u/home/mjurek/.local/lib/python3.6/site-packages/pyMRA/MRANode.py", line 102, in __init__
    pipe.send(self)
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/connection.py", line 393, in _send_bytes
    header = struct.pack("!i", n)
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
Process Process-3:
Traceback (most recent call last):
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/process.py", line 249, in _bootstrap
    self.run()
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/glade/u/home/mjurek/.local/lib/python3.6/site-packages/pyMRA/MRANode.py", line 102, in __init__
    pipe.send(self)
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "/glade/u/apps/ch/opt/python/3.6.2/gnu/6.3.0/lib/python3.6/multiprocessing/connection.py", line 393, in _send_bytes
    header = struct.pack("!i", n)
struct.error: 'i' format requires -2147483648 <= number <= 2147483647

A: This is a limitation in multiprocessing -- the data you're trying to send is evidently larger than 2 GB, so the length of the resulting pickled string doesn't fit in a 32-bit integer (which is the exception you're getting). You should use shared memory to transfer it instead of passing it as an argument (which pickles it).
See issue #17560 on the bug tracker.


text:
Q: How to modify XSD element from string to xml? I have the following part in my XSD:
 <xs:element name="Parameter">
   <xs:complexType mixed="true">
     <xs:attribute name="Name" use="required" type="xs:string"/>
   </xs:complexType>
 </xs:element>

which means that value for a Parameter can be any string. Can I somehow specify that value for Parameter can be  any valid xml like <aaa></aaa> ? Something like type="xs:xml"

A: Use <xs:any> to allow any XML elements in your content model.
<xs:element name="Parameter">
  <xs:complexType>
    <xs:sequence>
      <xs:any minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

You can restrict elements allowed by <xs:any> to certain namespaces with namespace attribute and control their validation with processContents attribute. To allow any attribute, use <xs:anyAttribute>
More info in the XML Schema recommendation: 3.10.2 XML Representation of Wildcard Schema Components

A: You will have to use
<xs:element name="Parameter" type="myType>

where
<complexType name="myType>
<choice>
<element "myXml" type="xml">
<element "myStr" type="xs:sting">
</choice>
</complexType>

and you will have to define xml like a pattern of xml you want to be your value.


text:
Q: How do I stop the screen from being locked on resume on Kubuntu/KDE? Per How do I stop the screen from being locked on suspend? I want to be able to sleep and resume without the screen locking.
All the previous answers seem to involve fairly Gnome-specific things that won't apply to me but please correct me if I'm incorrect in that assumption!

A: To make it so that it does not lock on resume do the following: Power management → Advanced settings  and uncheck "Lock screen on resume"
Note for 15.04: This has moved to Desktop Behaviour → Screen Locking.


text:
Q: A work around for having a role that can report to at least 2 other roles? I want to create a role child that reports to Parent1 and Parent2. If I create child under Parent1 I cannot create child under Parent2. It says: Error: This Role Name already exists or has been previously used. Please choose a different name.
Is there a way (a work around, as we cannot have multiple parent roles for a single child role) to create a child role that answers to multiple parent roles?

A: A role can only report to one other role. If you need additional flexibility, you might want to use Territory Management or, if you just need visibility, you can simply create a Sharing Rule. The latter allows you to share records owned by one role with users in another role, and is far easier to set up for simple use cases. TM should only be considered if you need the advanced power, as once enabled, you can't disable it later.


text:
Q: SQLite Count where query I use a simple sql lite query to fetch the count value from a table.
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME, null);
if (cursor.moveToFirst()) {
   return cursor.getInt(0);
}
return cursor.getInt(0);

This works good
But when I add a where clause to the select query
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME + "WHERE name in (" + k + ")", null);
if(cursor.moveToFirst()) {
   return cursor.getInt(0);
}
return cursor.getInt(0);

process stops unexpectedly.......

A: You're missing a space in front of the WHERE: ... + TABLE_NAME + "WHERE name ...
But there's a lot wrong with your code:

*

*Why do you use rawQuery() when there's nice methods like query(table, columns, selection, selectionArgs, groupBy, having, orderBy) that spare you from building query strings at risk of SQL injection? Even rawQuery() takes query arguments as second parameter.

*Where do you close your Cursor? You'll leak memory this way.

*What happens if cursor.moveToFirst() returns false and you execute the line after your if-block? This will crash.

A: Check the value of that k variable, it might be not valid for sql IN operator.


text:
Q: How to execute a single TypeScript that uses `import type` file in ts-node I would like to execute a single TypeScript file using ts-node as a "module" to take advantage of the import type syntax.
When using the .ts extension, I get the warning Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. and then an error SyntaxError: Unexpected token 'export'.
When using the .mts extension, I get the error SyntaxError: Cannot use import statement outside a module.
What would I need to do to execute a single TypeScript file in ts-node and use import type without changing the type in package.json?

A: In my case, I'm using vite with react
In my tsconfig.json file, add in this section
{
...
"ts-node": {
    "compilerOptions": {
      "module": "commonjs"
    }
  },
}

then simply run npx ts-node path/to/your/script


text:
Q: Remove extra HTML spaces in Smarty We heavily use Smarty for all our front end templating. I have observed the following situation:
When my Smarty template is similar to as follows:

    {if $a == 'A'}
        {$var1}
    {else}
        {$var2}
    {/if}

SUBTEXT

The final HTML which is delivered to the browser is:

                            65

SUBTEXT

I would expect it to be more clean and something like:

    65
SUBTEXT

or better:

65
SUBTEXT

Anyway I can do this with some configuration settings in Smarty 3? Any setting to format and clean the final HTML created?
Thanks

A: You can use {strip} to remove all white space and carriage returns in part of a template:
http://www.smarty.net/docsv2/en/language.function.strip.tpl
{strip}

    {if $a == 'A'}
        {$var1}
    {else}
        {$var2}
    {/if}

SUBTEXT

{/strip}

Output should be:

65
SUBTEXT

This may be inconvenient, but be aware that white space and newlines have a significant impact/importance on the HTML output, and stripping them globally can have unintended side effects.

A: You can load the output filter trimwhitespace. It removes HTML comments (except ConditionalComments) and reduces multiple whitespace to a single space everywhere but


text:
Q: spark: How to get data by foreachRDD which is a DSStream created by ReceiverLauncher.launch? // consumer data from kafka

val tmp_stream = ReceiverLauncher.launch(ssc, props, numberOfReceivers,StorageLevel.MEMORY_ONLY)

tmp_stream.foreachRDD(rdd => {
  rdd.collect()
  val count = rdd.count()  // here I can get the count of datas
     // How can I get data here ?
})

Any idea how to complete this code to get data by foreachRDD from stream created by ReceiverLauncher.launch

A: You can call the getPayLoad to get the raw byte[]. Something like this
val stream = tmp_stream.map(x => { val s = new String(x.getPayload); s })


text:
Q: Calculate area based on based on shape bounded by longitude and latitude I am new to geotools and jts. I have requirement to calculate the area of any shape bounded by longitude and latitude.
How can I start with it?


text:
Q: How to show different function usages when using varargin (...)? When you type in a Matlab function name and open a brace (e.g. sum() in the command window, a tooltip opens that shows all possible usages of this function.
When I write my own function that accepts varargin, the tooltip shows just one option, which instead of varargin puts ... (e.g. myfunc(x,...)).
How can I suggest more specific usages of my function to the user?

A: I can get you there without editing 'Syntax' that works on current releases, though a little muddy.
The below function takes a range of required, optional, and optional name-value pairs for inputs.  I want tool tip to give the user information on the required and optional inputs.  varargin always exists even if no variables are passed into it, and inputParser works pretty well when handed varargin.  I'm going to take advantage of this by leaving my optional inputs on the function call, but then stack them into varagin before I ever work with them.
tool tip will display myFun( frequency, gain_optional, phase_optional, ...)
function myFun( frequency, gain_optional, phase_optional, varargin )

%% Get mandatory and optional Inputs using inputParser
p = inputParser;

% mandatory inputs
argName = 'frequency';
validation = @(x) validateattributes( x, {'numeric'}, {'2d','positive'} );
p.addRequired( argName, validation );

% optional inputs

% start by packaging all optional inputs into varargin.  The two optional
% inputs were kept out of varargin so they will display in the tooltip
if nargin > 2
    varargin = [{phase_optional} , varargin];
end
if nargin > 1
    varargin = [{gain_optional} , varargin];
end

% add optional inputs into inputParser
argName = 'gainLinear';
default = [];
validation = @(x) validateattributes( x, {'numeric'}, {'2d','positive'} );
p.addOptional( argName, default, validation );

argName = 'phaseDeg';
default = [];
validation = @(x) validateattributes( x, {'numeric'}, {'2d','positive'} );
p.addOptional( argName, default, validation );

% name-value pairs
argName = 'model';
default = [];
validation = @(x) validateattributes( x, {'numeric'}, {'vector','positive'} );
p.addParameter( argName, default, validation );

argName = 'order';
default = [];
validation = @(x) validateattributes( x, {'numeric'}, {'scalar','integer','>',0,'<',3} );
p.addParameter( argName, default, validation );

% pull out all passed data with the inputParser and stash into input struct
p.parse(frequency, varargin{:});
input = p.Results

A: One method, if you know the maximum number of variable inputs and all of their names, is to do something like:
function out = my_func(var1, var2, var3)

    if nargin < 1
        var1 = default_var1_value;
    end
    if nargin < 2
        var2 = default_var2_value;
    end
    if nargin < 3
        var3 = default_var3_value;
    end

end

When you do this, Matlab lets you call my_func with 0,1,2 or 3 arguments. But the tooltip will only have one entry:
my_func(var1, var2, var3)

This, to me, at least seems better than .... I have no idea how/if it's possible to make it display more than one tooltip.
Edit: It seems that built-in functions get some kind of extra privilege somewhere. For example, the function rank comes with Matlab and displays two tooltips. If you edit rank, copy the code into a new file my_func.m, and rename the function my_func, it only gets one tooltip. So it's not just some special formatting of the commented lines at the top.


text:
Q: How to populate data frame from thousands of ncdf files using a for-loop? I'm trying to open thousands of netcdf files and pull the data into a dataframe that I can save as a csv file.
So after putting all the ncdf files names in a csv file as a list, I ended up using this code to create a dataframe populated with the data from the ncdf files.
vec0 <- vector()
time <- c(vec0,1:28413)

vec1 <- vector()
temp <- c(vec1,1:28413)

vec2 <- vector()
sphum <- c(vec2,1:28413)

vec3 <- vector()
rain <- c(vec3,1:28413)

vec4 <- vector()
totprcp <- c(vec4,1:28413)

for (i in 1:length(filenames))
  {ncdata=nc_open(filenames[i])

 nctime=ncvar_get(ncdata,"time")
  time[i] = nctime[1]

nctemp=ncvar_get(ncdata,"Tair_f_inst")
  temp[i] = nctemp[1]

 nchum=ncvar_get(ncdata,"Qair_f_inst")
  sphum[i] = nchum[1]

  ncrain=ncvar_get(ncdata,"Rainf_tavg")
  rain[i] = ncrain[1]

  ncprcp=ncvar_get(ncdata,"Rainf_f_tavg")
  totprcp[i] = ncprcp[1]
  nc_close(filenames[i])}

  cbind(time,temp,sphum,rain,totprcp)

But I'm only getting accurate data for the first row and its filling in a sequence of numbers (1 through 28412) for the rest of the rows. I think my mistake lies in the way I wrote the nc_close component of the code. Any ideas?

A: nc_close() should be applied to the nc object itself, not to the filename. I.e. to "An object of class ncdf4 (as returned by either function nc_open or function nc_create."
So, you should use
nc_close(ncdata)