text:
Q: Get printing page count Some process starts a print job and then tells me about it.
At this point, using C++, I need to find out how many pages the current print job consists of so I can display a "Printing page X of Y" message.
i.e. I'm trying to find out Y.
I'd be grateful if someone could point me in the right direction. I've got as far as doing some things with the printer, but just can't see where I can get this info from.
Thanks for any help.

A: As you can see in this example here:
https://support.microsoft.com/en-us/kb/158828
You ned to enumerate jobs in Print Queue, then you will get JOB_INFO_1 structure for each job.
When you do pJobInfo->TotalPages you will have TotalPages of each job in print queue.
So in example above, find this:
printf( "[%d] [%s]\n", pJobInfo[i].JobId, pJobInfo[i].pDocument );

and add this:
printf( "Total Pages: [%d]\n", pJobInfo[i].TotalPages );

and you will have total pages count.


text:
Q: C++ process class error Following the tutorial here, I decided to make a process class for C++ so that I did not have to constantly keep writing out the same code for starting a process. It does work starting the process, but when I pass a command line function, it does nothing. Example ("c:\\windows\\notepad.exe", "c:\\windows\\PFRO.txt"). What is the problem?
Note: format is just a basic formatting function, using vsprintf
class process
{
public:
    static BOOL __stdcall start(LPCSTR _Proc_name, LPSTR _Command_line = NULL, LPSECURITY_ATTRIBUTES _Proc_attrib = NULL,
        LPSECURITY_ATTRIBUTES _Thread_attrib = NULL, BOOL _Inherits_handles = FALSE, DWORD _Creation_flags = NULL,
        LPVOID _Environment = NULL, LPCSTR _Cur_directory = NULL)
    {
        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        ZeroMemory(&pi, sizeof(pi));
        if (!CreateProcess(_Proc_name, _Command_line, _Proc_attrib, _Thread_attrib,
            _Inherits_handles, _Creation_flags, _Environment, _Cur_directory, &si, &pi))
        {
            fputs(format("process::start(...) failed [%d]\n", GetLastError()), stderr);
            return false;
        }
        WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return true;
    }
};

int main()
{
    process::start("c:\\windows\\notepad.exe", "c:\\windows\\PFRO.txt");
    getchar();
}

A: When the command line parameter is parsed to provide arguments for a main function, the first token is taken to be the executable file. A called program might well try to open the second token as its file argument, and of course you there wasn't one.
The usual practice is to repeat the program name as the first token in the command line. For example
process::start("c:\\windows\\notepad.exe", "notepad c:\\windows\\PFRO.txt");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not to delete child record on deleting parent table record I am little bit newbie in Hibernate and DBMS and stuck on a problem. I have two table. One is A and second is B. There is Many-to-One relationship between these two tables. Now on removing one record from table A I do not want to delete the record from table B. What type of cascading strategy should I apply.
Please help.

A: Here's what Hibernate manual says.
Based on what you wrote I think you should use cascade="persist,merge,save-update"


text:
Q: Installing Microsoft.Extensions.DependencyInjection in .NET Framework 4.7.1 project I'm attempting to install the Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.DependencyInjection.Abstractions 2.0.0 nuget packages into a .NET Framework 4.7.1 project (Microsoft.AspNet.OData), however I'm getting the error:

Could not install package 'Microsoft.Extensions.DependencyInjection
  2.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.7.1', but the package does not
  contain any assembly references or content files that are compatible
  with that framework. For more information, contact the package author.

The dependency for these packages is .NETStandard,Version=v2.0. I understand that .NET Standard isn't .NET Framework, however I thought that .NET Framework 4.6 and greater projects could install .NET Standard projects? If this isn't possible, then are there other equivalent versions of these nuget packages for .NET Framework?
The whole reason that I'm going through this exercise is because many developers are completely blocked by Microsoft.AspNet.OData only supporting DI 1.0, not 2.0. This means that we cannot upgrade our nuget packages in our OData web api, as other packages require DI 2.0 but OData is stuck on 1.0. The rest of our applications are using the latest and greatest, so really it means that our OData web api solution can't leverage ANY of our shared code, and is completely quarantined until this compatibility block is resolved.

A:
Installing Microsoft.Extensions.DependencyInjection in .NET Framework 4.7.1 project

I think the error message is not accurate. When I install the nuget package Microsoft.Extensions.DependencyInjection 2.0.0 to the project (Microsoft.AspNet.OData), I got the following error message:

Unable to resolve dependencies.
  'Microsoft.Extensions.DependencyInjection 2.0.0' is not compatible
  with 'Microsoft.AspNet.OData 7.0.0-beta2 constraint:
  Microsoft.Extensions.DependencyInjection (>= 1.0.0 && < 2.0.0)'.

That is exactly what you said "because many developers are completely blocked by Microsoft.AspNet.OData only supporting DI 1.0, not 2.0."
Check the dependencies of package Microsoft.AspNet.OData, we could know there are strict restrictions for the dependencies Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.DependencyInjection.Abstractions ((>= 1.0.0 && < 2.0.0))
So, this is really a issue that the package Microsoft.AspNet.OData don't support DI 2.0. Many other communities also report this issue on Github, but there is still no any workaround and solution.
My current workaround is:

*

*Create a new project without installing package Microsoft.AspNet.OData.

*Install the other dependencies of package Microsoft.AspNet.OData: Microsoft.OData.Core (>= 7.2.0 && < 8.0.0), Microsoft.AspNet.WebApi.Core (>= 5.2.2 && < 5.3.0) and Microsoft.AspNet.WebApi.Client (>= 5.2.2 && < 5.3.0) (The latter two packages should be included in the template by default).

*Install the nuget package Microsoft.Extensions.DependencyInjection 2.0.0

*Install the nuget package Microsoft.AspNet.OData with option -IgnoreDependencies in the Package Manager Console:
update-package Microsoft.AspNet.OData -IgnoreDependencies -IncludePrerelease
With this workaround, we could use Microsoft.AspNet.OData and DI 2.0, but I could fully confirm whether breaking the dependency limition will cause any problem for the Microsoft.AspNet.OData package. Simple tests are not problematic.
Hope this helps.


text:
Q: React Js Event handling in Mapped object I am learning React js and I cannot get the following code to work, I am trying to build a calculator but when I put the onClick event handler on mapped objects they do not work. Any help would be appreciated

class Calculator extends React.Component{

constructor(){
  super();
  this.state = {
    initialVal:'',
    formula:'33',
    buttons:buttons
  }
  this.clearMem = this.clearMem.bind(this)
  this.addToFormula = this.addToFormula.bind(this)

}
componentDidMount = () =>{
  console.log("Component Mounted!!")
}
clearMem = () => {
  console.log("clearmem")
    this.setState({formula:'0'})
  }

addToFormula = (e) => {
  console.log(e)
  this.setState({formula:'9999'})

}

render(){

       const {formula} = this.state;
       return (

{formula}

           {
             this.state.buttons.map(function(button){
                  if (button.id==="AC"){
                   return <Button
                           onClick = {this.clearMem}
                           key={button.id}
                           value={button.value}
                           className="number-button"/>

                }  else if (button.id === '-'){  return  <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           />
                }  else if (button.id === '+'){  return  <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           />
                }  else if (button.id === '/'){  return  <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           />
                }  else if (button.id === '*'){  return  <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           />
                }  else if (button.id === '='){  return  <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           />
                }  else if (Number.isInteger(parseInt(button.id))){  return <Button
                           key={button.id}
                           value={button.value}
                           className="number-button"
                           onClick = {this.addToFormula}
                           />
                }

              },this)
           }

       )
}
}

I am trying to eventually make it so that when I press the "AC" button the formula turns to zero. But no onClick event handler works for any of the mapped objects
Any help would be tremendous. Thank you

A: class Calculator extends React.Component{
  constructor(){
    super();
    this.state = {
      initialVal:'',
      formula:'33',
      buttons:[{"id":"AC", "value":"AC"},{"id":"+","value":"+"},{"id":"-","value":"-"},{"id":"/","value":"/"},{"id":"*","value":"*"},{"id":"=","value":"="}]
      }
      this.clearMem = this.clearMem.bind(this)
      this.addToFormula = this.addToFormula.bind(this)
    }
    componentDidMount = () =>{
      console.log("Component Mounted!!")
    }
    clearMem = () => {
      console.log("clearmem")
      this.setState({formula:'0'})
    }

    addToFormula = (e) => {
      console.log(e)
      this.setState({formula:'9999'})
    }

render(){
    const {formula} = this.state;
    return (

{formula}

       {
         this.state.buttons.map(function(button){
              if (button.id==="AC"){
               return <Button
                       handleClick = {this.clearMem}
                       key={button.id}
                       value={button.value}
                       className="number-button"/>

            }  else if (button.id === '-'){  return  <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       />
            }  else if (button.id === '+'){  return  <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       />
            }  else if (button.id === '/'){  return  <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       />
            }  else if (button.id === '*'){  return  <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       />
            }  else if (button.id === '='){  return  <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       />
            }  else if (Number.isInteger(parseInt(button.id))){  return <Button
                       key={button.id}
                       value={button.value}
                       className="number-button"
                       onClick = {this.addToFormula}
                       />
            }
          },this)
       }

    )
  }
}

import React from 'react';

const Button = (props) => (
    <button
        id={props.id}
        onClick={props.handleClick}>{props.value}
    </button>
)

export default Button


text:
Q: using space in path for copying files using batch script I want to copy all the *.jar files to another directory  i wrote the below script
echo Enter path to ILM_HOME:
set /p ILM_HOME=

echo Deployment in progress
copy  WEB-INF/lib/*.jar "%ILM_HOME%"/webapp/WEB-INF/lib

I use C:\Documents and Settings\asimon\Desktop\test as my input
It gives me syntax of the command is incorrect
I think the problem is Documents and Settings I even put "%ILM_HOME%" and I don't need c:\Docume~1\asimon\Desktop\test any other solution?
Update
This is working
@echo off
echo

echo Enter path to ILM_HOME:
set /p ILM_HOME=

IF EXIST "%ILM_HOME%\stopApplimation.bat" (

echo Deployment in progress
xcopy WEB-INF\lib\*.jar "%ILM_HOME%\webapp\WEB-INF\lib"

CALL "%ILM_HOME%\stopApplimation.bat"

CALL "%ILM_HOME%\startApplimation.bat"

) ELSE (
echo %ILM_HOME% path is incorrect.
)

also any linux solution is also helpfull with .sh for the below 2 statements
"%ILM_HOME%/stopApplimation.bat"
"%ILM_HOME%/startApplimation.bat"

for linux, how can i replace the above 2 statements?
$ILM_HOME/stopApplimation.sh
$ILM_HOME/startApplimation.sh

A: Did you try
xcopy  WEB-INF\lib\*.jar "%ILM_HOME%\webapp\WEB-INF\lib"?
EDITED:
In your batch use CALL "%ILM_HOME%\stopApplimation.bat"


text:
Q: How to save in global environment immediately using gwidgets? I'm currently building a GUI in R which uses a Google API. I'm using gwidgets2 and when I add a handler to the button I expect it to save the output in my global environment.
addHandlerClicked(search_button, handler = function(h,...) {
  .GlobalEnv$output = api_call(svalue(txt_pattern1),lon,lat,50000,NULL,api_key)

})

However, only when I close the window and run the script again does it then only show that it has saved in the global environment. i.e. output will show in global environment. How can I fix this so that after I click the button it stores in global environment?


text:
Q: Javascript create number upto 17 decimal places I have to create a JavaScript Number containing 17 decimal places. I used the following code :
var integerPart  = "10";
var roundedDigits = "12345678912345678";
var x  = Number(integerPart + '.' +  roundedDigits);

Output:
10.123456789123457
But when I try to output this number object, I get max of 15 decimal places. How can I achieve this?

A: all numbers in javascript are double. they have a maximum of 16 digits.
you need a special datatype like BigDecimal
see this answer
Dealing with float precision in Javascript
and
IEEE floating point


text:
Q: Убрать отступ у изображения в контейнере Ребят, у меня есть контейнер, а в нём лежит изображение. У изображения в container-2 есть отступ сверху (выделил красным), который я никак не могу убрать и не могу найти причину, почему он там есть.

html,
body,
h1 {
  font-family: 'Gamja Flower', cursive;
  padding: 0;
  margin: 0;
}

header {
  height: 110px;
  color: #edeff1;
}

nav,
.menu {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  font-size: 22px;
}

.menu li {
  display: block;
  margin-right: 40px;
  margin-top: 30px;
  margin-left: 40px;
  font-weight: bold;
}

li:nth-child(3) {
  margin-top: 21px;
  color: #ffffff;
  background-color: #dd4b2b;
  border-radius: 10px;
  padding: 8px 20px;
  text-decoration: none;
  text-align: center;
}

.menu li a {
  text-decoration: none;
  color: #31353e;
}

.main {
  width: 100%;
}

.image {
  position: relative;
}

.image img {
  display: block;
  width: 100%;
  height: 1000px;
}

.image .captions {
  left: 5%;
  right: 5%;
  bottom: 55%;
  position: absolute;
  text-align: center;
  line-height: 0.5;
}

.image .captions .line-1 {
  color: #fff;
  font-size: 30px;
}

.line-1 h1 {
  letter-spacing: 2px;
}

.image .captions .line-2 {
  color: #fff;
  font-weight: bold;
  font-size: 26px;
}

.main-2 .icons {
  color: white;
  left: 15%;
  right: 5%;
  bottom: 25%;
  position: absolute;
}

.icons img {
  width: 110px;
  height: 110px;
}

.main-2 .icons-2 {
  color: white;
  left: 50%;
  right: 5%;
  bottom: 23%;
  position: absolute;
}

.icons-2 img {
  width: 110px;
  height: 110px;
}

.main-2 .icons-3 {
  color: white;
  left: 80%;
  right: 5%;
  bottom: 21%;
  position: absolute;
}

.icons-3 img {
  width: 110px;
  height: 110px;
}

.button {
  position: absolute;
  bottom: 9%;
  left: 43%;
  display: block;
  text-decoration: none;
  font-size: 22px;
  text-align: center;
  color: #61362c;
  background-color: #fff;
  border-radius: 20px;
  padding: 15px;
  width: 145px;
}

.container {
  padding: 0;
  margin: 0;
  height: 900px;
  width: 100%;
  background-color: #edeff1;
  text-align: center;
}

.container h1 {
  padding-top: 80px;
  font-size: 52px;
}

div.images {
  margin-top: 87px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.first h2 {
  text-align: center;
  padding-top: 20px;
}

.first p {
  text-align: center;
}

.second h2 {
  text-align: center;
  padding-top: 20px;
}

.second p {
  text-align: center;
}

.third h2 {
  text-align: center;
  padding-top: 20px;
}

.third p {
  text-align: center;
}

.button2 {
  display: block;
  text-decoration: none;
  font-size: 22px;
  text-align: center;
  color: #66686f;
  background-color: #fff;
  border-radius: 20px;
  padding: 15px;
  width: 195px;
  margin: 40px auto;
}

.container-2 {
  width: 100%;
  height: 350px;
  background-color: white;
  padding: 0;
  margin: 0;
}

.container-2 img {
  background-color: red;
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
<link href="https://fonts.googleapis.com/css?family=Gamja+Flower" rel="stylesheet">

Fusce at

Facilisis

Ante donec

Blandit rhoncus

Placerat

Integer at tortor ut magna

finibus lobortis sed quis tellus.

Tincidont

        Phasellus arcu justo, ullamcorper non diam sit amet,
 luctus condimentum metus. Nullam tempus egestas
 efficitur. Sed quam dolor.

Duis Bibendum

        Ut arcu arcu, faucibus eu risus blandit, pulvinar
 viverra justo. Phasellus arcu justo, ullamcorper
 non diam sit amet, luctus condimentum metus. In
 hac habitasse platea dictumst.

Donec Ligula

        Nullam tempus egestas efficitur. Sed quam dolor,
 vulputate sed mattis et, sodales quis orci. Ut arcu
 arcu,faucibus eu risus blandit,.

    Read more

Our news

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more

A: Полоски не вижу - возможно у нас на картинке есть прозрачный фон сверху

html,
body,
h1 {
  font-family: 'Gamja Flower', cursive;
  padding: 0;
  margin: 0;
}

header {
  height: 110px;
  color: #edeff1;
}

nav,
.menu {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  font-size: 22px;
}

.menu li {
  display: block;
  margin-right: 40px;
  margin-top: 30px;
  margin-left: 40px;
  font-weight: bold;
}

li:nth-child(3) {
  margin-top: 21px;
  color: #ffffff;
  background-color: #dd4b2b;
  border-radius: 10px;
  padding: 8px 20px;
  text-decoration: none;
  text-align: center;
}

.menu li a {
  text-decoration: none;
  color: #31353e;
}

.main {
  width: 100%;
}

.image {
  position: relative;
}

.image img {
  display: block;
  width: 100%;
  height: 1000px;
}

.image .captions {
  left: 5%;
  right: 5%;
  bottom: 55%;
  position: absolute;
  text-align: center;
  line-height: 0.5;
}

.image .captions .line-1 {
  color: #fff;
  font-size: 30px;
}

.line-1 h1 {
  letter-spacing: 2px;
}

.image .captions .line-2 {
  color: #fff;
  font-weight: bold;
  font-size: 26px;
}

.main-2 .icons {
  color: white;
  left: 15%;
  right: 5%;
  bottom: 25%;
  position: absolute;
}

.icons img {
  width: 110px;
  height: 110px;
}

.main-2 .icons-2 {
  color: white;
  left: 50%;
  right: 5%;
  bottom: 23%;
  position: absolute;
}

.icons-2 img {
  width: 110px;
  height: 110px;
}

.main-2 .icons-3 {
  color: white;
  left: 80%;
  right: 5%;
  bottom: 21%;
  position: absolute;
}

.icons-3 img {
  width: 110px;
  height: 110px;
}

.button {
  position: absolute;
  bottom: 9%;
  left: 43%;
  display: block;
  text-decoration: none;
  font-size: 22px;
  text-align: center;
  color: #61362c;
  background-color: #fff;
  border-radius: 20px;
  padding: 15px;
  width: 145px;
}

.container {
  padding: 0;
  margin: 0;
  height: 900px;
  width: 100%;
  background-color: #edeff1;
  text-align: center;
}

.container h1 {
  padding-top: 80px;
  font-size: 52px;
}

div.images {
  margin-top: 87px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.first h2 {
  text-align: center;
  padding-top: 20px;
}

.first p {
  text-align: center;
}

.second h2 {
  text-align: center;
  padding-top: 20px;
}

.second p {
  text-align: center;
}

.third h2 {
  text-align: center;
  padding-top: 20px;
}

.third p {
  text-align: center;
}

.button2 {
  display: block;
  text-decoration: none;
  font-size: 22px;
  text-align: center;
  color: #66686f;
  background-color: #fff;
  border-radius: 20px;
  padding: 15px;
  width: 195px;
  margin: 40px auto;
}

.container-2 {
  width: 100%;
  height: 350px;
  background-color: white;
  padding: 0;
  margin: 0;
}

.container-2 img {
  background-color: red;
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
<link href="https://fonts.googleapis.com/css?family=Gamja+Flower" rel="stylesheet">

Fusce at

Facilisis

Ante donec

Blandit rhoncus

Placerat

Integer at tortor ut magna

finibus lobortis sed quis tellus.

Tincidont

        Phasellus arcu justo, ullamcorper non diam sit amet,
 luctus condimentum metus. Nullam tempus egestas
 efficitur. Sed quam dolor.

Duis Bibendum

        Ut arcu arcu, faucibus eu risus blandit, pulvinar
 viverra justo. Phasellus arcu justo, ullamcorper
 non diam sit amet, luctus condimentum metus. In
 hac habitasse platea dictumst.

Donec Ligula

        Nullam tempus egestas efficitur. Sed quam dolor,
 vulputate sed mattis et, sodales quis orci. Ut arcu
 arcu,faucibus eu risus blandit,.

    Read more

Our news

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more

Lorem ipsum

Est a elit scelerisque vestibulum. Donec est sem,
 lobortis sit amet imperdiet vel, pretium lobortis
 erat. Nulla vitae hendrerit odio.

      Read more


text:
Q: Variable does not get replaced inside ' ' in a bash function I need to put this
gulp --cordova 'prepare ios' --buildVars='version:${buildVarVersion},target:${target}' --res=${target}
gulp --cordova 'build ios --device --release --codeSignIdentity=${codeSignIdentity}' --no-build --res=${target}

inside a function. The single quotes need to be preserved. I'm struggling with the correct escaping. I've tried:
function buildIPA() {
  CFBundleIdentifier=$1
  target=$2
  version=$3
  codeSignIdentity=$4

  buildVarVersion="public";
  if [ "$version" = "enterprise" ]; then
      buildVarVersion="private";
  fi

  gulp --cordova \'prepare ios\' --buildVars=\'version:${buildVarVersion},target:${target}\' --res=${target}
  gulp --cordova \'build ios --device --release --codeSignIdentity=${codeSignIdentity}\' --no-build --res=${target}

};

But it seems that this translates to:
gulp --cordova prepare ios --buildVars=version:${buildVarVersion},target:${target} --res=${target}

removing the single quotes alltogether.

A: You should replace all
gulp --cordova \'prepare ios\' --buildVars=\'version:${buildVarVersion},target:${target}\' --res=${target}

with
gulp --cordova "prepare ios" --buildVars="version:${buildVarVersion},target:${target}" --res=${target}

otherwise word-splitting (at blanks) will cause your commands to receive more args than you expect.

A: Wrap the part containing the variables in double quotes:
gulp --cordova 'prepare ios' --buildVars="'version:${buildVarVersion},target:${target}'" --res=${target}
gulp --cordova "'build ios --device --release --codeSignIdentity=${codeSignIdentity}'" --no-build --res=${target}


text:
Q: Получение минут и секунд из полного времени в виде строки Есть функция _tctime, которая форматирует число в строку следующего формата:

день.месяц.год часы:минуты:секунды

А какая функция форматирует в формате

минуты:секунды.

int tileLeft = 113;
TCHAR caption[100] = {};
_tcscpy_s(caption, _tctime(&tileLeft));
caption[_tcslen(caption) - 1U] = TEXT('\0');

A: Для более полной настройки формата строки времени можно использовать функции типа strftime. При этом стоит отметить, что ctime работает с time_t (UNIX time). И итог есть не интервал времени, а точка во времени от 1970 года.
Если же Ваша переменная просто содержит кол-во секунд, и нужно вывести это значение как минуты и секунды - самый простой вариант ограничиться делением, как это уже было предложено в комментарии:
timeLeft / 60 -> минуты
timeLeft % 60 -> секунды


text:
Q: How can I reach specific Facebook users who are not connected to my app? Is it anyhow possible to reach a Facebook user through a Facebook app who is not a user of the app?
The only way I found so far is to send an email to {username}@facebook.com, but this message will go to the "other" folder.
Further, I guess an app cannot make use of the "paid messaging" feature? (Users who are not connected to each other can pay $1.00 to send a message to someones inbox).
Is there any other way? (Notifications? Requests?)
Edit:
Here is an example:
Imagine an app where you can send gifts or greeting cards.
User A is connected to the app and sends a gift to User B (who isn't a user of the App). How can User B learn about his gift? Hard mode: User B isn't connected with User A.

A:
How can User B learn about his gift?

*

*by User A making a post on their wall (if User A is allowed to do so) -> Feed dialog

*by User A sending them a private message -> Send dialog

*by User A asking them to join the app -> invite via Request dialog


text:
Q: How to remove '../' tokens from a file path using the Visual Studio 2012  classes? I have a file path like
"C:/Documents/Music/Jazz/../../Pictures/picture.jpg".
I need to remove the '../' tokens and transform the original file path to "C:/Documents/Pictures/picture.jpg".
How could I do that using the classes from Visual Studio 2012 (or 2013)  header?

A: C++11 does not have a filesystem library. This is considered for the C++14 or C++17 standards.
Boost has a filesystem api, boost:filesystem:path is what you might want to look at.

A: C++ 11 doesn't have a filesystem library.
However it does have a algorithm library and string library which will work for you.

A: C++11 doesn't contain filesystem library. You can work with your path using standard facilities offered by std::string:
std::string s("C:/Documents/Music/Jazz/../../Pictures/picture.jpg");
size_t t;
while ( (t = s.find( "/..")) != std::string::npos) {
    s.erase( t, 3);
}
if ( (t = s.find( "/Music/Jazz")) != std::string::npos) {
    s.erase( t, 11);
}


text:
Q: Hyperloop without acceleration feeling I have a question about hyperloop.
Is it possible to create a hyperloop with high acceleration and that the passengers dont feel the acceleration, theoretically speaking?
And is a situation possible you dont feel acceleration?

A: In fact yes it's possible in theory, sorry to disagree with some other posts.
Because of the absence of tidal forces due to earth's gravity on the human scale you don't feel acceleration due to gravity. When you fall you feel a reduction in acceleration against gravity. When in free fall you experience no acceleration although external observers will see you speed up as you follow a gravitational geodesic.
Therefore a frame of reference of vehicle in free fall can be manipulated with artificial acceleration of 1g in any desired direction and the force felt by occupants will be 1g. All you have to do is orient the passenger such that they point in the right direction matching the acceleration and they cannot distinguish this acceleration from that normally experienced on the planet surface.  This is Einstein's equivalence principal.
The solution hyperloop involves an initial descent phase and final ascent stage, which are connected by the horizontal transport stage.
In an initial descent and final ascent therefore up to 2g could be applied, which is tons; there are more moderate "partly falling" solutions. Generally the shape has to be very carefully calculated.
I'm not saying it's practical, of course, there are enough engineering challenges in hyperloops already, not least of which is maintaining a tube vacuum in the first place.

A: I guess you want to a roller coaster path with constant apparent gravity (in magnitude).  That would be a clothoid loop.

Check the mathematical treatment here.

A: First,
one should claryfy what it means "to feel acceleration".
If you think of that as being pressed into the back of
your seat, then yes that can be avoided.
Just fill the passenger cabin with a liquid of similar
density as your body (e. g. water) and wear some scuba
apparatus (the cylinders with pressurized air should be
mounted separately, the tubes from the cylinders to your
mouth should have a mean density of 1 g cm³)
In such a hyperloop you will see pressure rise and fall
on a manometer, but no "acceleration" in Your back.
A problem might arise with the cavity of your lung,
I need to think about that.
Georg


text:
Q: Is there a way to simply copy console output into new text file? I had a very simple request, I have a full code that sorts through an input file and outputs the merged strings properly into the console. My question is can I take this already perfect output from my CONSOLE and simply output it into a seperate .txt fle as well?
I've tried doing a simple
PrintStream printStream = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(printStream);
it does create my output.txt file, but it's always empty?

A: Option 1: Output via Terminal
Since your script already outputs perfectly to the terminal, you can redirect that output to a file via >
$ ./my-script > output.txt

You can also use the tee command if you still want to see the output in your terminal.
$ ./my-script | tee output.txt

Option 2: Generate file via code
I'm not too familiar with Java / PrintStream but from https://www.tutorialspoint.com/java/io/printstream_print_string.htm, you should see content in your file by:
PrintStream printStream = new PrintStream(new FileOutputStream("output.txt"));

printStream.print("foo");

printStream.flush();


text:
Q: Defining an array out of method in C I am new in C, I have a question and I searched  in here and google but I didn't get answer.
int main(){
char name[];
name = "PeerNet";
}

this is wrong I know but
char name[];
int main(){
scanf("%s", name); // I write PeerNet in scanf.
}

this is allowed.
What is the difference? And how compiler act?

A: It's a difference in how initialization works vs. what scanf does. When you want to initialize a character array to a string, you have to do it right when you declare the array. The initialization then copies characters from the string literal into the array. Assigning a string literal to a character array is not allowed at any other time, because this copying and filling of the array process only happens at initialization. At any other time, such as saying:
name = "PeerNet";

The compiler sees this as telling the pointer to the character array to point somewhere else, which shouldn't happen -- that array pointer has to remain bound to its own array.
However, scanf follows this copy and fill process even after the array is declared. So with a statement like:
scanf("%s", name);

scanf will copy the characters in the inputted string into the array called name.

A: please use index number for array if you are not initializing. You can write like:
int main(){
char name[8];
strcpy(name,"PeerNet");
}

or
int main(){
char *name;
name="PeerNet";
}

The error you are doing is, you are trying to assign a char * type to char type, (name is a char type and "PeerNet" is a char * type), which you cannot do.
And you cannot assign a whole string to char type because char type is one byte and string is starting from first character more than one byte. So, use strcpy to assign that string to your char type array.
And one more neither of your codes will run! Even if you make your character array global, you should give index number (plus one for null) as below:
char name[8];
int main(){
    name="PeerNet";
    }

Of course this
char name[];
int main(){
scanf("%s", name); // I write PeerNet in scanf.
}

will work but in undefined way, actually it's not encouraged, you might be getting correct results now, but in future if you extend code we cannot guaranty.
You are writing to unallocated memory (beyond the array). In order to compile this, the compiler is allocating at least one element, and you're then writing beyond that.


text:
Q: Change range of a DC signal without changing the offset with op amps I have a voltage signal with the following range:
low - 2.5VDC
middle point - 2.725VDC
high - 2.95VDC
I would like to condition this signal to:
low - 0.4VDC
middle point - 1.65VDC
high - 2.9VDC
I have only a +/-12VDC power supply available, op-amps, capacitors and resistors. Anybody has any suggestions on how can I do it? Thanks!
EDIT:
Added by DKNguyen for clarification.

A: You want a non-inverting amplifier configuration, with an offset.

simulate this circuit – Schematic created using CircuitLab
Because it's an op-amp, if the circuit is stable then \$V_- = V_{in}\$.  You can calculate \$V_-\$ using the voltage divider equation:
$$V_{in} = V_- = \frac{R_1 V_{out} + R_2 V_1}{R_1 + R_2}.$$
Solving, \$ V_{out} = \left(1 + \frac{R2}{R1}\right) V_{in} - \frac{R2}{R1} V_1\$.
Take two pairs of your voltages:
$$\begin{aligned}
2.9 \mathrm V & = \left(1 + \frac{R2}{R1}\right) 2.95 \mathrm V - \frac{R2}{R1} V_1 \\
0.4 \mathrm V & = \left(1 + \frac{R2}{R1}\right) 2.50 \mathrm V - \frac{R2}{R1} V_1
\end{aligned}$$
Now it's down to high-school algebra (I'll cheat and use Maxima):
$$\frac{R2}{R1} = \frac{41}{9} \simeq 4.56,\ V_1 = \frac{607}{205} \simeq 2.96 \mathrm V.$$
Use a resistive divider to obtain your 2.96V, compute it's Thevenin equivalent resistance (which will just be the parallel equivalent of the two resistors in the divider) then compute R2.  You won't get things exactly right, so then you'll want to juggle resistor values until you get close enough to make you happy (I suggest using math or a circuit simulator to home in on the best values).
Falstad Circuit Simulator
$ 1 0.000005 10.20027730826997 57 5 50 5e-11
v 80 224 80 176 0 0 40 2.95 0 0 0.5
w 304 304 304 352 0
a 304 288 448 288 9 15 -15 1000000 2.9499709571690462 2.95 100000
w 448 288 448 352 0
r 304 352 448 352 0 41000
r 208 352 304 352 0 9000
w 208 208 304 208 0
w 304 208 304 272 0
O 448 288 512 288 0 0
g 160 272 160 288 0 0
v 208 400 208 352 0 0 40 2.96 0 0 0.5
g 208 400 208 416 0 0
S 208 208 160 208 0 1 false 0 2
S 160 192 128 192 0 1 false 0 2
v 112 256 112 208 0 0 40 2.725 0 0 0.5
v 160 272 160 224 0 0 40 2.5 0 0 0.5
w 80 176 128 176 0
w 112 208 128 208 0
g 80 224 80 240 0 0
g 112 256 112 272 0 0
o 0 64 3 4098 5 0.00009765625 0 1

A: Try this code imported into Falstad Circuit Simulator
 $ 1 0.000005 10.20027730826997 57 5 50 5e-11
v -176 224 -176 176 0 0 40 2.5 0 0 0.5
w 304 304 304 352 0
a 304 288 448 288 9 15 -15 1000000 1.4249675011270142 1.4249715005717007 100000
w 448 288 448 352 0
r 304 352 448 352 0 45550
r 208 352 304 352 0 10000
w 208 208 304 208 0
w 304 208 304 272 0
O 448 288 512 288 0 0
a 64 208 208 208 9 15 -15 1000000 0.7124857502849943 0.7125 100000
v -80 320 -80 272 0 0 40 -1.075 0 0 0.5
r 0 160 -80 160 0 50000
r 0 224 -80 224 0 50000
w -80 160 -128 160 0
g -80 320 -80 336 0 0
r 64 272 208 272 0 10000
w 208 272 208 208 0
w 64 224 64 272 0
w 0 224 64 192 0
w 64 192 0 160 0
g -176 224 -176 240 0 0
r 64 272 64 336 0 10000
g 64 336 64 352 0 0
v 208 400 208 352 0 0 40 1.65 0 0 0.5
g 208 400 208 416 0 0
x -241 102 -210 105 4 15 Input
x -163 304 -113 307 4 15 -1.075V
x 149 379 186 382 4 15 1.65V
x -67 109 -4 112 4 24 Offset
x 42 107 367 110 4 24 Offset\sCompensation\sAmplifier
x 329 222 599 225 4 24 Dynamic\sRange\sAmplifier
w -80 224 -80 272 0
S -128 160 -176 160 0 0 false 0 2
S -176 144 -224 144 0 0 false 0 2
v -224 208 -224 160 0 0 40 2.725 0 0 0.5
v -272 176 -272 128 0 0 40 2.95 0 0 0.5
g -272 176 -272 192 0 0
g -224 208 -224 224 0 0
w -272 128 -224 128 0

Not very elegant, but I'm not sure if op-amp offsetting circuits ever are.
The structure is a summer to offset the voltage center by -1.075V so 2.725V becomes 1.65V. The resistor divider nature of the summer halves the output voltage from what it should be so I re-amplified it by two relative to GND to compensate.
Then the re-centered signal is fed and amplified by a gain of 5.555 to change the dynamic range from \$2.95V-2.5V=0.4V\$ to \$2.9V - 0.4V = 2.5V\$. The amplification here takes place about 1.65V (rather than GND) so that the signal center is preserved.


text:
Q: pip install with --no-cache-dir and --target I'm trying to make an AWS lambda function that will run a python script and it has to use python2.7 (because I can't make it work with python3). I am trying to put together a dependency package for my script that includes beautiful soup but I keep running into the error message:
ImportError: No module named html.entities
I've found the source of the error (https://docs.python.org/2.7/library/htmllib.html#module-htmlentitydefs - this module was renamed in the switch from 2 to 3) and I found a solution that will make it run without this error on my computer. If I just run pip install --upgrade --no-cache-dir beautifulsoup4, then I can run python2.7 master.py and it works without error. But the problem comes when I try to create this dependency package. I run pip install --upgrade --no-cache-dir beautifulsoup4 --target . and the packages I want show up in the directory, but then when I run the script again it gets the same error as before:
/home/user/.../tempStorage/bs4/element.py:16: UserWarning: The soupsieve package is not installed. CSS selectors cannot be used.
  'The soupsieve package is not installed. CSS selectors cannot be used.'
Traceback (most recent call last):
  File "master.py", line 10, in <module>
    from bs4 import BeautifulSoup
  File "/home/user/.../tempStorage/bs4/__init__.py", line 34, in <module>
    from .builder import builder_registry, ParserRejectedMarkup
  File "/home/user/.../tempStorage/bs4/builder/__init__.py", line 7, in <module>
    from bs4.element import (
  File "/home/user/.../tempStorage/bs4/element.py", line 19, in <module>
    from bs4.dammit import EntitySubstitution
  File "/home/user/.../tempStorage/bs4/dammit.py", line 13, in <module>
    from html.entities import codepoint2name
ImportError: No module named html.entities

It seems that the difference is that this time it is using the dependencies installed to the directory it is in rather than the ones somewhere else on my machine and unfortunately, it's the ones in this directory that I need to be able to work with. Any help would be appreciated.
EDIT:
A little more info. When I run python2.7 -c "import bs4 ; print(bs4.__version__)" from the directory where I put the dependency packages (with the --target command) I get
bs4/element.py:16: UserWarning: The soupsieve package is not installed. CSS selectors cannot be used.
  'The soupsieve package is not installed. CSS selectors cannot be used.'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "bs4/__init__.py", line 34, in <module>
    from .builder import builder_registry, ParserRejectedMarkup
  File "bs4/builder/__init__.py", line 7, in <module>
    from bs4.element import (
  File "bs4/element.py", line 19, in <module>
    from bs4.dammit import EntitySubstitution
  File "bs4/dammit.py", line 13, in <module>
    from html.entities import codepoint2name
ImportError: No module named html.entities

and when I run the same command from a different directory (I just went to cd .. in this case) I get
4.4.1


text:
Q: Finding the angle formed by the tangents of a triangle inscribed in a square
In the following image, $ABCD$ is a square and $AEF$ is an isosceles
triangle with $|AF|=|AE|$, such that $E$ and $F$ are on segments $BC$ and $DC$, respectively.
Point $I$ is the barycentre of $AEF$ and circle $c$ has centre $I$ and
is tangent to $FE$ in $J$. $AK$ and $AL$ are the tangents to circle
$c$ from point $A$. Find the measure of  $\angle{BAL}$.

Any ideas to this problem? I did notice that the points of tangency of lines $AK$ and $AL$ to circle $c$ form with point $J$ an equilateral triangle. I feel like that could be the key to the solution but I can't seem to find anything to go further (also it looks like those points form a parallel line to $FE$ but I can't find a succesful proof of that).

A: Because $I$ is the centroid, we have that $AI = 2IJ$. Letting $P$ and $Q$ be the $2$ tangency points, we then have that $\angle IPA = \angle IQA = 90^{\circ}$ and $AI = 2IP = 2IQ$. However, this means that $\triangle IPA$ and $\triangle IPQ$ are 30-60-90 triangles, so $\angle BAL = 45 - \angle IAP = \boxed{15^{\circ}}$

A: Hint:  $AI=\frac 23AJ$.  There is nothing to locate $J$ in the problem.  If you trust the problem setter to ensure a unique solution, it cannot depend on where $J$ is.  Probably the easiest place is $J=C$.  Now figure out where $I$ is and the radius of the circle.  If you are not willing to trust the problem setter, you need to demonstrate that the positions of $K$ and $L$ do not depend on where $J$ is.


text:
Q: Browser app to connect to several sshd I would like to draft a browser application which can connect to ~20 remote sshd. Per ssh connection multiple commands should be handled. After restarting the browser, the several running jobs should be displayed in the browser again.
How would you construct the application ? The application should run on a Raspberry Pi. So utilization is limited.

A: Check the wikepedia page for web based SSH. The basic idea is to have JavaScript on client to submit commands to server side web application. And server side application will connect to several different server sshd as proxy to send command and receive output.
Personally I will suggest to use WebSocket to implement the communication between client and server. But not sure what's the OS you will have and what library and programming language will be handy for you.


text:
Q: What are all the different names for apps, projects, modules etc in Android Studio Changing names in Android Studio is a nightmare, particularly as it seems to use a number of different names. I think I worked out how to change most of them, but what is this (see yellow highlighting on screenshot attached) and how do I change it?

A: for your problem with names, if you want to change a name of a file/variable in all of the places that it was mentioned in you should use the refractor.

*

*right click on whatever you're changing its name.

*refractor.

*rename/rename file.

*it will ask you for the new name and whether you want to change it everywhere (even in comments if you want) or not.

*choose what you see fit and click refractor, he will then check where it exists and ask for confirmation on all the place he found what you're changing name and if you're 100% sure to change its name there.

warning : sometimes refractor operations are non reversible so you should double check before clicking do refractor.
as for the name up there its called project name and you can change it as instructed here


text:
Q: exclude IE7 from a piece of jQuery? I seem to have a problem with some jQuery, and I can't figure out where I am going wrong so I just want to take ie7 out of the equation by excluding it, can this be done with jQuery?

A: You can try http://api.jquery.com/jQuery.browser/ :)

A: I don't know about jQuery, but you could prevent the code from running using Conditional Comments

A: if you need the detection inside a script(conditional comments are HTML-comments), you can detect it by checking some properties.
var ie7 = (document.all && !window.opera && window.XMLHttpRequest && typeof window.external.AddToFavoritesBar=='undefined') ? true : false;
var ie7mode = (document.all && !window.opera && window.XMLHttpRequest && !document.querySelectorAll) ? true : false;

inside a script you can use it like this:
if(!ie7mode)
{
  //this will be ignored in IE7 or higher versions running in IE7-mode
}
if(!ie7)
{
  //this will be ignored in IE7 only
}


text:
Q: value of private variable is not maintained after page load even in ASP.NET I have two pages. first.aspx and second.aspx. In order to get all the control values from first.aspx, i added directive to second.aspx
<%@ PreviousPageType VirtualPath="~/PR.aspx" %>

I have no problem to get all the previous page controls and set it to labels, but i have a big problem to save those values to a private variable, and reuse it after page load event is done. Here is code example. when i try to get the value from input in another method, it has nothing added. Why?
    public partial class Second : System.Web.UI.Page
        {
            List<string> input = new List<string>();
            protected void Page_Load(object sender, EventArgs e)
            {
                    if (Page.PreviousPage != null&&PreviousPage.IsCrossPagePostBack == true)
                    {
                        TextBox SourceTextBox11 (TextBox)Page.PreviousPage.FindControl("TextBox11");
                        if (SourceTextBox11 != null)
                        {
                            Label1.Text = SourceTextBox11.Text;
                            input.Add(SourceTextBox11.Text);
                        }
                     }
              }

            protected void SubmitBT_Click(object sender, EventArgs e)
        {
                  //do sth with input list<string>
                  //input has nothing in it here.
         }
       }

A: The SubmitBT_Click-click event happens in a postback. But all variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your List, e.g. in the ViewState or Session.
public List<String> Input
{
    get
    {
        if (Session["Input"] == null)
        {
           Session["Input"] = new List<String>();
        }
        return (List<String>)Session["Input"];
    }
    set { Session["Input"] = value; }
}

Nine Options for Managing Persistent User State in Your ASP.NET Application


text:
Q: On the misuse of two sample test: How to report difference in entire "populations" I have the following understanding: Two (or more) sample tests are only required if conclusion should be drawn about a population based on observed samples (typically much smaller than the population).
If I observe the entire population, e.g. quality (numeric) of each product produced in two or more factories, then this approach does not apply. I could directly compare the population means but this does not provide information how important/large (not significant! ) the difference is. One could compare the difference to the std (of either of the populations). To circumvent choosing one standard deviation of one population one could consider a joint standard deviation of the combined population (what if some factories are much larger than others). (standard deviation could be replaced by IQR or similar). This can be extended to multiple products produced in multiple factories.
What is the best way to present these comparisons? What is the best reference to show that no significance test is required (pretty obvious to me).

A: Since you know the full population, you are (indeed) in a position where you do not need to make inference. So, you « simply » need to analyse the figures. Using "side-to-side" boxplots can be a good start to understand better your data.
Simple example in R

factory1 <- c(50,55,52,57,53,2,125,70,74,40,45,48,115,1,56,86,30,69,36)
factory2 <- c(50,55,52,57,53,2,125,70,74,40,45,48,145,1,56,86,30,69,36,28,27,29,24,31,29,85,87,83,89,84,85,84)
factory3 <- c(50,55,52,57,53,2,125,70,74,40,45,48,145,1,56,86,30,69,36,85,87,83,89,84,85,84,120,115,110,109,133,125,129,160,123)
boxplot(factory1, factory2, factory3, names=c("Factory 1","Factory 2", "Factory 3"), col=c("#f68e1f","#00adef", "#ec008b"))

You might also be interested in:

*

*analyzing/comparing central tendency and variability

*identifying correlations

*identifying/explaining outliers

*identifying trends

*etc.


text:
Q: Need to perform the action of a left click when right mouse button is clicked(Jquery) Does anyone know the jquery code  to perform the action of a left click button when right mouse button is clicked
For Example:
Say I right click on a link , instead of opening a pop up window I need it to go the link's destination . In other wants I need the right click to do the action of a mouse left click .
Tried searching the web , but was of no use . Hence posting this as my last option .
Would really appreciate any help .
Thanks in advance .

A: Try
$('a').on('contextmenu', function(e){
    window.location = this.href;
    return false;
});

DEMO

A: $('#element').mousedown(function(event) {
    if (event.which==3) {
        $('#element').trigger('click');
         break;
       }
});


text:
Q: Deleteing multiple SObjects in batch apex I have the following code that executes exactly how I need it to, the only issue is I receive "Apex CPU time limit exceeded" when I run the delete on Accounts, EmailMessage and update Cases. After looking into the error it looks like I need to move this code into a batch job however all of the documentation around batch jobs only ever delete one SObject. How can I execute this code in a batch job since I am looking at 3 SObjects?
The code basically deletes any accounts, cases and emailmessages that are over 30 days old. If the account has a new case then we ignore the old cases until that new case is 30 days old.
    Date threshold = Date.today().addDays(-30);
    List<Account> accountsToDelete = new List<Account>();
    List<Case> casesToDelete = new List<Case>();
    List<EmailMessage> messagesToDelete = new List<EmailMessage>();
    Integer count = 0;
    Integer count2 = 0;
    Integer count3 = 0;
    for (Account account : [
        SELECT (SELECT LastModifiedDate FROM Cases ORDER BY LastModifiedDate DESC)
        FROM Account WHERE Id IN (
            SELECT AccountId FROM Case
            WHERE LastModifiedDate < :threshold
            AND Account.Name Like '%Test%'

        )
    ]){
        if (account.Cases[0].LastModifiedDate < threshold)
        {
            accountsToDelete.add(account);
            casesToDelete.addAll(account.Cases);
        }
    }
    messagesToDelete = [ SELECT Id, ParentId FROM EmailMessage WHERE ParentId IN : casesToDelete];

    for(Case c: casesToDelete){
        c.OwnerId = '005i0000001I5Y3';
        c.Guest_Email__c = '';
        c.Guest_Name__c = 'Purged';
    }

    for(Account a: accountsToDelete){
        a.Id = '0018A000006Xvgo';
    }

    for(EmailMessage e: messagesToDelete){
        e.FromAddress = '';
        e.ToAddress = ''
    }

    update casesToDelete;
    delete accountsToDelete;
    delete messagesToDelete;

A: When dealing with parent and child records in most batch processes, you just need to first query for the parent, and then its children:
global class DeleteOldRecords implements Database.Batchable<SObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            [SELECT Id FROM Account
             WHERE LastModifiedDate < LAST_N_DAYS:30 AND
             Name LIKE '%test%']);
    }
    global void execute(Database.BatchableContext bc, Account[] scope) {
        Set<Id> accountIdsToKeep = new Map<Id, AggregateResult>(
            [SELECT AccountId Id FROM Case WHERE AccountId IN :scope
             AND LastModifiedDate = LAST_N_DAYS:30 GROUP BY AccountId]).keySet();
        Set<Id> accountIdsToDelete = new Map<Id, Account>(scope).keySet();
        accountIdsToDelete.removeAll(accountIdsToKeep);
        if(!accountIdsToDelete.isEmpty()) {
            Case[] casesToDelete = [SELECT Id FROM Case WHERE AccountId IN :accountIdsToDelete];
            EmailMessage[] emailsToDelete = [SELECT Id FROM EmailMessage WHERE ParentId IN :casesToDelete];
            Account[] accountsToDelete = [SELECT Id FROM Account WHERE Id IN :accountIdsToDelete];
            delete emailsToDelete;
            delete casesToDelete;
            delete accountsToDelete;
        }
    }
    global void finish(Database.BatchableContext bc) {
    }
}

When you run this, you can adjust the batch size to figure out what the optimal number is, since batch processes still have governor limits.
Some general notes:

*

*Don't use hard-coded ID values, because they may change or break your tests.

*Don't change the Id field of a record before deleting it, as you'll delete an entirely different record.

*Delete doesn't save new field values, so if that's your intent, you must do so before the delete occurs.

*I'm pretty sure you don't need to delete the emails, since the cascade delete on cases should probably work. You might actually be doing more work than necessary.


text:
Q: How to create a more lighweight fragment? I've a navigation drawer for changing fragments in my MainActivity, there is a fragment that has many views inside it and I need to make it more lightweight.
The problem is that by the time Navigation Drawer hides, the Fragment Transaction hasn't happened yet. My Fragment has 3 CardViews with several EditText inside it, all of them with attached TextWatchers, for updating the text in other views. I've tried to remove as many views as posible, and still not big difference, but if I remove half of the views can notice the change, so I believe that is the problem. Is there any way to make a Fragment more lighweight without removing views?
My NavigationDrawer includes this menu and a header:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/home_fragment_selector"
            android:title="@string/home"
            android:icon="@drawable/icons8_home_96px">
        </item>
        <item
            android:id="@+id/conteo_fragment_selector"
            android:title="@string/review"
            android:icon="@drawable/icons8_banknotes_96px">
        </item>
        <item
            android:id="@+id/exchange_fragment_selector"
            android:title="@string/exchange"
            android:icon="@drawable/icons8_exchange_96px">
        </item>
    </group>
</menu>

For replacing the fragments, the code I'm using looks like this, I used 2 Runnables so I can run the code in any order I want:
@Override
    public boolean onNavigationItemSelected(final MenuItem item) {

        final int id = item.getItemId();

        Runnable closeDrawerLayoutRunnable = new Runnable() {
            @Override
            public void run() {
                mDrawerLayout.closeDrawer(GravityCompat.START);
            }

        };

        Runnable replaceFragmentRunnable = new Runnable() {
            @Override
            public void run() {
                switch (id){
                    case R.id.home_fragment_selector:
                        FragmentTransaction ftHome = getSupportFragmentManager().beginTransaction();
                        ftHome.setCustomAnimations(R.anim.slide_in,0);
                        ftHome.replace(R.id.main_fragment_container,home);
                        ftHome.commit();
                        break;
                    case R.id.count_fragment_selector:
                        FragmentTransaction ftCount = getSupportFragmentManager().beginTransaction();
                        ftCount.setCustomAnimations(R.anim.slide_in,0);
                        ftCount.replace(R.id.main_fragment_container,count);
                        ftCount.commit();
                        break;
                    case R.id.exchange_fragment_selector:
                        FragmentTransaction ftExchange = getSupportFragmentManager().beginTransaction();
                        ftExchange.setCustomAnimations(R.anim.slide_in,0);
                        ftExchamge.replace(R.id.main_fragment_container,exchange);
                        ftExchange.commit();
                        break;
                    default:
                        break;
                }
            }
        };

        Handler mHandler = new Handler();
        mHandler.postDelayed(closeDrawerLayoutRunnable,250);
        mHandler.postDelayed(replaceFragmentRunnable,50);
        return true;
    }

With the other two fragments there's no problem at all, but with count fragment, rest of the code is pretty much the same:
TextWatcher generiTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void afterTextChanged(Editable s) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(s.hashCode()==Edit1000.getText().hashCode()){
                    if(s.toString().equals("")){cup1000 = 0;}
                    else {cup1000 = Float.valueOf(s.toString());}
                    //Same procedure for rest of the EditText, so I can use same TextWatcher instead of using a new one
                }
};

//There is 21 of this EditText with its own findViewById() and TextWatcher attachment
Edit1000 = view.findViewById(R.id.edit_1000);
cupEdit1000.addTextChangedListener(generiTextWatcher);
//.. So on

I've noticed that if I replace this Fragment with another one, and then replace de the other again with this first one, the transaction is very fast, I don't know what can it be

A: I used this idea:
https://stackoverflow.com/a/25671367/11456044
I know this is not an efficient way, but it is very very fast, it solved my problem, at least temporarily


text:
Q: find field references/dependencies in word I've got a ms word file in front of me with ''tons'' of fields. Now im trying to figure out what field is dependent on what other field... or is not referred to at all. Stupid comparison: in excel you put in cell B5 "=A1". If i type something in A1, B5 changes. When i select cell B5 i can see =A1 so B5's reference is A1. Now, how can i check something like that in word's fields?
thanks you all
best regards,
Erik


text:
Q: Correct way for converting RGB heatmap image to Grayscale heatmap I am trying to convert a RGB heatmap image to grayscale heatmap image. First I thought It was a simple rgb to grayscale conversion. But it isn't.
For example, blue color may represent soft things and red color may represent hard things.

Using commonly used simple rgb to grayscale conversion method, I found red and blue color has converted to save gray color although they had very different nature of representation.

But What I want something like this where blue is deep gray, and red is bright gray.

I had searched a lot. Unfortunately I did't find (or maybe I couldn't understand). After reading some article on rgb color model, I have found a way to generate grayscale image. My code is
import colorsys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('input_image/abnormal_hi_res.png')
img = img[ : , : , 0:3] # keep only r, g, b channels

new_image = np.zeros((img.shape[0], img.shape[1]))

for y_pos in range(img.shape[0]):
    for x_pos in range (img.shape[1]):

        color = img[y_pos, x_pos]
        r,g,b = color
        h, _, _ = colorsys.rgb_to_hls(r, g, b)
        new_image[y_pos, x_pos] = 1.0 - h

plt.imshow(new_image, cmap='gray')
plt.show()

But I believe there should exists a good method backed by proven mathematics.
Please help me to find out the correct one for this problem.

A: You can follow these links. They have got some good notes on heatmaps and grayscale
https://docs.opencv.org/3.1.0/de/d25/imgproc_color_conversions.html
https://matplotlib.org/users/colormaps.html
*UPDATE
First, you need to convert your BGR image to LUV then convert it to a grayscale image. Use opencv.
Code for converting BGR to LUV in opencv.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2LUV)
I think it what you are looking for


text:
Q: How to use -*-_DB_SHORT_LIVED_SESSIONS configuration setting What does "-*-" represent in -*-_DB_SHORT_LIVED_SESSIONS (Django-specific) Celery setting.
I need short-lived sessions but I don't understand what am I supposed to replace -*-.
I can't find it in the documentation neither
The Django-specific doc is here:
Django-specific Celery settings doc

A: In short, you shouldn't be using this anymore.
See https://github.com/celery/celery/issues/5819
From this Github issue I raised:
you should use the lowercase database_short_lived_sessions instead. This also applies for Django.


text:
Q: Web Application: Server File Copy - Progress Tracking I have a web application that allows limited file manipulation on the web server. The users can upload, download, copy, and move files to various locations within their file space.
What possibilities do I have, if I wish to track progress of file copying operation from one location to another on the server?
Currently, when I copy a large file (about 1 GB), for couple of seconds nothing happens, until the file copy is finished. During those times, users will definitely be confused, whether their function actually is taking place. I want to show progress bar to inform the user, that this operation is in progress.
I need to show percentage about how much data has been already copied, as it is higher value progress information than just informing, that copying is in progress without percentage info(say a rotating icon with info: Copying in progress.).
Currently, I use php copy() function. Should I implement my own read/write function in PHP?
My planned configuration:

*

*HTML5

*PHP

*JavaScript

*Linux Ubuntu

*Apache Web Server

*MySQL

Thank you in advance.


text:
Q: Merge all MKMapRects to single MKPolygon I want to draw corridor using MKPolygon over MKMap using Mapkit. I have one route from station A to B.
I have MKMapRects around route for drawing corridor. Now i want to merge all rectangles in single Polygon and that is my Corridor along with route. How to join all the rectangles in single Polygon .
No.of rectangles : 160
Here i am attaching sample image indicating what i needed.
Here is code snippet.
for(int i=0;i<[self.boundingRectsArr count];i++) {

            lat1 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"xLT"] doubleValue];
    long1 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"yLT"] doubleValue];

    lat2 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"xRT"] doubleValue];
    long2 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"yRT"] doubleValue];
            lat3 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"xRB"] doubleValue];
    long3 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"yRB"] doubleValue];
    lat4 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"xLB"] doubleValue];
    long4 = [[[self.boundingRectsArr objectAtIndex:i] valueForKey:@"yLB"] doubleValue];

            CLLocationCoordinate2D rect[5];
            rect[0] = CLLocationCoordinate2DMake(lat1, long1);
    rect[1] = CLLocationCoordinate2DMake(lat2, long2);
    rect[2] = CLLocationCoordinate2DMake(lat3, long3);
    rect[3] = CLLocationCoordinate2DMake(lat4, long4);
            rect[4] = CLLocationCoordinate2DMake(lat1, long1);

    MKPolygon* polyCorridor = [MKPolygon polygonWithCoordinates:rect count:5];
    polyCorridor.title = @"Colorado";
    [self.map addOverlay:polyCorridor];
}

Thanks in Advance. Welcome to your answers.
Regards, Sagar P.

A: So, to be fast:

*

*Draw corrigor: draw second thick line.

*Highlight objects in corridor: calculate them without a polygon union, but with distance-to-route approach.

You could draw two lines in your overlay implementation, one, thin, for route, and one for a corridor - thiiick and semi-transparent, you could try to calculate point to km ratio using data MKMapView provides and calculate the thick line width. And for the objects on map you want to highlight - you could use different approaches, there are number of algos for finding points near curve or a straight line. You even could be rather straightforward: split the route into straight lines and check the distance of all the objects - that would be very slow, but it will work (sure you'll need to google for those complex algos for that).

A: Simple, first convert the MKMapRects to MKPolygons, then create the union of all the MKPolygons using this library:
https://github.com/SunGard-Labs/MKPolygon-GPC unfortunately its not free.


text:
Q: Comando remove() en listas de python estoy aprendiendo python, y tengo que hacer un programa donde pide al usuario escribir 5 elementos de una lista, y posteriormente mostrarlos. Así también preguntar si se desea eliminar o agregar un elemento a la lista. Todo mi código corre bien, solamente cuando se quiere eliminar un elemento, y se ingresa el nombre de, me dice que hay un error, y que el elemento x de remove no existe.
Si alguien puede ayudarme pls, no sé que estoy haciendo mal
elementos: list[str] = [input('Escriba 5 elementos cualesquiera: ')]
print(elementos)

elemento = (input('¿Desea agregar o eliminar algun elemento de dicha lista?: '))
if elemento == "agregar":
    elementos.append(input("Por favor agregue otro elemento: "))
    print(elementos)

elif elemento == "eliminar":
    elementos.remove(input("Por favor escriba el elemento que quiera eliminar: "))
    print(elementos)

elif elemento == "ninguno":
    print("Gracias por participar, vuelva pronto. Hasta luego.")

A: Buen día,
En tu código, por el momento al solicitar los 5 elementos los estas guardando como un solo string, por ejemplo, si ingresas 1 2 3 4 5 al imprimir los elementos te va a dar
['1 2 3 4 5']

Es importante ver que todos los elementos están en un único string y por lo tanto al eliminar, si deseas hacer por ejemplo remove(2) te va a mandar error
Para corregirlo puedes utilizar los métodos map() y split() para que la entrada se divida en diferentes índices en tu lista elementos
elementos = input('Escriba 5 elementos cualesquiera: ').split()

Ejemplo completo
elementos = input('Escriba 5 elementos cualesquiera: ').split()

elemento = (input('¿Desea agregar o eliminar algun elemento de dicha lista?: '))
if elemento == "agregar":
    elementos.append(input("Por favor agregue otro elemento: "))
    print(elementos)

elif elemento == "eliminar":
    elementos.remove(input("Por favor escriba el elemento que quiera eliminar: "))
    print(elementos)

elif elemento == "ninguno":
    print("Gracias por participar, vuelva pronto. Hasta luego.")

Ejemplo de ejecución (Nota como ahora al imprimirse elementos cada valor es un índice diferente de la lista
Escriba 5 elementos cualesquiera:  1 2 3 4 5
['1', '2', '3', '4', '5']
¿Desea agregar o eliminar algun elemento de dicha lista?:  eliminar
Por favor escriba el elemento que quiera eliminar:  3
['1', '2', '4', '5']


text:
Q: Java FX 8, trouble setting the value of text field I'm trying to populate the value of a text field in Java FX.
I have the Main Class,the controller and the fxml.I have bind the fxml file with controller and the appropriate field in it. When i try to set its value, it fails.
Main.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Main extends Application {

    private Stage primaryStage;
    private FlowPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        try {

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("test.fxml"));
            rootLayout = (FlowPane) loader.load();
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

testController.java
package application;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public class testController {

    @FXML
    private TextField t1;

    public testController() {

        System.out.println("hi");
        t1 = new TextField("j");
        t1.setText("hi");

    }

}

FXML file:
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.FlowPane?>

<FlowPane prefHeight="200.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.testController">
   <children>
      <TextField fx:id="t1" />
   </children>
</FlowPane>

A: You are doing it in the wrong place! If you need to play around with your controls just before your fxml is loaded, you need to do it in the initialize(). For this your controller should implement the Initializable
So your controller becomes :
public class testController implements Initializable{

    @FXML
    private TextField t1;

    public void initialize() {

        System.out.println("hi");

        //You should not re-initialize your textfield
        //t1 = new TextField("j");

        t1.setText("hi");

    }
}


text:
Q: Querying more than 1 table in a single query via JOIN I cannot quiet get using the JOIN clause around my head, even after I have ready multiple posts on the topic.
Here is my problem:
At the moment I have 2 tables.
Users Table:
ID | Username | Password
1  |   Micky  |   123
2  |   Mouse  |   145

Questions Table:
Question ID| Question_Title   | Question      | Rating | Category ID | User ID |
    1      | Meaning of Life? | Same as Title |  100   |      2      |    1    |
    2      | Foo is love?     | Same as Above |   95   |      4      |    2    |

Now I simply want to run a query which will find a match in the title and the find out which user ID corresponds to that question and then get the name of the user, as well as the Question Title, Question and Rating then print them out.
So far I have:
"SELECT Question_Title, Question, Rating FROM Questions WHERE Question_Title LIKE  '%$Term%'";

This works as in it will get me the Question Title, Question and Rating from the table wherever it finds a match but how would I use JOIN so that it will also get me the Username from the Users table?
Also this is just early implementation I will in the future have a lot more tables that will require similar query so I need to understand how this works.
P.S: I know their are plenty of examples like this but I had trouble understanding them so if one of you kind souls could break it down and explain I would be grateful.

A: Select a.* from a join b on a.id=b.a_id join c on c.b_id = b.id

in your case something like this:
SELECT Question_Title, Question, Rating,user.* FROM Questions join User on user_id=id WHERE Question_Title LIKE  '%$Term%'";

A: Try this
 SELECT
    u.username
    q.Question_Title,
    q.Question,
    q.Rating
    FROM Questions q
    join Users u on u.id = q.userid
    WHERE q.Question_Title LIKE  '%$Term%'";


text:
Q: What are the benefits of Mercurial or git over svn for branching/merging? I've heard for instance that merging branches with git or mercurial is easier than with svn.
Reading last Joel on software blog entry, I didn't get it exactly why. Could you provide a concrete example where merging with git/mercurial lead to less merge conflicts compared to svn please?

A: Check HGINIT out. It's an article/tutorial by Joel Spolsky (not his latest blog entry) on the topic. You might find the Subversion Re-Education part specially interesting.

A: One simple example is git can automatically convert a merge into a "fast forward". For example, let's say I have a branch that looks like this:
Master:
A ---> B ---> C
And I create a feature branch based on Master with new commits D and E.
Feature:
A --- > B ---> C
                \
                 D ---> E

In svn, when you merge the feature branch back into master, you must create an entirely new commit that applies the changes of D and E on Master. So, it looks like:
Master:
    A ---> B ---> C -----------------> F
Feature:           \                  /
                    ---> D ---> E -->

In git we have a choice of how to incorporate the branch feature into master. If we do a
git rebase feature

git will automatically recognize that this is a trivial merge and perform a fast-forward merge, which will add the new commits to the master branch. The result of the rebase is:
Master:
A ---> B ---> C ---> D ---> E

Both the head of Master and Feature point at commit E (in other words, they look exactly the same). A fast-forward merge is similar to what happens when you do an update in svn.
Additionally, you have the option of forcing git to create a merge commit. If instead we do:
git merge feature

git will create a merge commit. The result of the merge is:
Master:
    A ---> B ---> C -----------------> F
Feature:           \                  /
                    ---> D ---> E -->

Commit F is the combination of D and E.

A: Subversion conviniently implements only the single concept - fearure branches. This means one branch is always a parent and the other is feature. Feature can pull the updates from parent over time (merge), but parent can pull feature's changes only once (merge --reintegrate) and then the child should be closed. It is sufficient in many cases but not always. Not all branches are feature branches. I've got a couple of examples.

*

*First. A good example is a release branch. Suppose, you're preparing a release based on a thoroughly tested trunk revision. You make a release branch from the desired trunk revision. Now you're not affected by any subsequent trunk modifications. But you may want to commit hotfixes to the release branch and you may want to backport those to trunk without closing the release branch. This cannot be implemented with svn's feature branches. With svn you will have to wait until your release branch is no longer needed and then reintegrate it. Or to backport the hotfixes by hand.

*Second. Per-team or per-developer branches. Don't have a ready example of when they're really useful, but you won't like them in svn for sure. It'll be painful to synchronize such branches.


text:
Q: Leaflet: style using Promise Hello i was working for a long time on a tiny weather website using leaflet.
The site show perfectly the Region, the departement and the city with their weather data from an API.
To access into the weather data, you click on a region then you select one of the department of the region than it show marker with data on it.
I want to add one last feature before i move on:
it's coloring the region or the department according to their global temperature.
The region have a color in their layer according of the global temperature of all his department.
and the department have a color in their layer according of the temperature of all his city.
The problem is the whatever temperature it is from the departement or the region, it's inside a promise.
Here is the code:
function getColor(temp)
        {
            return temp > 50 ? '#8c1500' :
                temp > 40 && temp < 50  ? '#bf1d00' :
                temp > 30 && temp < 40 ? '#ff2600' :
                temp > 20 && temp < 30 ? '#ff5500' :
                temp > 10 && temp < 20 ? '#ffe100' :
                temp > 0 && temp < 10  ? '#0088ff' :
                temp < 0 ? '#0011ff' :
                '#ffffff';
        }

        function style(feature) // met en place la style
        {
            feature.temperature_global.then(temperature => {
                return {
                    fillColor : getColor(temperature),
                    weight: 2,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                };
            });
        }

and here
return new Promise((resolve,reject) =>{
            geojson = L.geoJSON(layer,{
                style: style,
                onEachFeature: onEachFeature
            }).addTo(this.leaflet_map);

            resolve(geojson);
        });

it's in a method of a class put_geojson_map(geojson,layer,tab_region) put witch is called in the main by this fonction:
async display_map()
    {
        let geojson;
        let tab_region = this.Tableau_Region;

        if (this.Tableau_Region.length != 1) // si il y a plus qu'une Region dans la carte
        {
            for (region of this.Tableau_Region)
            {
                let geojson_Region = await region.get_Region_Shape("region");
                let geojson_Departement_Region = await region.get_Region_Shape("departements");
                region.set_geojson_Region(geojson_Region);
                region.set_geojson_Departement_Region(geojson_Departement_Region);
                region.créer_Attribut_Classe_Geojson();
                geojson = this.put_geojson_map(geojson,geojson_Region,tab_region); // on ajoute les zones des regions de paca dans la map grâce au GeoJSON que on récupére dans un fichier.
                region.get_tableau_Historique_Layer_Region().push(geojson_Region);
            }

        }
        else // si il y a qu'une seule Region
        {
            let geojson_Region = await this.Tableau_Region[0].get_Region_Shape("region");
            let geojson_Departement = await this.Tableau_Region[0].get_Region_Shape("departements");
            this.Tableau_Region[0].set_geojson_Region(geojson_Region);
            this.Tableau_Region[0].set_geojson_Departement_Region(geojson_Departement);
            this.Tableau_Region[0].créer_Attribut_Classe_Geojson();
            geojson = this.put_geojson_map(geojson,geojson_Region,tab_region);
            console.log(geojson);
            this.Tableau_Region[0].get_tableau_Historique_Layer_Region().push(geojson_Region);
        }
    }

Not the full code but it's the part that affect the style fonction for coloring the layer in the map.
Here feature.temperature_global is in every feature part of the layer and it's a promise.
how can i color the layer using the promise, i know i have to transform every part into a promise but it will bring forward the problem again and again.
How can i do it?
thanks in advance.


text:
Q: CloudFormation deploy Method already exists for this resource I have a CloudFormation template that creates an APIGateway, but when I deploy again to add APIGateway methods (running update stack) I get:
Method already exists for this resource (Service: AmazonApiGateway; Status Code: 409;
Error Code: ConflictException; Request ID: 7058deed-14e1-46bc-863d-efba23cd668b; Proxy: null)

I attempted to add an update/delete policy to all resources but that doesn't seem to have worked:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain

I have a hunch it may be caused by not specifying the resources correctly, do I have something wrong with my resource paths? Are both resources being created at the root resource or something?
My End Goal
To declare two separate resources (with seperate URLS) eg
https://xxx/post-note
https://xxx/deleteNote
that are both tied to lambda functions
My template:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
# above two lines necessary to convert SAM template to CloudFormation template
Description: Resource definitions for my site
Globals: # any parameters you want available to all your resources
  Api:
    Cors:
      AllowMethods: "'OPTIONS,POST,GET'"
      AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
      AllowOrigin: "'*'"

  Function:
    Runtime: nodejs14.x # language used at runtime
    Timeout: 35 # timeout seconds for a given lambda function execution
    Environment:
      Variables: # these will be important later
        DYNAMO_TABLE: !Ref DynamoNotesTable
        DB_ENDPOINT: http://dynamodb.us-east-1.amazonaws.com
        REGION_NAME: us-east-1

Resources:
  # #############################################################################
  # # BACK END LAMBDAS
  # #############################################################################
  postNote:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::Serverless::Function
    Properties:
      Handler: backend/dynamo/postNote.postNote
      CodeUri: s3://backend/xxx
      Policies:
        - AmazonDynamoDBFullAccess

  deleteNote:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::Serverless::Function
    Properties:
      Handler: backend/dynamo/deleteNote.deleteNote
      CodeUri: s3://backend/xxx
      Policies:
        - AmazonDynamoDBFullAccess

  #############################################################################
  # api-gateway (with cognito auth)
  # https://bl.ocks.org/magnetikonline/c314952045eee8e8375b82bc7ec68e88
  #############################################################################
  apiGateway:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Description: API Gateway
      EndpointConfiguration:
        Types:
          - REGIONAL
      Name: my-api

  postNoteGatewayMethod:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt postNote.Arn
      ResourceId: !GetAtt apiGateway.RootResourceId
      RestApiId: !Ref apiGateway

  deleteNoteGatewayMethod:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt deleteNote.Arn
      ResourceId: !GetAtt apiGateway.RootResourceId
      RestApiId: !Ref apiGateway

  apiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    DependsOn:
      - postNoteGatewayMethod
      - deleteNoteGatewayMethod
    Properties:
      RestApiId: !Ref apiGateway
      StageName: Prod

  lambdaApiGatewayInvoke:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !GetAtt postNote.Arn
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/Prod/POST/PATH_PART

A: Both cloudformation resources AWS::ApiGateway::Method pointing to same api gateway resource with same method POST.
We have two options
Option 1: Change Method Name for one of the methods.
  deleteNoteGatewayMethod:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST   <--- should be DELETE
      AuthorizationType: "NONE"

Option 2: have a different root resource for each methods. so, if we need two POST endpoints /postNote and /deleteNote, we must have two separate resources from the root path and use these resources for the lambdas.
Ex:
/postNote with Parent as root resource.
  noteResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt apiGateway.RootResourceId
      PathPart: "postNote"
      RestApiId: !Ref apiGateway

and method ResourceId pointing to !Ref noteResource
  postNoteGatewayMethod:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::ApiGateway::Method
    DependsOn:
      - noteResource
    Properties:
      HttpMethod: POST
      AuthorizationType: NONE
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt postNote.Arn
      ResourceId: !Ref noteResource
      RestApiId: !Ref apiGateway

Similarly we need to add delete resource.
  deleteResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt apiGateway.RootResourceId
      PathPart: "deleteNote"
      RestApiId: !Ref apiGateway

  deleteNoteGatewayMethod:
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Type: AWS::ApiGateway::Method
    DependsOn:
      - deleteResource
    Properties:
      HttpMethod: POST
      AuthorizationType: "NONE"
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri: !Sub
          - arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${lambdaArn}/invocations
          - lambdaArn: !GetAtt deleteNote.Arn
      ResourceId: !Ref deleteResource
      RestApiId: !Ref apiGateway


text:
Q: Create dataset by filtering 4 hour intervals from datetime I wish to create a dataset that only has the data from every observation 4 hours apart.
Currently I possess a dataset that has hourly observations.
Dividing does not work because the samples would not have 4 hour intervals between them.
IndividId   DateTimeLMT          isDaylight    YEAR  month   day  hour
  <chr>     <dttm>                  <chr>      <dbl> <dbl> <dbl> <dbl>
1 M_15_03   2017-01-13 15:00:42     True        2017     1    13    15
2 M_15_03   2017-01-13 16:00:14     False       2017     1    13    16
3 M_15_03   2017-01-13 17:00:09     False       2017     1    13    17
4 M_15_03   2017-01-13 18:00:42     False       2017     1    13    18
5 M_15_03   2017-01-13 19:00:14     False       2017     1    13    19
6 M_15_03   2017-01-13 20:00:45     False       2017     1    13    20

The result I would be looking for is a formula that would create something similar to this:
IndividId   DateTimeLMT          isDaylight    YEAR  month   day  hour
  <chr>     <dttm>                  <chr>      <dbl> <dbl> <dbl> <dbl>
1 M_15_03   2017-01-13 15:00:42     True        2017     1    13    15
2 M_15_03   2017-01-13 19:00:14     False       2017     1    13    19
3 M_15_03   2017-01-13 23:00:09     False       2017     1    13    23
4 M_15_03   2017-01-14 03:00:42     False       2017     1    14    03
5 M_15_03   2017-01-14 07:00:14     False       2017     1    14    07
6 M_15_03   2017-01-14 11:00:45     True        2017     1    14    11

A: You can use lubridate::floor_date. floor_date set to 4 hours will round at 16 - 20 - 24 hours, so you can use lead to make to 15 - 19, and fill with tidyr::fill.
library(lubridate)
library(tidyr)
library(dplyr)

data %>%
  mutate(fl = floor_date(lead(DateTimeLMT), unit = "4 hours")) %>%
  fill(fl) %>%
  group_by(IndividId, fl) %>%
  summarise(across(c(DateTimeLMT, YEAR:hour), first),
            isDaylight = any(isDaylight == "True"))

# A tibble: 2 x 8
# Groups:   IndividId [1]
  IndividId fl                  DateTimeLMT          YEAR month   day  hour isDaylight
  <chr>     <dttm>              <dttm>              <int> <int> <int> <int> <lgl>
1 M_15_03   2017-01-13 16:00:00 2017-01-13 15:00:42  2017     1    13    15 TRUE
2 M_15_03   2017-01-13 20:00:00 2017-01-13 19:00:14  2017     1    13    19 FALSE

data
data <- read.table(header = T, text = "IndividId   DateTimeLMT          isDaylight    YEAR  month   day  hour
1 M_15_03   2017-01-13-15:00:42     True        2017     1    13    15
2 M_15_03   2017-01-13-16:00:14     False       2017     1    13    16
3 M_15_03   2017-01-13-17:00:09     False       2017     1    13    17
4 M_15_03   2017-01-13-18:00:42     False       2017     1    13    18
5 M_15_03   2017-01-13-19:00:14     False       2017     1    13    19
6 M_15_03   2017-01-13-20:00:45     False       2017     1    13    20 ")


text:
Q: How to generate a color based on an alphanumeric string using Ruby? I want something like "hey there" to turn into, for example, #316583.
I want a string of any length to be "boiled down" so to speak to a hex color. I'm at loss even where to start.
I was thinking, an MD5 hash of every string is different - but how to turn that hash into a hex color number?

A: You can mod the md5 value by 2^24 and print that result in hex with a # sign before it.
Here's a bad way without the MD5, that gives very low values on short strings, but shows the idea:
sprintf("#%06x", ("asdf".sum % (256*256*256)))

output:
ruby-1.9.2-p290 :032 > sprintf("#%06x", ("asdf".sum % (256*256*256)))
 => "#00019e"

Replace "asdf".each_byte.inject(:+) with the MD5 value and you should be good!

A: You can just take a few first digits:
require 'digest/md5'
color = Digest::MD5.hexdigest('My text')[0..5]


text:
Q: IE8 inner html and tag object properties I have some kind of trouble in my code in IE8.

So I put some property to object of DOM element 'li' and fetching whole html code. In normal browsers all what I will get is just

.

BUT, this is IE...
So now I'm getting

and it's clearly disappointing me. What I can do, how should I save properties in DOM objects to do not crash DOM HTML code? I tried jQuery prop() but it didn't work out.

A: This:
$( 'li' , $container ).data( 'my_plugin_inited', true );

Read here: http://api.jquery.com/data/

Btw you could do this:
$( 'li' , $container )[0].dataset.my_plugin_inited = true;

but dataset is not implemented in IE.
Read here: https://developer.mozilla.org/en/DOM/element.dataset


text:
Q: How to get all fridays within date range by carbon I'm using this function to get all Fridays between two dates:
public function getFridaysInRange($dateFromString, $dateToString)
{
    $dateFrom = new \DateTime($dateFromString);
    $dateTo = new \DateTime($dateToString);
    $dates = [];

    if ($dateFrom > $dateTo) {
        return $dates;
    }

    if (1 != $dateFrom->format('N')) {
        $dateFrom->modify('next friday');
    }

    while ($dateFrom <= $dateTo) {
        $dates[] = $dateFrom->format('Y-m-d');
        $dateFrom->modify('+1 week');
    }

    return $dates;
}

$this->getFridaysInRange('2017-01-01','2017-01-30');

result :
array:4 [▼
  0 => "2017-01-06"
  1 => "2017-01-13"
  2 => "2017-01-20"
  3 => "2017-01-27"
]

Is there any function in carbon like above?

A: Slight modification to Alexey Mezenin's answer to include the current day if it is a Friday.
$fridays = [];
$startDate = Carbon::parse($fromDate)->modify('this friday'); // Get the first friday. If $fromDate is a friday, it will include $fromDate as a friday
$endDate = Carbon::parse($toDate);

for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
    $fridays[] = $date->format('Y-m-d');
}

A: You can use all the power of Carbon like this:
$fridays = [];
$startDate = Carbon::parse($fromDate)->next(Carbon::FRIDAY); // Get the first friday.
$endDate = Carbon::parse($toDate);

for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
    $fridays[] = $date->format('Y-m-d');
}


text:
Q: Displaying all the columns from two different tables How to display all the columns of two different tables as ONE ?
I have two tables, movies and movie_actors in MovieDB. The id of the movies is primary key and id of the movie_actor is foreign key, and movies_actor.id is referenced to movies.id
   TABLE MOVIES
   id/title/director/genre/year_of_release

   TABLE MOVIE_ACTOR
   id/title/actor/age

I used Union, but its not working, because union is asking for same number of attributes. but here the first table has 4 columns and the second has only 3.
I would like to display as in one table
   id/title/director/genre/year_of_release/actor/age

any ideas?

A: You will want to use a join on the tables.  The join will be between the two fields that are primary/foreign keys to each other which you stated was the id in the movie table and the id in the movie_actor table:
select m.id,
  a.title,
  m.director,
  m.genre,
  m.year_of_release,
  a.actor,
  a.age
from movies m
inner join movie_actor a
  on m.id = a.id

If you are not familiar with join syntax than here is great visual explanation of joins.
An INNER JOIN will return the set of records that match in both tables. If you had records in the movie table that did not have matching records in the move_actor table, then you would want to use a LEFT JOIN. This would return all movies even if it did not have records in the movie_actor table:
select m.id,
  a.title,
  m.director,
  m.genre,
  m.year_of_release,
  a.actor,
  a.age
from movies m
left join movie_actor a
  on m.id = a.id

See SQL Fiddle with Demo of both queries.

A: You can join these tables using the following query.
SELECT MOVIES.id, title, director, genre, year_of_release, actor, age
    FROM MOVIES INNER JOIN MOVIE_ACTOR ON (MOVIE.id = MOVIE_ACTOR.id)


text:
Q: How to switch from activity to fragment I want to move from an activity to the fragment using intent. I know the opposite, but I don't know that.
public class ResultActivity extends AppCompatActivity {
private void history() {
    Intent my = new Intent(ResultActivity.this, ThreeFragment.class);
    startActivity(my);
    finish();
}

A: You can use Activity with fragment (Fragment is part of Activity); Add/remove fragments into your manually using FragmentManager (fragmentManager.beginTransaction() ... .commit()).
If you need to open new activity with fragment
    Intent my = new Intent(ResultActivity.this, ActivityWithThreeFragment.class);
    startActivity(my);
    finish();

you can define fragment class in xml layout of ActivityWithThreeFragment (using <fragment> tag) or add fragment manually. See documentation


text:
Q: Renaming a dataframe dynamically based on output of pivot_table Im trying to Condense my data in a format so it would be more useful , Data Format:
Table1
Key       AttName     Rank
1          Color       1
1           type       2
1           kkk        3
2          Color       1
2           type       2

As seen in the above eg some keys have 2 atts while others have 3 so when i create the Pivot table and then try to label the column names it doesnt work, hpw could i change this, As is displayed above key 1 has 3 attribute Names and Key 2 has only 2 due to which the error occurs
Final data:
Table2
Family     Assortment Group       Key       Attribute Name      Attribute Value
a                ab                1            Color              Green
a1               ab                1            Color              Yellow
a2               ab                1            type               shirt
a6               ab                1            kkkk               f
a3               ab                2            Color              Red
a4               ab                2            Type               TShirt
a5               ab                2            Color              Yellow

Code
#For loop that loops over key values; key values defined as Zone AG

Finals=[]
Finals2=[]
Finals=pd.DataFrame(Finals)
Finals2=pd.DataFrame(Finals)
for group in Select.groupby('Key'):
    # group is a tuple where the first value is the Key and the second is the dataframe
    Final2=group[1]
    Family1=Family.merge(Final2, on='Key1', how='inner')
    result=Family1.pivot_table(index=['Family','Assortment Group','Key'], columns='Attribute Name', values='Attribute Value', aggfunc='first').reset_index()
    result.columns=['Family','Assortment Group','Key','Att1','Att2','Att3']
    Finals=Finals.append(result)

Traceback
ValueError: Length mismatch: Expected axis has 5 elements, new values have 6 elements

A: You can rename the columns with a list comprehension to generate the right amount of Att columns.
result.columns = ['Family','Assortment Group','Key']\
                 + [f'Att{i}' for i in range(1, result.shape[1]-2)]

EDIT: explanation, result.shape[1] gives the number of columns in result. let's say it is 5, then the first 3 are the 'Family','Assortment Group','Key'. So what you want is to create 2 more Att, and range(1, result.shape[1]-2) is in this case range(1, 3) and [f'Att{i}' for i in range(1, result.shape[1]-2)] will then iterate for i=1 and i=2 to create the list ['Att1', 'Att2']. add this list to the one with the 3 first columns name to get the right number of columns


text:
Q: How to keep wrapped text in SVG when loaded into QGIS? I have an SVG that contains a graph where the y-axis title is wrapped to two lines. The upper line is the parameter ("Parameter") and the lower line is the units ("(units)").
When I load the SVG into a template in QGIS, the y-axis title is unwrapped, so that the parameter and units are on one line. I would like the axis title to remain wrapped so that the y-axis is two lines.
In other words, the title looks like this:
In the SVG:

Parameter
(units)

When the SVG is loaded into a QGIS template:

Parameter (units)

The SVG is generated with python, where the y-axis title is set as follows:
fig.update_yaxes(title_text="Parameter <br> (units)",
                 titlefont=(dict(family="Arial", size =20)),
                 mirror=True,
                 showline=True,
                 linecolor='#000',
                 ticks='outside',
                 tickcolor='#000',
                 row=4, col=1,
                 showgrid=True,
                 gridwidth=1,
                 gridcolor='Gray')

Anyone have insight of what I may be doing wrong, or know how I can keep the text wrapped when it's loaded into QGIS?