text:
Q: adding wordpress to existing ZF web app - where to install? I have a ZF web app up and running. Now we are planning to add blog to our web app. I am considering using WP blog because of the super tight timeline to complete blogging system. Note: I am not looking to convert my ZF app into WP app.
There isn't much about on how to integrate ZF and wordpress on google, so before I install WP I would like to make sure that I am on the right path. So here this is what I have learned so far by looking at the bit and pieces of articles I found on internet.
My ZF directory structure looks like this: (This is just the crude structure)
trunk /
    module /
        app /
            (contains controller, view, model)
    public /
        css
        js
    vendor /
        ZF

1) Create a new directory inside ZP app (let's say www.domain.com/blog)
2) Upload and install WP under blog directory.
3) Add the following header to the all PHP pages.
<?php
/* This make the magic: */
define('WP_USE_THEMES', false);
require('path-to-the-file/wp-blog-header.php');

My question is where should I exactly create the blog folder and upload/install WP? Is it going to be under view folder? or in the public folder? Also, is there anything I need to include in root index file for routing?
This is my index.php files looks like which is located in the public folder
<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

function debug( $data ) {
    try {
        throw new Exception();
    } catch( Exception $e ) {
        $trace  = $e->getTrace();
        $desc = array_shift($trace);
        $info = $desc['file'].' on line '.$desc['line'].'';
        $infoS = basename($desc['file']).'('.$desc['line'].')';
    }
    $errTempId = 'e'.mt_rand(0,9999999999999);
    $onClick = "e=document.getElementById('".$errTempId."');if(e.style.display=='none'){e.style.display='';}else{e.style.display='none';}";
    echo '<acronym style="cursor:pointer;" title="'.$info.'" onClick="'.$onClick.'">'.$infoS.' debug:</acronym>';
    if( is_object($data) === true or is_array($data) === true ) {
        echo '
';
        print_r($data);
        echo '

';
    } else if( is_null($data) ) {
        echo 'NULL
';
    } else {
        echo $data.'
';
    }
    echo '';
}

function arrayMerge( $a, $b ) {
    foreach( $b as $k => $v ) {
        $a[$k] = $v;
    }
    return $a;
}

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

htaccess file (just in case I need to modify anything over here)
RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
# The following rule blocks botnets scripts
RewriteCond %{HTTP_USER_AGENT} libwww-perl.*
RewriteRule .* – [F,L]
# The following rule maps IP address with domain name
RewriteCond %{HTTP_HOST} ^***\.**\.***\.**
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

A: Usually the public/ dir is the only public accessible directory in a zend app and used as a document root of the domain.
So if you want your blog to be under domain.com/blog/ you have to put it to public/blog/
You dont have to modify any files of the zend app.


text:
Q: how to do ${bean.methodWithArg('${value}')} in el jsp I want to fetch all the subjects and topics related to Subject from DB just like :

*1- Java Basic // As Subject and topics below

*
*Variable

*Operators

*Java Statement

  2- PHP Basic // As Subject and topics below

*
*Variable

*Operators

*Statement

in code it is :
<jsp:useBean id="bean" class="com.super.db.dao.SuperBean" scope="page"></jsp:useBean>
<c:forEach items="${subjects}" var="subject">
    <li
       <c:catch>
        <c:choose>
             <c:when test="${subject.subjectId == param.subj_id}">

       </c:catch>><a href='/super-context/super-controller?action=view-content&subj_id=
            <c:out value="${subject.subjectId}"/>'>
            <c:out value="${subject.subjectName}" />

            <c:forEach items="${bean.topicList('${subject.subjectId}')}" var="topic">
                <li
                <c:catch>
                <c:choose>
                    <c:when test="${topic.topicId == param.topic_id}">
                    <c:out value=" class=\"selected\""/>
                    </c:when>
                </c:choose>
                </c:catch>><a href='/super-context/super-controller?action=view--content&topic_id=
                    <c:out value="${topic.topicId}"/>'>
                    <c:out value="${topic.topicName}" />

                </c:forEach>

</c:forEach>

I'm stuck in my code where I face scenario like :
${bean.methodWithArg('${value}')}

EDIT
bean.topicList(subjectId);

from above I want to get subjectId and use here :
public List<Topic> topicList(String subjectId) throws SQLException{
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List<Topic> topics = new ArrayList<>();

    try {
        connection = DatabaseManager.initConnection();
        statement = connection.prepareStatement("SELECT * FROM topic WHERE subj_id = " + subjectId + " ORDER BY position ASC LIMIT 0 , 30");// Here this ${bean.topicList('${subject.subjectId}')} subject ID is required.
       // System.out.println("ResultSet returned...");
        resultSet = statement.executeQuery();

        while (resultSet.next()) {
            Topic topic = new Topic();
            topic.setTopicId(resultSet.getString(Constant.TOPIC_COL_ID));
            topic.setSubjectId(resultSet.getString(Constant.TOPIC_SUBJECT_COL_NAME));
            topic.setTopicName(resultSet.getString(Constant.TOPIC_COL_NAME));
            topics.add(topic);
        }
    } finally {
        if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
        if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
    }

    return topics;
}

when I use :
${topicDAO.topicList('subject.subjectId')}

I get
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'subject.subjectId' in where clause'

I could figure that out how to get the above code work.
thanks in advance.

A: In case value is a known variable in expression language the current page (stored in page, request, session or application context), use it like this:
${bean.methodWithArg(value)}

If you're passing a concrete String "value", use it like this:
${bean.methodWithArg('value')}

By the way, the code above is supported by Expression Language, it is not JSTL.

Not related to your original problem but you're misusing PreparedStatement. You should not append the parameters in the query, instead mark the parameters in the statement as ? and then set the values for the parameters. Change the code to:
statement = connection.prepareStatement(
    "SELECT * FROM topic WHERE subj_id = ?"
    + " ORDER BY position ASC LIMIT 0 , 30");
statement.setString(1, subjectId);
resultSet = statement.executeQuery();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integration of $\int^{\pi/45}_0 \frac{x^2 \ln (1-x)}{1-x^3}\, dx$ How would you integrate:
$$I=\int^{\pi/45}_0 \frac{x^2 \ln (1-x)}{1-x^3} dx$$
My attempt:
$$du=\frac{x^2}{1-x^3}dx ⇒ u=\frac{-1}{3}\ln (1-x^3)$$
$$v= \ln (1-x) ⇒ dv=\frac{-1}{1-x}$$
$$I=\frac{-1}{3}\ln (1-x^3) \ln (1-x)-\int \frac{\ln (1-x^3)}{1-x}\,dx$$
$\ln (1-x^3)=\ln (1-x)+\ln (1+x+x^2)$
$$\int \frac{\ln (1-x^3)}{1-x}\,dx=\int \frac{\ln(1-x)}{1-x}\,dx+\int \frac{\ln (x^2+x+1)}{1-x}\,dx$$
$$I_1=\int \frac{\ln(1-x)}{1-x}\,dx=-\frac{1}{2} \ln^2 (1-x)$$
$$x^2+x+1=\left(x+\frac{1-i\sqrt3}{2}\right)\left(x+\frac{1+i\sqrt3}{2}\right)$$
$$\ln \left(x+\frac{1-i\sqrt3}{2}\right)= \ln (2x+1-i\sqrt 3)- \ln 2=\tan^{-1}-\frac{\sqrt3}{2x+1}-\ln 2$$
$$\ln \left(x+\frac{1+i\sqrt3}{2}\right)= \ln (2x-1+i\sqrt 3)- \ln 2=\tan^{-1}\frac{\sqrt3}{2x-1}-\ln 2$$
$$\int \frac{\ln (x^2+x+1)}{1-x} \,dx=\int \frac{\tan^{-1}-\frac{\sqrt3}{2x+1}}{1-x}\,dx+\int \frac{\tan^{-1}\frac{\sqrt3}{2x-1}}{1-x}\,dx+2 \ln2 \ln (1-x)$$
Can someone proceed?

A: Hint: A better method
Using the  partial fraction:
$$\frac{{{x}^{2}}}{1-{{x}^{3}}}=\frac{1}{3}\frac{1}{1-x}-\frac{1}{3}\frac{2x+1}{{{x}^{2}}+x+1}=\frac{1}{3}\frac{1}{1-x}-\frac{2}{3}\frac{1}{2x-i\sqrt{3}+1}-\frac{2}{3}\frac{1}{2x+i\sqrt{3}+1}$$
The integral becomes
$$\begin{align}
  & I=\frac{1}{3}\int{\frac{\ln \left( 1-x \right)}{1-x}dx--\frac{2}{3}\int{\frac{\ln \left( 1-x \right)}{2x-i\sqrt{3}+1}dx}-\frac{2}{3}\int{\frac{\ln \left( 1-x \right)}{2x+i\sqrt{3}+1}dx}} \\
 & \quad =-\frac{1}{6}{{\ln }^{2}}\left( 1-x \right)-\frac{2}{3}J-\frac{2}{3}K \\ \end{align}$$
Evaluating $J$ and $K$ are similar, for $J$  first set $u=1-x$, to get:
$$J=\int{\frac{\ln \left( u \right)}{2u-3+i\sqrt{3}}du}$$
Now use the formula:
$$\int{\frac{\ln \left( u \right)}{au+b}dx}=\frac{1}{a}\log \left( u \right)\log \left( \frac{au}{b}+1 \right)+\frac{1}{a}L{{i}_{2}}\left( -\frac{au}{b} \right)$$
where $L{{i}_{n}}$ is the poly-logarithm function.


text: Q: My system crashes when I try to enable mod_rewrite module in Wamp Server 2.4 My system crashes when I try to enable mod_rewrite module in Wamp Server 2.4. Its really frustrating..I reinstalled..then also same problem...I have also installed Visual C++ 2010 SP1 Redistributable Package x86. Then also same issue.


text:
Q: Unable to call Ion infinite scroll method present in angular controller from with ionic fancy select directive I am using Ionic multi select directive, I want to do pagination. So, I used the ion-infinte-scroll. I added the ion-infinte-scroll in fancy select directive. But, when I scroll down method present in controller is not getting called.
Added the below code in fancy select directive.
In fancy select directive.js (line no 115 and 116)
<ion-infinite-scroll immediate-check="false"
  on-infinite="scrollDown()" distance="5%"></ion-infinite-scroll>

In script.js
$scope.scrollDown = function(){
   console.log('function triggered');
}

I have created a plunker for this https://plnkr.co/edit/ZlhZOZVcDGuIxRyEtCfv?p=preview. Kindly, help me through.

A: I corrected some errors in your directive, for example this line was missing:
 modalScope.scrollMethod = scrollMethod;

and there was another error in retrieving the scrollMethod attribute:
scrollMethod = attrs.scrollMethod,

Besides in HTML the attribute must be scroll-method: camelCase on JS side, dash separator on HTML side.
Then the scrollMethod() function must be in the modal scope not in the controller, or you can do inherit modal scope from parent controller (but it is not the case of your modal service). Another possibility is to add the method to $rootScope.
Here is a plunker updated:
https://plnkr.co/edit/3CK1wUEQustmkEPoJBqG?p=preview


text:
Q: Invalid object name dbo.Table1 error in Entity Framework I have the following tables: StudentCourses is a mapping table of Student and Course

*

*Student (Id, ..)

*Course (Id, ..)

*StudentCourses (StudentId, CourseId)

Model classes:
public class Student {
      ....
      ....
      public virtual ICollection<Course> Courses { get; set; }

}

public class Course {
      ...
      ...
      public virtual ICollection<Student> Students { get; set; }
}

public class StudentCourse  {
      ...
      ...
      public virtual Student Student { get; set; }
}

Mappings are set as below:
public class StudentConfiguration
      : EntityTypeConfiguration<Student>
{
      public StudentConfiguration()
      {
         HasKey(x => x.Id);

         //Many to many
         HasMany(s => s.Course)
            .WithMany(t => t.Students)
            .Map(x =>
            {
               x.ToTable("StudentCourses");
               x.MapLeftKey("StudentId");
               x.MapRightKey("CourseId");
            }
            );
        }
}

public class StudentCourseConfiguration
      : EntityTypeConfiguration<StudentCourse>
{
      public StudentCourseConfiguration()
      {
         HasKey(x => new {x.StudentId, x.CourseId});
      }
}

I am trying to get a collection of Courses with with the number of students enrolled for each course.
public ActionResult GetAllCourseInfo()
{
         var courses = _context.Course.ToList();
         var courseInfo = new List<CourseInfo>();

         foreach (var course in courses )
         {
            var studentCount = _context.StudentCourse.Count(x => x.Student.CourseName.Equals(course.CourseName));
            courseInfo.Add(new CourseInfo{ CourseName = course.CourseName, Count = studentCount });
         }

         return Json(courseInfo, JsonRequestBehavior.AllowGet);
}

I am getting an exception

Invalid object name dbo.StudentCourses1

*

*How do I resolve this?

*Is my EntityTypeConfiguration correct?


text:
Q: Route-based code splitting causes css duplicate Using route-based code splitting causes css duplicate in chunks.
Steps to reproduce:

*

*Create simple app with create-react-app

*Use react-router-dom for client side routing

*Add one common component with local css.

*Add 2 pages, using the common component with style overwriting

*Run build command

*Check static folder

// /components/CommonPageHeader/CommonPageHeader.module.scss
.header {
  color: black;
}

// /components/CommonPageHeader/CommonPageHeader.tsx
import styles from "./CommonPageHeader.module.scss";
import { ReactNode } from "react";

export const CommonPageHeader = (props: {
  className: string;
  children: ReactNode;`your text`
}) => {
  const { className = "", children } = props;

  return <h1 className={`${styles.header} ${className}`}>{children}
;
};

// /pages/Home/Home.module.scss
.greenHeader {
  color: green;
}

// /pages/Home/Home.tsx
import React from "react";
import { Link } from "react-router-dom";
import { CommonPageHeader } from "../../components/CommonPageHeader/CommonPageHeader";
import styles from "./Home.module.scss";

const Home = () => (
  <>
    <CommonPageHeader className={styles.greenHeader}>
      I'm a green header
    </CommonPageHeader>
    <Link to={"some-page"}>Some page</Link>
  </>
);
export default Home;

// /pages/SomePage/SomePage.module.scss
.redHeader {
  color: red;
}

// /pages/SomePage/SomePage.tsx
import React from "react";
import { Link } from "react-router-dom";
import { CommonPageHeader } from "../../components/CommonPageHeader/CommonPageHeader";
import styles from "./SomePage.module.scss";

const SomePage = () => {
  return (
    <>
      <CommonPageHeader className={styles.redHeader}>
        I'm a red header
      </CommonPageHeader>
      <Link to={"/"}>Home</Link>
    </>
  );
};
export default SomePage;

// index.tsx

import React, { Suspense } from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";

const Home = React.lazy(() => import("./pages/Home/Home"));
const SomePage = React.lazy(() => import("./pages/SomePage/SomePage"));

const router = createBrowserRouter([
  {
    path: "/",
    element: (
      <Suspense>
        <Home />
      </Suspense>
    ),
  },
  {
    path: "/some-page",
    element: (
      <Suspense>
        <SomePage />
      </Suspense>
    ),
  },
]);

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

You get css chunks with duplicates and unexpected styles overwrites in production:
// /build/static/css/499.408c3ff0.chunk.css
.CommonPageHeader_header__eTauC {
    color: #000
}

.Home_greenHeader__YwF4H {
    color: green
}

// /build/static/css/136.855973ab.chunk.css
.CommonPageHeader_header__eTauC {
    color: #000
}

.SomePage_redHeader__a-I8c {
    color: red
}

Demo page

*

*Click to some page link

*Go back to home page

Repo
Is there way to prevent it?


text:
Q: How to get the remaining string after removing a substring Suppose, I have the following string:
string temp = "some string contains text which contains demo";
string result = RemainingString(temp, 12, 8); // string, startIndex, length

The result string I need should look as follows:
some string text which contains demo

Note, that the word contains is removed from first place only.
Update: I personally want to achieve this using regular expression explicitly.

A: Try the String.Remove method, it does exactly what you ask.

A: String.Remove(Int32, Int32) will do the job:
string temp = "some string contains text which contains demo";
string result = temp.Remove(12,8);

A: Use string.Remove:
public string RemainingString(string orig, int startIndex, int length)
{
    return orig.Remove(startIndex, length);
}

Alternatively - concatenate two substrings - up to the index, and after the index+length (.NET 1.0/1.1):
public string RemainingString(string orig, int startIndex, int length)
{
    return orig.Substring(0, startIndex) +
           orig.Substring(startIndex + length);
}

A: Here's a solution using regular expressions:
public string RemainingString(string str, int start, int length)
{
    return Regex.Replace(str, "^(.{" + start+ "})(?:.{" + length + "})(.*)$", "$1$2");
}

A:    $line_string = 'this is all the sting from which i would want to treat';

    $key_string ='from which';

    //use strpos

    $position2 = strpos($line_string,$key);

   if($position2){

      $found = substr($line_string,$position2,strlen($key_string));

      //echo $found;

    }

    //the substr now begins at character position $position2

    //and ends at position2 + strlen($key_string);

     //so
     $remainderpos = position2 + strlen($key_string);

     $str_remaining = substr($line_string,$remainderpos);

     echo $str_remaining;

as simple as it can get. code from the scratch.


text:
Q: Integer corrupt in GLSL I have this strange behavior in my rendering process. I'm passing an 32-bit unsigned integer as an attribute to my shader. The vertex-shader forwards this attribute as a flat uint to the fragmentshader.
In the fragment shader I do a comparison. In my case send in 1u and I compare with 1u. This doesn't generate true. Instead my value compared to
0x3F800000

generates true.
So, somehow my initial 32-bit value:
0000 0000 0000 0000 0000 0000 0000 0001

Has become:
0011 1111 1000 0000 0000 0000 0000 0000

All I'm doing is this:
Vertex:
layout(location = 3) in uint in_index
flat out uint v_index;
v_index = in_index;

Fragment:
if (v_index == 0x3F800000u){discard;}

And all fragments are discarded. I'm using core 330.
And by the way, I've used floats and shorts and they all work fine.

A: @Andon M. Coleman solved it for me!
use glVertexAttribIPointer (...) instead of glVertexAttribPointer (...).


text:
Q: Who created the dome and why? I'm looking for spoilers for the Stephen King novel Under the Dome and the TV show, if available.
Who created the dome and why?

A: In the TV series, the dome exists to protect the egg that converts other species into The Kinship, an alien species, and to trap suitable subjects within the space to be converted.

The Kinship is an alien species that can take over any living person and control its actions. Another species had sought to take over The Kinship's world, during an event known as "The Great Destruction". To survive, The Kinship abandoned their own world, hoping to live on another life-supporting planet. They used an egg inside a meteor to transport themselves across the galaxy, hoping the meteor would crash on another inhabited planet.
In 1980, The Kinship's meteor crashed in the center of Chester's Mill. Teenagers Melanie, Pauline, Sam and Lyle found the meteor in the middle of the woods. As they approached it, four hand prints glowed, one on each side of the meteor. Each of them placed his or her hand on the meteor, which triggered it to open, revealing a glowing pink egg. Attracted by the egg, Melanie picked it up. However, Lyle pushed her into the meteor, and she died.
Had she stayed alive longer, Melanie would have been infected by The Kinship, and a dome (a device that traps and protects life forms inside it) would have lowered over the town, while a mini-dome descended over the egg (an energy source), and Melanie and her friends, as the first life forms to have come into contact with the egg, would have been pulled underground, into a large cave which forms instantly. There, they would have been able to view the town from within a large "Queen-size" cocoon. But since she died, it didn't happen then. Panicking, Melanie's friends buried her and the alien egg, swearing never to talk about the incident again.

The events of the series were kicked off when another intact egg was found and activated, this time without any of the activators immediately being killed.

Now, in 2013, two archaeologists, Christine and Eva, search for an intact egg, which they believe to be located in Chester's Mill. They work for a large energy company called "Aktaion," which, in the past, studied other eggs that crashed to earth. The other eggs had broken when they'd crashed, so, when the eggs were touched, domes did not come down.
Christine and Eva find the intact egg. As Christine holds it, the infection process begins, and The Kinship beings transfer into her, as she screams in pain. Once the process is complete, a large pink explosion occurs, and the dome lowers around them, a mini-dome descending over the egg. Christine and Eva get sucked into a large cave, which appears below them, and get cocooned.

A:
In the book, Aliens.  Never very much explained, but, basically, some kind of Leather-headed Alien Children, playing with the Earth the way human kids might play with an Anthill.  They are seen by several of the protagonists when they touch the artifact that is generating the dome.

To quote from the Stephen King Wiki:

They not only conclude that the device was put in place by extraterrestrial "leatherheads" (so named for their appearance), but that specifically they are juveniles who have set up the Dome as a cruel form of entertainment, a sort of ant farm used to capture sentient beings and allow their captors to view everything that happens inside.

I haven't seen the TV series, so I can't speak to that :)

A: The TV Series and the novel have already diverged quite significantly, and there's every indication that it will keep doing so.
In the novels, the dome's origin is eventually exposed as:

 Alien kids playing with Earth, the same way human children might play with an ant farm or hamster cage.

In the TV show, it's becoming clear that the dome has a far more significant purpose, but we have no idea where it came from or who (if anyone) is "operating" it. Given that it's Stephen King, it wouldn't be surprising if aliens were involved, but I highly doubt it will be as straightforward (and largely anti-climactic) as the book.


text:
Q: Como verificar se um arquivo está corrompido em c#? Como verificar se um arquivo está corrompido em c#?
Ex: Possuo um arquivo "xpto.txt" em um diretório e preciso verificar se esse arquivo não está corrompido.

A: Uma opção é conferindo o CRC. Há uma biblioteca chamada DamienGKit que implementa o Crc32.
Exemplo de uso:
Crc32 crc32 = new Crc32();

String hash = String.Empty;

using (FileStream fs = File.Open("c:\\meuarquivo.txt", FileMode.Open))
  foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();

Console.WriteLine("CRC-32 é {0}", hash);

Tirei daqui. Este método só funciona se você tiver o CRC de um arquivo íntegro. Se forem diferentes (o CRC do original e da cópia) para uma mesma data de modificação, o arquivo está corrompido.
Outra forma é tentando abrir o arquivo como somente-leitura e verificar se essa abertura levanta alguma exceção, mas isso não necessariamente verifica se o arquivo está corrompido ou não: verifica apenas se ele pode ser lido ou não, que é outra coisa:
var fi = new System.IO.FileInfo(@"C:\meuarquivo.txt");

try
{
  if (fi.IsReadOnly)
  {
    // Se entrar aqui, o arquivo está ok.
  }
}
catch (Exception ex)
{
  Response.Write("Problema ao ler arquivo.");
}

Este último tirei daqui.


text:
Q: Sublime Text 2 Mac Markdown Preview Keybinding I am having some difficulty setting a simple keybinding in Sublime Text 2, which I have only been using for a few hours.
I managed to install Markdown Preview and learned how to invoke it on a simple markdown text file.  My next desire was to set a simple key binding to bring up the browser preview without having to go through the Command Palette, which I find a bit cumbersome.
The instructions at the above link are fairly clear, and I managed to modify my User Settings as directed, so that they look like this:
// Settings in here override those in "Default/Preferences.sublime-settings", and
// are overridden in turn by file type specific settings.
{
    "keys": ["alt+m"],
        "command": "markdown_preview",
        "args":
            {
                "target": "browser"
            }
}

For some reason, however, ALT-m is not bringing up the preview.  Instead, the greek letter mu gets inserted into my text file.
I assumed this is because of some peculiarity involving the Option key on a Mac, so I experimented with trying to bind it to another key like "f7", but that doesn't seem to work either.
Can anybody think of any gotchas involving keybindings for Sublime Text 2 on MacOS X that I might be overlooking?

A: User keybindings are defined in the .sublime-keymap file, I think you are in the .sublime-settings file. Just put it in the right file and it should work. I'm on Windows, so I'm not sure if it's identical for Mac, but I can access the file from the Preferences menu (Key Bindings - User).

A: I 'd like to add something,  sublime text2, and os x 10.8
Check the following picture, go to the Menu of sublime text 2,  Sublime Text 2 -> Preference -> Key Binds Default -  and then in the file do the edit for need,


text:
Q: Android application crashes, but doesn't restart - resumes from another point in the application The application in question has already been deployed. I have found out about ACRA, and will be adding that in to find out why the application crashes are happening.
My problem however, is that the application will crash (the dialog will show up giving you the option to either "Force Close" or "Wait"), but instead of restarting the application completely, it resumes from a point before the crash occurred. This causes problems however, that are only fixed by restarting the application (eg. sudden loss of data, crashes that don't make sense, etc.).
So how can I force my application, once crashed, to just end? (NOT restart).
Edit: The biggest issue is that after the application crashes, all the data in my preferences file disappears, until the app is restarted when it comes back.

A: Android will re-start the last active activity by default. Instead of forcing it to restart, the better strategy would be to fix your application, so that activities don't crash or exit gracefully even if no data is available. If you absolutely depend on some data (intent extras) and there are no defaults, you can just call finish() if it is not available, or start the main/parent activity.
Another way is to have your own default exception handler which re-starts the main activity, etc. after reporting the crash using ACRA (I believe there is a feature request for this in ACRA's bugtracker).

A: I know this question is a bit old, but for future references and googlers, here is a complete answer from another, hard to find, stackoverflow question: Android App Restarts upon Crash/force close

create a class used to handle unCaughtException
public class MyExceptionHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final Class<?> myActivityClass;

    public MyExceptionHandler(Context context, Class<?> c) {

        myContext = context;
        myActivityClass = c;
    }

    public void uncaughtException(Thread thread, Throwable exception) {

        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace);// You can use LogCat too
        Intent intent = new Intent(myContext, myActivityClass);
        String s = stackTrace.toString();
        //you can use this String to know what caused the exception and in which Activity
        intent.putExtra("uncaughtException",
                "Exception is: " + stackTrace.toString());
        intent.putExtra("stacktrace", s);
        myContext.startActivity(intent);
        //for restarting the Activity
        Process.killProcess(Process.myPid());
        System.exit(0);
    }
}

Then in every thread (usually you have just one, unless you start a new thread (Async or ... , ofcourse you know about threads if you are able to make new ;) ), set this class as the DefaultUncaughtExceptionHandler
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            YourCurrentActivity.class));

Remember though!
Do it in the very last step of developing your application, you HAVE to at least try handle all of your exceptions one by one before leaving them for DefaultUncaughtExceptionHandler


text:
Q: Handling Browser authentication when parsing I am currently working on a link validation script which uses HTTPURLCONNECTION to connect to the servers. But some of the servers have browser authentication, which invariably causes 401 errors. The major problem over here is that there are multiple authentication credentials and it would be useful I can extract the string displayed in the authentication dialog box so that I can enter the correct credentials.
If this is not possible programatically, could you please guide me as to how I can display the Pop Up's to the user itself and get the credentials manually and then continue with the link validation.(I have seen Xenu Link Sleuth do this). Any help will be greatly appreciated.
Thanks


text:
Q: Determine element position in list Consider a list of exam scores (give as percentages) such that
set list = ( 90 100 80 )

The position of these scores in the list determine which exam they pertain to.  For example, the first element, 90, corresponds to Exam 1, the second element, 100, corresponds to Exam 2, etc.).
I sort list to find the minimum score as follows:
echo $list | fmt -1 | sort -n | head -1

Clearly the minimum score in this case would be 80 which is the third element in the list (corresponding to the third exam).  I need to know how to determine the minimum value as well as its corresponding position in a list of arbitrary length.  In this way I can retrieve the proper 'total possible points' for that exam and apply a drop grade.


text:
Q: Вычитание / сложение дат C# в пределах 5-дневного рабочего дня Мне нужно произвести условное вычитание и сложение дат, а так же условное вычитание и сложение минут. Опишу что имею ввиду:
В неделе 5 рабочих дней (Пн - Пт). В эти дни есть рабочие часы (10 - 18).
Мне нужно производить ряд операций:
 1. (DT_1-DT_1).TotalMinutes
 2. DT.AddMinutes(minutes)

Как бы наиболее просто реализовать это ? Пробовал с методами расширения но получается очень громоздко и запутано...
Мне нужно следующее к примеру:

DT_1 = 2019.01.11 18:00:00.000 (Пт)
DT_2 = 2019.01.12 10:00:00.000 (Сб)
minutes = 60 (1 час)
(DT_1-DT_).TotalMinutes_custom = 0
(DT_2-DT_1).TotalMinutes_custom =0
DT_1.AddMinutes_custom(minutes)= 2019.01.14 11:00:00.000
DT_2.AddMinutes_custom(-minutes) = 2019.01.11 17:00:00.000

Быть может кто нибудь знает как подобное реализовать наиболее просто и красиво ? Или же быть может уже есть встроенное решение ?

A: У вас 40-часовая рабочая неделя.
Тогда что... вам нужно расписать ваше время внутри этой недели.
Тогда нужно
struct DAYS40{ DayOfWeek day;  int hour; };

List<DAYS40> days40; // TODO: задать дни и часы 40 штук

// Тогда у нас 40-ричная система счисления)))
// Если мы берем i = от нуля до 39 - это внутри недели.
// 40 - новая неделя, тогда...

Каждый час отдельно. Если ПН с 9-18 то ПН 9, ПН 10, ПН 11.... ПН 17 ВТ 8.... ПТ 9 ... ПТ 15 наверно так.
Тогда ваша прибавка будет выглядеть так.
 DateTime AddHour(DateTime dt, int hour) {
     DAYS40 item;
     item.day = dt.DayOfWeek;
     item.hour = dt.hour;
     i = days40.indexOf(item);
     if (i == -1) throw new Exception(""); // Придумать что-то
     // вот і это текущая позиция.
     int dayfrom = (int)days40[i].day;
     i = i +  (hour % 40); // меняем позицию.
     int weeks = (hour / 40) +  (i / 40); // Дни
     // Первое слагаемое - ясно, второе слагаемое-если прошло 7 дней.
     // Получились к-во недель
     i = i % 40; // и часы в 40-часовой системе
     // Ну... теперь можно переводить.
     int dayto = (int)days40[i].day;
     return dt.Date.AddDays(7*weeks + dayto - dayfrom)
      .AddHours(days40[i].hour);
      // Думаю минуты не нужны
      // отрицательная разница dayto-dayfrom компенсируется слагаемым (i/40)
     }

Но ваше dt - должно быть в рамках 40-часовой системы, если это не так - то нужно уточнять задачу.
А да. Разница в часах... то же, переводим в 40-ричную систему, и вычитаем.
Находим два индекса i и j (так как выше). Тогда ответ в часах будет...   (TotalDays / 7)*40 + j - i
А дальше... дальше можно как-то нормировать день. Можно найти min и max час в дне... и... либо вычитать "лишний остаток", либо переносить его на следующий день... думаю имея такой массив - это не тяжело сделать.
Да... такой метод не учитывает празничные дни и переносы, отрабатывание по субботам и т п. Нужно создать ещё одну таблицу - массив НомерРабочегоДня-День-Месяц-Год и через неё считать к-во дней, а не через сквозной календарь. Например сделать Dictionary<DateTime,int> days и вести "календарь рабочих дней" в базе данных. Только расчётные данные не должны менятся - потому что интервалы не совпадут. Тогда расстояние между днями "грубо" будет days[d2.date]-days[d1.date], а в предложеном выше методе - прийдётся вместо AddDays использовать такой массив, и через индексы вычислять расстояние в днях.


text:
Q: Java dynamic method creation I have following information in JSON format.
 [
  {
    "name": "A",
    "value": {
      "isValueApplicable": "true"
    }
  },
  {
    "name": "B",
    "parameters": [
      {
        "name": "x",
        "isMandatory": "true"
      },
      {
        "name": "y",
        "isMandatory": "true"
      }
    ]
  },
  {
    "name": "C",
    "parameters": [
      {
        "name": "x",
        "isMandatory": "true"
      },
      {
        "name": "y",
        "isMandatory": "false"
      }
    ]
  }
]

What I want is, a class is created with following methods :
public Structure getA (String value) {
}

public Structure getB (String xValue, String yValue) {
}

public Structure getC (String xValue) {
}

public Structure getC (String xValue, String yValue) {
}

The important part here is, these methods should be created dynamically based on the information given in JSON. So, for A only value is applicable. For B, both values x and y are needed. But for C, only x value is mandatory and user can provide value for y, hence the 2 different methods.
Q. Is it possible in java to generate the methods at compile time after reading the JSON, like if the parameters are mandatory i will create method with those many parameters. If the value if not applicable then i will create method without any parameter.

A: Yes it can be done using Reflection in Java Or You can use javaassit and cglib

A: yes, you can generate Java bytecode on the fly. CGLib (Github link here) is one option to do that.
Or you can generate Java source code from Json with something like Jackson, and compile that. Here's one example.
I'm sure there are more ways, but yes, it's certainly possible.
Of course the Json you're showing is corrupt so would never yield anything but a parser error.


text:
Q: Meteor: create user account when the client is authenticated the fist time they signin with linkedin? I am running meteor.js and have globally installed npm package node-linkedin
https://www.npmjs.com/package/node-linkedin
I have registered my application with linkedin which means I have my api key, secret key and oAuth redirect urls to localhost:3000
My app currently displays the 'sign in' linkedIn button where the user grants my application access to the full profile of the user. According to linkedIn javascript API docs, the onLinkedInAuth() object (which runs upon successful authentication) contains the linkedin id of the user.
How do I create a user account, Accounts.createUser when the user is authenticated and store the id from the onLinkedInAuth() object in the user collection?
server.js
var Linkedin = Npm.require('node-linkedin')('api', 'secret', 'I-PUT-REDIRECT-URL-HERE');

How do I make the get requests using the npm package https://www.npmjs.com/package/node-linkedin (see under heading oAuth 2.0) which redirects the user to linkedins authorization dialog and subsequently retrieve the access token.
HTML:

<template name="parent"> //layout template

</template>

A: Have you considered using a combination of https://github.com/Differential/accounts-entry and https://atmospherejs.com/pauli/accounts-linkedin?  Based on the docs for http://docs.meteor.com/#/full/accounts_oncreateuser, you should be able to fetch the data from options.profile.


text:
Q: heatmap to color image matlab I have a grayscle image. I can create a heatmap in matlab using:
        I = imagesc(I);

it displays the intensity values in color. I want to get a color image using this heatmap. How can I do it?
This is the output of imagesc:

A: Presumably by "color image" you mean an RGB or truecolor image (an image array with three color channels). And what you're calling a "heatmap" is the colormap that Matlab applies by default to grayscale images (image arrays with only one color channel). A grayscale image plus a color map is referred to as an indexed color image (read more about that here). You can use the ind2rgb function to convert from indexed color to RGB:
IMG_gray = rand(100);
map = colormap; % Get the current colormap
IMG_rgb = ind2rgb(IMG_gray,map);

Note that by default the colormaps in Matlab use only 64 colors rather 256. To get smoother color gradations you can set the colormap manually via map = colormap(jet(256)); or map = colormap(hsv(256));.
If you then want an image file, you can use imwrite, which can take either RGB images or indexed color images with colormaps as input.

A: Scale the intensity values in your image as imagesc does, and use a colormap (jet is default):
N = 256;
IN = round(N * (I-min(I(:)))/(max(I(:))-min(I(:))));
cmap = jet(N); % see also hot, etc.
IRGB = ind2rgb(IN,cmap);


text:
Q: Multiprocessing with pool in python: About several instances with same name at the same time I'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of SomeKindOfClass with the same name (a) at the same time. How is that possible? Moreover, is there a potential risk with this kind of programming?
from multiprocessing.dummy import Pool
import numpy
from theFile import someKindOfClass

n = 8
allOutputs = numpy.zeros(n)

def work(index):
    a = SomeKindOfClass()
    a.theSlowFunction()
    allOutputs[index] = a.output

pool = Pool(processes=4)
pool.map(work,range(0,n))

A: The name a is only local in scope within your work function, so there is no conflict of names here.  Internally python will keep track of each class instance with a unique identifier.  If you wanted to check this you could check the object id using the id function:
print(id(a))

I don't see any issues with your code.

A: Actually, you will have 8 instances of SomeKindOfClass (one for each worker), but only 4 will ever be active at the same time.
multiprocessing vs multiprocessing.dummy
Your program will only work if you continue to use the multiprocessing.dummy module, which is just a wrapper around the threading module.  You are still using "python threads" (not separate processes).  "Python threads" share the same global state; "Processes" don't.  Python threads also share the same GIL, so they're still limited to running one python bytecode statement at a time, unlike processes, which can all run python code simultaneously.
If you were to change your import to from multiprocessing import Pool, you would notice that the allOutputs array remains unchanged after all the workers finish executing (also, you would likely get an error because you're creating the pool in the global scope, you should probably put that inside a main() function).  This is because multiprocessing makes a new copy of the entire global state when it makes a new process.  When the worker modifies the global allOutputs, it will be modifying a copy of that initial global state.  When the process ends, nothing will be returned to the main process and the global state of the main process will remain unchanged.
Sharing State Between Processes
Unlike threads, processes aren't sharing the same memory
If you want to share state between processes, you have to explicitly declare shared variables and pass them to each process, or use pipes or some other method to allow the worker processes to communicate with each other or with the main process.
There are several ways to do this, but perhaps the simplest is using the Manager class
import multiprocessing

def worker(args):
    index, array = args
    a = SomeKindOfClass()
    a.some_expensive_function()
    array[index] = a.output

def main():
    n = 8
    manager = multiprocessing.Manager()
    array = manager.list([0] * n)
    pool = multiprocessing.Pool(4)
    pool.map(worker, [(i, array) for i in range(n)])
    print array

A: You can declare class instances inside the pool workers, because each instance has a separate place in memory so they don't conflict.  The problem is if you declare a class instance first, then try to pass that one instance into multiple pool workers.  Then each worker has a pointer to the same place in memory, and it will fail (this can be handled, just not this way).
Basically pool workers must not have overlapping memory anywhere.  As long as the workers don't try to share memory somewhere, or perform operations that may result in collisions (like printing to the same file), there shouldn't be any problem.
Make sure whatever they're supposed to do (like something you want printed to a file, or added to a broader namespace somewhere) is returned as a result at the end, which you then iterate through.

A: If you are using multiprocessing you shouldn't worry - process doesn't share memory (by-default). So, there is no any risk to have several independent objects of class SomeKindOfClass - each of them will live in own process. How it works? Python runs your program and after that it runs 4 child processes. That's why it's very important to have if __init__ == '__main__' construction before pool.map(work,range(0,n)). Otherwise you will receive a infinity loop of process creation.
Problems could be if SomeKindOfClass keeps state on disk - for example, write something to file or read it.


text:
Q: Yii2 Pjax reloads the page I have a Pjax container in which i want to load either books or authors.My active form has two tabs by which i choose what to load. I tested my sql in phpmyadmin and they are ok(returns what expected). Tried to var_dump after each row of my controller but it seems to be ok also. But when i comes to the 'magic of the pjax' the page get reloaded. There is no errors in the console log. The response from the request in the Network tab returns the whole html. Can you take a look and give and advance?
Controller action:
public function actionSingleGenre(){
        $first_step = Yii::$app->getRequest()->getQueryParam('first_step');
        $second_step = Yii::$app->getRequest()->getQueryParam('second_step');
        $id = end(explode('-', $second_step));
        $genresPage = Page::findOne(76);
        $booksPage = Page::findOne(45);
        $authorsPage = Page::findOne(46);
        $lang = Lang::getCurrent();
        $genre = Brands::findOne($id);
        $banner = CategoryImage::find()->where(['page_id' => $genresPage->id])->one();
        $pageSize = 12;
        $entity = 'book';

        $sql = "SELECT *
                 FROM `product` as p
                 LEFT JOIN `productLang` as pl ON p.`id`=pl.`product_id`
                 LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
                 WHERE bb.`brand_id`=$id";

        if(Yii::$app->request->isPjax){
            if(isset($_GET['type']) && $_GET['type'] != ''){
                $type = $_GET['type'];
                if($type == 1){
                    $sql = "SELECT *
                                FROM `product` as p
                                LEFT JOIN `productLang` as pl ON p.`id`=pl.`id`
                                LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
                                WHERE bb.`brand_id`=$id";
                }
                else if($type == 2)
                {
                    $sql = "SELECT *
                            FROM `author` as a
                            LEFT JOIN `authorLang` as al ON a.`id`=al.`author_id`
                            WHERE a.`id` IN (
                              SELECT p.`author_id`
                              FROM `product` as p
                              LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
                              WHERE bb.`brand_id`=$id
                            )";
                    $entity = 'author';
                }
            }
        }

        $count = count(Yii::$app->db->createCommand($sql)->queryAll());

        $dataProvider = new SqlDataProvider([
            'sql' => $sql,
            'totalCount' => $count,
            'pagination' => [
                'pageSize' => $pageSize,
                'route' => $first_step . '/' . $second_step
            ]
        ]);

        $models = $dataProvider->getModels();

        $pagination = new Pagination([
           'pageSize' => $pageSize,
            'totalCount' => $count,
            'route' => $first_step . '/' . $second_step
        ]);

        if(Yii::$app->request->isPjax){
            return $this->renderAjax('single-genre', [
                'genresPage' => $genresPage,
                'authorsPage' => $authorsPage,
                'lang' => $lang,
                'banner' => $banner,
                'booksPage' => $booksPage,
                'genre' => $genre,
                'models' => $models,
                'pagination' => $pagination,
                'entity' => $entity,
            ]);
        }
        return $this->render('single-genre', [
            'genresPage' => $genresPage,
            'authorsPage' => $authorsPage,
            'lang' => $lang,
            'banner' => $banner,
            'booksPage' => $booksPage,
            'genre' => $genre,
            'models' => $models,
            'pagination' => $pagination,
            'entity' => $entity,
        ]);
    }

jQuery:
function pjaxFilterForm() {
    var dataString = $("#filter-group2").serialize();
    $.pjax.defaults.timeout = false;
    $.pjax({
        container: "#booksGrid",
        url: location.href.split("?")[0],
        data: dataString,
        scrollTo: false
    });
    return false;
}

View:

    <?php \yii\bootstrap\ActiveForm::begin([
            'method' => 'get',
            'action' => '#',
            'options' => ['data-pjax'=>true, 'onsubmit'=>'return pjaxFilterForm()', 'id'=>'filter-group2']
    ]) ?>

    <input type="hidden" name="type">

<?= Yii::t('app', 'app.Books') ?>

<?= Yii::t('app', 'app.Authors') ?>

    <?php \yii\bootstrap\ActiveForm::end(); ?>

<?php \yii\widgets\Pjax::begin(['id'=>'booksGrid']) ?>
    <?php if($models) : ?>

        <?php foreach ($models as $model){
            if($entity == 'book'){
                $model = \backend\modules\products\models\Product::findOne($model['product_id']);
                echo $this->render('_authorBooks', ['book' => $model, 'lang' => $lang, 'booksPage' => $booksPage]);
            }else if($entity == 'author'){
                $model = \backend\models\Author::findOne($model['author_id']);
                echo $this->render('_authorGenre', ['book' => $model, 'lang' => $lang, 'authorsPage' => $authorsPage]);
            }
        } ?>

        <?= \yii\widgets\LinkPager::widget([
            'pagination' => $pagination,
            'hideOnSinglePage' => true,
            'prevPageLabel' => Yii::t('app', 'app.Prev'),
            'nextPageLabel' => Yii::t('app', 'app.Next')
        ]) ?>

    <?php endif; ?>
<?php \yii\widgets\Pjax::end() ?>


text: Q: If $f$ is quasiconvex and differentiable then $f$ is convex? Let $f\colon C \to \mathbb{R}$ be a homogeneous function of degree $1$, $C\subset \mathbb{R}^n$ a cone. If $f$ is differentiable then it is true: if $f$ is quasiconvex $\Rightarrow$ $f$ is convex.


text:
Q: how to get cellular connection data I can not find any plugin to get android cellular data (I want to know first if My connection is of type 2G, 3G or 4G then at least I want to get my signal strength and some other info but those 2 are very important).

A: Yes there is plugin available for check internet connection state in different parameter.like downloading and uploading data speed.
internet_speed_test
Like this,
Var unitText = unit == SpeedUnit.Kbps;


text:
Q: "Method range of object global failed" Calling for a named range in VBA I need some help fixing this error a ran into with a named range. So I'm getting the "Method range of object global failed" on Range("Frost_T"). I defined the Range Frost_T in the name manger but it's not exactly a range it's basically just a formula taking an input from a cell to calculate an output and the output itself is not in a define cell it's just under Frost_T and then I callout that name in other formulas within the workbook. That part works fine it's when I try to use it in VBA for macros It's not working. I need help to learn how to callout these kind of named range that aren't really in a range of cells but just kept under it's name. I tied explaining it the best way I can but if you need more details let me know. See code bellow.
Thanks in advance for the help!
Sub OA_T_Reset()

  If Range("CB_CL_Values").Cells(6) = 1 Then

    If Range("Inputs_OA").Cells(3) < Range("Frost_T") = True Then
    Range("Inputs_OA").Cells(3).Value = Range("Frost_T")

    Else

    End If

  Else

  End If

End Sub

A: Try to change Range("Frost_T") to Evaluate("Frost_T") as follows:
Sub OA_T_Reset()

    If Range("CB_CL_Values").Cells(6) = 1 Then
        If Range("Inputs_OA").Cells(3) < Evaluate("Frost_T") Then
            Range("Inputs_OA").Cells(3).Value = Evaluate("Frost_T")
        Else

        End If
    Else

    End If

End Sub


text:
Q: What tools exist that help me reference topics within a .CHM from a WinForms app? I have inherited both an existing WinForms app and an existing .CHM file, created using Dr. Explain. I need to reference different topics within the CHM from different parts of my WinForms app, but I don't know what topics, if any, are defined within the CHM. Is there a tool that lists all existing topics that I can reference using the System.Windows.Form.Help class? If there are no topics or I need to add a new one (let's say I want to add a topic named "TwainScanning" to existing content within the .CHM), is there a tool for that? I could ask the author to add some, but she is not very technical and I need to explain my request very carefully. Exactly what do I ask her to do?

A: The topics are roughly equal to the html files.
See
How to check if a subfile exists in a chm file?
how to get a list of the html files in the archive.
Aside from this, there is a TOC and an INDEX that also have topics. (and these can refer to anchors too). They are usually encoded in the chm file as .hhc and .hhk files, which you can extract from the CHM using an extracter.
Modifying a file without the tool it was made with (the exact chm compiler project files etc) is hard.

A: The HelpProvider will allow you to access specific parts of the help file. Not sure about your other questions though.


text:
Q: How to Collect data from ALL sheets using google Appscript I have script that searches through an entire workbook for a specific name and returns all the data on that name. The script works, but only collects data from 1 sheet within the workbook.
I searched for some code to assist me getting all the sheet names. So I have code that does that, but for some reason it still only returns from 1 sheet.
The code below collects all the sheet names.
This function is then called in the query function.
I Suspect that this is where the issue is occuring
function sheetnames() {

var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

for (var i=0 ; i < sheets.length ; i++) {
    var name = sheets[i].getName();

    var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
    var values = data.getRange(4, 1, data.getLastRow(),

    data.getLastColumn()).getValues();
    out.push(values);
    }

return out;
}

This function then searches for the requested data.
function query() {

var Sheet = SpreadsheetApp.getActiveSpreadsheet();

var searchSheet = Sheet.getSheetByName("Search");
var searchByName = searchSheet.getRange(4, 8).getValue();

var uses = sheetnames();
var output = new Array();

var i = 0;
var r = 0;

do{
  var from = uses[i];

  do{
    var row = from[r];

    if(row == null){
      r++;
      continue;
    }

    if(searchByName != null ){
      var newName = row[7];
      if(newName == searchByName){
        output.push(row);
      }
    }
     r ++;
    }while(r < from.length);
    i ++;

  }while(i < uses.length);

return output;
}

This part just prints the data into the cells and is attached to a search drawing, which runs the function in the sheet.
function search() {

 var Sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Search");

 var data = query();

 var count1 = 0;

do{
  var subData = data[count1];
  var count2 = 0;

  do{
    var setTo = subData[count2];
    Sheet.getRange((count1 + 5), (count2 + 1)).setValue(setTo);
    count2 ++;
    }while(count2 < subData.length);

   count1 ++;
   }while(count1 < data.length);
}

The sheet is called the "Daily Payments Sheet." As you can imagine there is A LOT of data. Each sheet name is named by the month and the year that the payment occurred. The more consistent customers would obviously make purchases in more than one month.
So when searching for a customers name, I only get 1 month (1 sheet's data) returned. We have data from May 2018 till date, so again, the script doesn't collect from all the sheets.

A: Your code is not very readable so I figured some things on my own and simplified it. Things I assume - your search term is in 'Search' sheet column H4 and you want to search all sheets for this term in H4 column and write those out in 'Search' sheet after 4th row. Try this.
// return all rows from all sheets except Search sheet
function sheetValues(ss) {
  var out = [];
  var sheets = ss.getSheets();

  for (var i = 0; i < sheets.length; i++) {
    var sheet = sheets[i];
    if (sheet.getName() == 'Search') continue;
    var values = sheet.getRange(4, 1, sheet.getLastRow() - 3, sheet.getLastColumn()).getValues();
    out.concat(values);
  }

  return out;
}
// search all rows for given term and return results
// look for term in H column of every row
function query(ss, term) {
  if (!term) return;

  var values = sheetValues(ss);
  var output = [];

  for (var i = 0; i < values.length; i++) {
    var row = values[i];
    var name = row[7]; // 7 = col H
    if (name == term) {
      output.push(row);
    }
  }

  return output;
}
// get search results and print into Search sheet
function search() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Search');
  var searchByName = sheet.getRange(4, 8).getValue(); // search term is in H4 cell

  var data = query(ss, searchByName);

  sheet.getRange(5, 1, sheet.getLastRow() - 4, sheet.getLastColumn()).clearContent();
  sheet.getRange(5, 1, data.length, data[0].length).setValues(data);
}


text:
Q: Python - Convert 8 bit binary number to decimal import math

while True:
    try:
        user_bin = int(input('\nPlease enter binary number: '), 2)
    except ValueError:
        print('Please make sure your number contains digits 0-1 only.')
    else:
        print(user_bin)

I've just been browsing this site looking for tips on how to complete an assignment, the basics of the assignment is to have the user input an 8 bit binary number, and convert it to decimal. Or pop up an invalid input error in situations where it doesn't fit the requirements. The code above seemed interesting so I tested it and I genuinely don't understand which part of the code converts the binary to decimal. Any tips for the assignment as well as explanations would be appreciated.

A: The part that converts the binary is int. From the documentation:

if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.

This means that int accepts a string representing an integer, that you tell it the base of. E.g. here we give it "11", and tell it this is in base 2, so it returns the integer 3 in decimal.
>>> int("11", 2)
3

Note that when supplying the base argument, you have to give a string:
>>> int(11, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base

And you can't use digits that are invalid in the given base:
>>> int("21", 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '21'


text:
Q: Nodejs/Express: Facing issues while working on routings viewController.js
const Book = require('./../models/bookModel')
const APIFeatures = require('./../utils/apiFeatures.js')

exports.getOverview=async(req,res,next)=>{

  const features = new APIFeatures(Book.find(),req.query).filter().paginations()
  let getItAllProd = await features.getBook;
  res.render('overview',{
    data:getItAllProd,
    title:"trending books"
  })
  next()
}

exports.getOneBook =async(req,res,next)=>{
  const getThatBook = await Book.findOne({slug:req.params.id})
  res.render('onebook',{
    data:getThatBook
  })
  next()
}

exports.categories= async(req,res,next)=>{
  const getCate = await Book.find({category:req.params.category});
  res.render('overview',{
    data:getCate,
    name:req.params
  })
  next()
}

exports.paginationOfBook = async(req,res,next)=>{
  let pages = req.params.page
  pages = pages * 6 || 6;
  const limit = 6;
  let skip = pages-6;

  const getlimitedbook = await Book.find({}).limit(limit).skip(skip);
  res.render('overview',{
    data:getlimitedbook,
  })
  next()
}

viewRoutes.js
const express = require('express');
const viewController = require('./../controllers/viewController')
const router = express.Router();

router.get('/overview',viewController.getOverview)

router.get('/overview/:category',viewController.categories)
router.get('/overview/:page',viewController.paginationOfBook)
router.get('/overview/:id',viewController.getOneBook)

module.exports = router;

using http://localhost:3000/overview I can get all the books and http://localhost:3000/overview/:category - using this I get the books by categories. but if I try to load the the for http://localhost:3000/overview/:page and http://localhost:3000/overview?:id - the data will not load up.. so below I did some changes in routing..
router.get('/overview',viewController.getOverview)
router.get('/overview/:id',viewController.getOneBook)
router.get('/overview/:category',viewController.categories)
router.get('/overview/:page',viewController.paginationOfBook)

Now I have access to the '/overview' and '/overview/:Id'. but not for others. the data is not loading for them. do you have any solution? so I can access all the routes.uuu

A: First of all please elaborate you're question more. But I think the problem is in the following line:
 const getThatBook = await Book.findOne({slug:req.params.id})

edit this line to:
 const getThatBook = await Book.findById(req.params.id)

and call this route like this http://localhost:3000/overview/34234232...
Or change your "id" to "slug" in the following line.
 const getThatBook = await Book.findOne({slug:req.params.slug})

and call this route like this http://localhost:3000/overview/xyz_book_slug...
router.get('/overview/:slug',viewController.getOneBook)

and pass the book's slug property value when calling this route.


text:
Q: Header is not fixed when textfield onfocus event fired in jquery Header is moving up/down when textfield onfocus event fired in jquery even if i used data-position="fixed" for header. Can anyone help how to fix the header when onfocus and onblur is calling?
Here is the html code.
I need to scroll list view  to upside then i click on the right button on header, one popup will come. If i select the textfiled on that popup keypad will comeup and header will move to down like below screen shot.

         <input type="text"  id="adddescriptionName"  placeholder="Enter Category Name"  style="background:rgba(218,218,218,1);height:32px;width:153px;margin-top:15px;border-radius: 3px;" />

A: You can try by making the position of the header to absolute instead of fixed.
#page1Header{
position:absolute !important;
top:0;
left:0;
right:0;
}


text:
Q: Issue with a generic dictionary of operations I have a dictionary of operations:
type INumerics<'T> =
  abstract Zer : 'T
  abstract Add : 'T * 'T -> 'T
  abstract Sub : 'T * 'T -> 'T
  abstract Mul : 'T * 'T -> 'T
  abstract Div : 'T * 'T -> 'T
  abstract Neq : 'T * 'T -> bool

With helper functions:
let inline add (x : 'T) (y : 'T) : 'T   = (+)  x y
let inline sub (x : 'T) (y : 'T) : 'T   = (-)  x y
let inline mul (x : 'T) (y : 'T) : 'T   = (*)  x y
let inline div (x : 'T) (y : 'T) : 'T   = (/)  x y
let inline neq (x : 'T) (y : 'T) : bool = (<>) x y

Then we have a simple calculator using a MailboxProcessor agent:
type Agent<'T> = MailboxProcessor<'T>

type CalculatorMsg<'T> =
    | Add of 'T * 'T * AsyncReplyChannel<'T>
    | Sub of 'T * 'T * AsyncReplyChannel<'T>
    | Mul of 'T * 'T * AsyncReplyChannel<'T>
    | Div of 'T * 'T * AsyncReplyChannel<'T>

type CalculatorAgent< ^T when ^T : (static member get_Zero : unit -> ^T)
                         and  ^T : (static member Zero : ^T)
                         and  ^T : (static member (+)  : ^T * ^T -> ^T)
                         and  ^T : (static member (-)  : ^T * ^T -> ^T)
                         and  ^T : (static member (*)  : ^T * ^T -> ^T)
                         and  ^T : (static member (/)  : ^T * ^T -> ^T)
                         and  ^T : equality >() =
    let agent =
        let ops =
            { new INumerics<'T> with
                member ops.Zer       = LanguagePrimitives.GenericZero<'T>
                member ops.Add(x, y) = (x, y) ||> add
                member ops.Sub(x, y) = (x, y) ||> sub
                member ops.Mul(x, y) = (x, y) ||> mul
                member ops.Div(x, y) = (x, y) ||> div
                member ops.Neq(x, y) = (x, y) ||> neq }

        Agent<CalculatorMsg<'T>>.Start(fun inbox ->
            let rec loop () =
                async {
                    let! msg = inbox.TryReceive()
                    if msg.IsSome then
                        match msg.Value with
                        | Add (x, y, rep) ->
                            printfn "Adding %A and %A ..." x y
                            let res = ops.Add(x, y)
                            res |> rep.Reply
                            return! loop()
                        | Sub (x, y, rep) ->
                            printfn "Subtracting %A from %A ..." y x
                            let res = ops.Sub(x, y)
                            res |> rep.Reply
                            return! loop()
                        | Mul (x, y, rep) ->
                            printfn "Multiplying %A by %A ... " y x
                            let res = ops.Mul(x, y)
                            res |> rep.Reply
                            return! loop()
                        | Div (x, y, rep) ->
                            printfn "Dividing %A by %A ..." x y
                            if ops.Neq(y, ops.Zer) then
                                let res = ops.Div(x, y)
                                res |> rep.Reply
                            else
                                printfn "#DIV/0"
                            return! loop()
                    else
                        return! loop()
                }
            loop()
        )

    // timeout = infinit => t = -1
    let t = 1000

    member inline this.Add(x, y) =
        agent.PostAndTryAsyncReply((fun rep -> Add (x, y, rep)), t)
        |> Async.RunSynchronously
    member inline this.Subtract(x, y) =
        agent.PostAndTryAsyncReply((fun rep -> Sub (x, y, rep)), t)
        |> Async.RunSynchronously
    member inline this.Multiply(x, y) =
        agent.PostAndTryAsyncReply((fun rep -> Mul (x, y, rep)), t)
        |> Async.RunSynchronously
    member inline this.Divide(x, y) =
        agent.PostAndTryAsyncReply((fun rep -> Div (x, y, rep)), t)
        |> Async.RunSynchronously

As a use example, we have:
let calculatorAgentI = new CalculatorAgent<int>()

(2, 1) |> calculatorAgentI.Add
(2, 1) |> calculatorAgentI.Subtract
(2, 1) |> calculatorAgentI.Multiply
(2, 1) |> calculatorAgentI.Divide
(2, 0) |> calculatorAgentI.Divide

The issue is that Add and Multiply and the Last Divide work ok:
>
Adding 2 and 1 ...
val it : int option = Some 3

>
Multiplying 1 by 2 ...
val it : int option = Some 2

>
Dividing 2 by 0 ...
#DIV/0
val it : int option = None

As soon as we use Subtract and first Divide which would return int option = None, I get into trouble and the following is the only output I would get from any of the operations:
>
val it : int option = None

As long and hard as I think about it, I cannot figure out if there is a problem in the "subtract"/"divide" part or the "receive"/"reply" operations.

A: Running this code with the Debugger attached, you'll see that you get a System.NotSupportedException when trying to run the sub function from inside the agent:
System.NotSupportedException occurred
  HResult=0x80131515
  Message=Specified method is not supported.
  Source=FSI-ASSEMBLY
  StackTrace:
  at FSI_0002.ops@60.FSI_0002-INumerics`1-Sub(T X1, T X2)

The reason you get val it : int option = None is because you have specified a 1-second timeout, and you are hitting that after the exception is thrown.
Calling the sub function directly works fine, but calling it through the CalculatorAgent class does not. This is because the type parameters are defined on the class in this case, and there are limitations on the use of structural type constraints on classes in F#.   I would suggest reading up on Statically Resolved Type Parameters and their limitations.

A: The behaviour seems to be an irregularity or a bug. I was also expecting that this would behave the same for all operations.
In any case, you can workaround this by capturing ops in a static inline member (rather than using statically resolved type parameters on a type). The following works fine for me:
type CalculatorAgent<'T>(ops:INumerics<'T>) =
  let agent =
    Agent<CalculatorMsg<'T>>.Start(fun inbox ->
      let rec loop () = async {
        let! msg = inbox.TryReceive()
        match msg with
        | Some(Add (x, y, rep)) ->
            printfn "Adding %A and %A ..." x y
            let res = ops.Add(x, y)
            res |> rep.Reply
            return! loop()
        | Some(Sub (x, y, rep)) ->
            printfn "Subtracting %A from %A ..." y x
            let res = ops.Sub(x, y)
            res |> rep.Reply
            return! loop()
        | Some(Mul (x, y, rep)) ->
            printfn "Multiplying %A by %A ... " y x
            let res = ops.Mul(x, y)
            res |> rep.Reply
            return! loop()
        | Some(Div (x, y, rep)) ->
            printfn "Dividing %A by %A ..." x y
            if ops.Neq(y, ops.Zer) then
                let res = ops.Div(x, y)
                res |> rep.Reply
            else
                printfn "#DIV/0"
            return! loop()
        | _ ->
            return! loop() }
      loop() )

  // timeout = infinit => t = -1
  let t = 1000

  member this.Add(x, y) =
    agent.PostAndTryAsyncReply((fun rep -> Add (x, y, rep)), t)
    |> Async.RunSynchronously
  member this.Subtract(x, y) =
    agent.PostAndTryAsyncReply((fun rep -> Sub (x, y, rep)), t)
    |> Async.RunSynchronously
  member this.Multiply(x, y) =
    agent.PostAndTryAsyncReply((fun rep -> Mul (x, y, rep)), t)
    |> Async.RunSynchronously
  member this.Divide(x, y) =
    agent.PostAndTryAsyncReply((fun rep -> Div (x, y, rep)), t)
    |> Async.RunSynchronously

type CalculatorAgent =
  static member inline Create() =
    let ops =
      { new INumerics<_> with
          member ops.Zer = LanguagePrimitives.GenericZero<_>
          member ops.Add(x, y) = x + y
          member ops.Sub(x, y) = x - y
          member ops.Mul(x, y) = x * y
          member ops.Div(x, y) = x / y
          member ops.Neq(x, y) = x <> y }
    CalculatorAgent<_>(ops)

let calculatorAgentI = CalculatorAgent.Create<int>()

(2, 1) |> calculatorAgentI.Add
(2, 1) |> calculatorAgentI.Subtract
(2, 1) |> calculatorAgentI.Multiply
(2, 1) |> calculatorAgentI.Divide
(2, 0) |> calculatorAgentI.Divide

That said, I think the cases where you really need generic numerical code are pretty rare - so I suspect it might be better to avoid introducing all this complexity altogether and just write the code for a specific numerical type.


text:
Q: Find text that appears multiple times (look for string most right in sheet) and copy I want to find the text "Locked" within Sheet1.
As the number of sales each week are locked down, the text "Locked" will appear in row 3.  The previous week's will all remain, therefore I am looking for code to find the "Locked" that appears most right in row 3.
Once that cell is detected I need to offset the selection to row 5 (same column) and copy to the bottom of the table.
The selection then needs to be pasted in cell M5.
If any more information is required, happy to provide.
Columns(13).ClearContents

Cells.Find(What:="LOCKED", LookIn:=xlFormulas, LookAt _
:=xlPart, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Select

ActiveCell.Offset(2, 0).EntireColumn.Select
Selection.Copy
Columns(13).Select
ActiveSheet.Paste

A: I believe the following will achieve what you are wanting:
Sub foo()
Dim ws As Worksheet: Set ws = ActiveSheet
'declare and set the worksheet you are working with, amend as required
Dim rng As Range

ws.Columns(13).ClearContents
'clear contents of Column M

Set rng = ws.Rows("3:3").Find(What:="LOCKED", LookIn:=xlFormulas, LookAt _
:=xlPart, SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False)
'set the rng variable to the last "LOCKED" found in Row 3

If Not rng Is Nothing Then 'if found
    LastRow = ws.Cells(ws.Rows.Count, rng.Column).End(xlUp).Row
    'get the last row with data in that column
    ws.Range(ws.Cells(3, rng.Column), ws.Cells(LastRow, rng.Column)).Copy
    'copy from row 3 to last row in found column
    ws.Range("M5").PasteSpecial xlPasteAll
    'paste into Range M5
End If

Application.CutCopyMode = False
'Escape the copied range
End Sub


text:
Q: Error in code - producing same result I have this code that I do not fully understand.  It is producing the same result.
The first section ('Return all the Account numbers that are greater than 250 days) works perfectly.  It take all the account numbers where the last payment date is greater than 250 days and returns the account numbers and corresponding days on to a new worksheet.
I need the next two sections (Return all the Account numbers that are 68 and older) and (Return all the Account numbers that are younger than 18), to return the account numbers where the age of the account holder is greater and equal to 68 , and those that are younger than 18.
This code is producing the same result for the 3 sections.  The page that the code is taking from, the columns used are ('A' account number, 'E' Days since last payment DSLP, and, 'C' Age)
Thanks in advance
'Populate the Recourse Items Sheet to provide the list of items for recourse

Dim DSLP As Range
Dim NewRange As Range
Dim MyCount As Long
MyCount = 1
Dim NewRange2 As Range
Dim MyCount2 As Long
MyCount2 = 1

'Return all the Account numbers that are greater than 250 days

    For Each DSLP In SFS.Range("E2:E" & LastRow)

        Select Case DSLP.Value

            Case Is > 250

                If MyCount = 1 Then
                    Set NewRange = DSLP.Offset(0, -4)

                Else
                   Set NewRange = Application.Union(NewRange, DSLP.Offset(0, -4))

                End If

               MyCount = MyCount + 1

'Return the corresponding days past 250

                If MyCount2 = 1 Then
                    Set NewRange2 = DSLP.Offset(0, -0)

                Else
                   Set NewRange2 = Application.Union(NewRange2, DSLP.Offset(0, -0))

                End If

               MyCount2 = MyCount2 + 1

        End Select

    Next DSLP

'Copy NewRange from inactive sheet into active sheet
 NewRange.Copy Destination:=RI.Range("A4")
 NewRange2.Copy Destination:=RI.Range("B4")

 Dim OLD As Range
 Dim NewRange3 As Range
 Dim MyCount3 As Long
 MyCount3 = 1
 Dim NewRange4 As Range
 Dim MyCount4 As Long
 MyCount4 = 1

'Return all the Account numbers that are 68 and older

    For Each OLD In SFS.Range("C2:C" & LastRow)

        Select Case OLD.Value

            Case Is >= 68

                If MyCount3 = 1 Then
                    Set NewRange3 = OLD.Offset(0, -2)

                Else
                   Set NewRange3 = Application.Union(NewRange3, OLD.Offset(0, -2))

                End If

               MyCount3 = MyCount3 + 1

'Return the corresponding ages 68 and older

                If MyCount4 = 1 Then
                    Set NewRange4 = OLD.Offset(0, -0)

                Else
                   Set NewRange4 = Application.Union(NewRange4, OLD.Offset(0, -0))

                End If

               MyCount4 = MyCount4 + 1

        End Select

    Next OLD

'Copy NewRange from inactive sheet into active sheet
    NewRange.Copy Destination:=RI.Range("D4")
    NewRange2.Copy Destination:=RI.Range("E4")

 Dim YOUNG As Range
 Dim NewRange5 As Range
 Dim MyCount5 As Long
 MyCount5 = 1
 Dim NewRange6 As Range
 Dim MyCount6 As Long
 MyCount6 = 1

'Return all the Account numbers that are younger than 18

    For Each YOUNG In SFS.Range("C2:C" & LastRow)

        Select Case YOUNG.Value

            Case Is < 18

                If MyCount5 = 1 Then
                    Set NewRange5 = YOUNG.Offset(0, -2)

                Else
                   Set NewRange5 = Application.Union(NewRange5, YOUNG.Offset(0, -2))

                End If

               MyCount5 = MyCount5 + 1

'Return the corresponding ages younger than 18

                If MyCount6 = 1 Then
                    Set NewRange6 = cell.Offset(0, -0)

                Else
                   Set NewRange4 = Application.Union(NewRange6, cell.Offset(0, -0))

                End If

               MyCount6 = MyCount6 + 1

        End Select

    Next YOUNG

'Copy NewRange from inactive sheet into active sheet
    NewRange.Copy Destination:=RI.Range("G4")
    NewRange2.Copy Destination:=RI.Range("H4")


text:
Q: Discovery of $E=hf$? How was the equation $E=hf$ discovered?
Was the proportional expression between energy and frequency of light $E\propto f$ discovered only by experiment? Or is there some logical(theoretical) senses affected?

A: The relationship $E = h f$ was proposed by Max Plank in 1899 or 1900 as a way to "fix" a major problem in the existing understanding of the how light was emitted by hot bodies (the so called "ultraviolet catastrophe"). The conventional story holds that Plank did not consider this as fundamental.1
Later Albert Einstein took the idea as a way to explain the photo-electric effect in 1905, bringing the principle that light energy actually came in discrete chucks to the forefront. This work was among that cited by the committee in awarding Einstien's Nobel prize.
The discovery of Compton Scattering in 1923 gave the "photon" a firm place in modern physics.
Quantum field theories eventual came to explain the photon as an excitation of the electromagnetic field.

1 I can't say if that is true or not, but it is the way the Lore goes.

A: Discrete spectral lines (frequencies) of atoms were known since long ago. So an emitted wave has a quite certain frequency. If an absorber has many "resonators", it is the resonance resonator who likely will absorb the wave entirely. But this exchange says nothing about the relationship of the wave energy and the wave frequency. Classically it is the amplitude square integrated over the space that gives the wave energy. So the Plank relationship is alien to classical notions. It was hard to accept and only experiments helped prove its universality.
The Plank law was first a fit bridging two experimental asymptotics. But it worked so well for different $T$ and with a unique $h$ that Plank started to "derive" this law and introduced those quanta. The original fit is one of those rare cases in Physics when the exact formula is extremely simple and can be guessed.


text:
Q: Using static variable in ASP.NET web-service like cross thread Is it possible to use it with everything like in threads, with locking?
Main idea is to track whether some web-method is already invoked by same user, so we want to block more than X calls in a minute. We would keep some data in relevant HashTable.

A: There is a big disadvantage of asp.net session. It locks executing same sessionId requests unless session is in ReadOnly state. I haven't use it in that way but it think it can solve your task.
ASP.NET Session State Overview

Concurrent Requests and Session State
Access to ASP.NET session state is exclusive per session, which means
  that if two different users make concurrent requests, access to each
  separate session is granted concurrently. However, if two concurrent
  requests are made for the same session (by using the same SessionID
  value), the first request gets exclusive access to the session
  information. The second request executes only after the first request
  is finished. (The second session can also get access if the exclusive
  lock on the information is freed because the first request exceeds the
  lock time-out.) If the EnableSessionState value in the @ Page
  directive is set to ReadOnly, a request for the read-only session
  information does not result in an exclusive lock on the session data.
  However, read-only requests for session data might still have to wait
  for a lock set by a read-write request for session data to clear.

A: ASP.NET Sessions are dependent on cookies, which are easily circumvented by malicious users. Since malicious users seem to be your problem, ASP.NET sessions aren't the solution.
You could write a wrapper class containing a static Dictionary<UserID, List<DateTime>> allowing operations on the dictionary only with 1-2 methods and properly locking it.
eg
class UserLogger
{
    private Dictionary<int, List<DateTime>> _visits;

    public bool AddPageVisit(int userID)
    {
       // lock dictionary
       // add or update entry for the user,
       // remove from all entries the datetimes older than a minute
       // remove entries without datetimes
       // check if number of datetimes for the user > max allowed
       // unlock dictionary
    }
}

class RestrictedController
{
   private static UserLogger _userLogger;
}

Disclaimer: I just wrote this pseudo-code in the answer, it may contain typo's.


text:
Q: Remove access to CNAME of application and allow access only to rerouted domain I have an application running on Elastic Beanstalk, which I can access using its CNAME: http://NameOfApp.eu-west-1.elasticbeanstalk.com/.
Using Route 53 I created an alias on a domain I bought and rerouted the traffic to it. I have also added an SSL and therefore can access the app on https://FooBar.com.
But while doing so, I thought app will not be available on its CNAME anymore, which is not the case. I want the app to be accessible only on the domain FooBar.com. Any help with arranging it like so would be great.


text:
Q: SF Service proxy calling stateless service instances In my SF application a stateful Worker service communicates with a stateless Logging service using service remoting. The stateful Worker service creates the Logging proxy in its constructor using ServiceProxy.Create<ILoggingService>(loggingServiceUri) and keeps the returned reference for its entire lifetime. There are  several stateless Logging service instances running on the cluster (i. e. Instance Count == -1). My question is:
Are calls to the ILoggingService proxy form the Worker service routed to different Logging service instances?

A: Yes, when you are using SF remoting to talk to a stateless service, your message will be delivered to a random instance. The proxy will keep track of healthy instances for you, and deal with transient errors.


text:
Q: How To Form this MySQL Query? I want to create a MySQL Query similar to
SELECT city, state, country FROM location
UNION
SELECT 'Chicago','Illinois', 'USA' IF 'Chicago' NOT IN (SELECT city FROM location);

Basically, if 'Chicago' is not returned in the results, I want to append it to the results. Problem is, the query expects a FROM table. Do I use a dummy table, or am I doing this all wrong?

A: Just write the second SELECT with no conditions and let the UNION do the work for you. UNION will remove duplicates from the result set, so there's no harm in repeating "Chicago" in the second query. If "Chicago" also occurs in your first SELECT, the UNION will remove the duplicate created by your second query.
SELECT city, state, country FROM location
UNION
SELECT 'Chicago','Illinois', 'USA'


text:
Q: Select column with only one negative value I'd like to select the columns that only have one negative value or none. How can I construct this looking at this example? I've been searching for something similar, didn't succeed though. Thanks for any help.
N = 5
np.random.seed(0)

df1 = pd.DataFrame(
          {'X':np.random.uniform(-3,3,N),
           'Y':np.random.uniform(-3,3,N),
           'Z':np.random.uniform(-3,3,N),
                })

          X         Y         Z
0  0.292881  0.875365  1.750350
1  1.291136 -0.374477  0.173370
2  0.616580  2.350638  0.408267
3  0.269299  2.781977  2.553580
4 -0.458071 -0.699351 -2.573784

So in this example I'd like to return columns X and Z.

A: Use np.sign to get the signs. Look for negative signs. Get the count of negative numbers for each column. Compare against the threshold of 1 to get a mask. Select the column names from the mask.
Hence, the implementation -
df1.columns[(np.sign(df1)<0).sum(0)<=1].tolist()

Or directly compare against 0 to replace the use of np.sign -
df1.columns[(df1<0).sum(0)<=1].tolist()

This gives us the column names. To select entire columns, other solutions I think have covered it.

A: You can use iloc to do that i.e
df1.iloc[:,((df1<0).sum(0) <= 1).values]

or (Thanks Jon)
df1.loc[:,df1.lt(0).sum() <= 1]

Output:

          X         Z
0  0.292881  1.750350
1  1.291136  0.173370
2  0.616580  0.408267
3  0.269299  2.553580
4 -0.458071 -2.573784

A: Or You can try :
df1.columns[(df1<0).sum(0).lt(1)]
Out[338]: Index(['X', 'Z'], dtype='object')


text:
Q: Matlab: How to sort a struct by one of its columns using another vector How can I order a struct in a way that one of its columns are equal to a certain vector? Below is an example which shows what I mean.
I have the following struct and vector:
% What I have:
my_struct = struct('value1', {4, 2, 1}, 'letters', {'CD', 'AB', 'XY'}, 'value2', {5, 3, 1});
% Looks like:
% 4   'CD'    5
% 2   'AB'    3
% 1   'XY'    1

my_cell_array = {'CD', 'XY', 'AB'};
% Looks like:
% 'CD' 'XY' 'AB'

Now I try to sort the struct in a way that the second column is in the same order as my_cell_array:
% What I try:
[~, my_order_struct] = sort({my_struct(:).letters});
% Gives:
% 2 1 3

my_struct_ordered_alphabetically = my_struct(my_order_struct);
% Gives:
% 2   'AB'    3
% 4   'CD'    5
% 1   'XY'    1

my_struct_ordered = my_struct_ordered_alphabetically(my_order_cell);
% Should give:
% 4   'CD'    5
% 1   'XY'    1
% 2   'AB'    3

However, I need to find my_order_cell for the last row of my code. Sort does not exactly do the trick here:
[~, my_order_cell] = sort(my_cell_array);
% Gives me: 3 1 2 (vector that can be used to sort the cell array alphabetically)
% What I need: 2 3 1 (vector with the alphabetical order of the cell array elements)

My exact question at this point is therefore: How do I extract the alphabetical order of a cell array (the 2 3 1 instead of the 3 1 2)?
I have to start with the above data types (struct and cell array), however, I would be willing to convert them to any other format if this would help.

A: I have to admit the answer is quite trivial now:
[~, my_order_cell] = sort(my_cell_array);
% Gives me: 3 1 2 (vector that can be used to sort the cell array alphabetically)

[~, my_order_cell2] = sort(my_order_cell);
% Gives me: 2 3 1 (vector with the alphabetical order of the cell array elements)


text:
Q: Removing and replacing the middle part of a string in bash I've a few strings:
Central and Western	Kwun Lung Lau

Central and Western	The Merton

Eastern	Fung Wah Estate

Wong Tai Sin	Tsz Oi Court

And I want to remove and replace the middle parts:
From:

I want to replace this entire part with the character:
;

I need my strings to become:
Central and Western;Kwun Lung Lau

Central and Western;The Merton

Eastern;Fung Wah Estate

Wong Tai Sin;Tsz Oi Court

How do I do this in a generic way?

A: If your strings are in a file called file:
$ sed 's|	]*">|;|g' file
Central and Western;Kwun Lung Lau
Central and Western;The Merton
Eastern;Fung Wah Estate
Wong Tai Sin;Tsz Oi Court

If your string is in a shell variable called s:
$ echo "$s"
Central and Western	Kwun Lung Lau
$ echo "$s" | sed 's|	]*">|;|g'
Central and Western;Kwun Lung Lau


text:
Q: JAXB - Namespace is not accepted I have in entry some XML with theses namespaces :
xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'

Unfortunately, for what I know, the
xmlns:z='#RowsetSchema'

Launch an error if I want to create classes with JAXB. I tried to change the namespace, but then when I want to unmarshall, JAXB said that he expect another namespace that he founds.
So I'm trying to find a solution to avoid this problem, and if possible doesn't want to dynamically change my namespaces...
Any suggestions ?


text:
Q: react native axios/fetch and UI run on same thread Does in react native axios/fetch and UI run on same thread. If I have a heavy upload when app comes to foreground will that impact UI interactions??
My app freezes whenever it comes in foreground. User can scroll but cannot tap on any button or navigate?
Know issue on Redmi Devices.

A: the axios/fetch are running on the Javascript thread


text:
Q: How do I use HTTP_ACCEPT_LANGUAGE to change the language on my Laravel application? I'm trying to change the language of my Laravel app when the user goes to any of its urls it has "/", "faq", "user/1/edit", I know I can use the request to find out about the server accepted language:
$locale = request->server('HTTP_ACCEPT_LANGUAGE');

And I'm already working on my resources/lang files.
Question is: If the user got a direct link to one of the pages and he is loading it, how do I change the language no matter what route they are going to and show the page in his language?

A: Create a Middleware assigned to all routes that should be translated and use the App::setLocale() with the correct value (I believe you want to get it from the browser's Accept-Language header)


text:
Q: Link EF to non database objects How can a create relationships with entity framework to non database objects. I generated my models and mappings with the power tools Here is the link of power tools.
This is mainly to accommodate for a lack of normalisation in a legacy system. I have a partial class setup in order to sustain any changes I make.
To elaborate:-
EfObject (generated from database) could have several addresses all in the same table (poor normalisation)
HomeAddressObject (Not to be stored in Database)
CorrespondanceAddressObject (Not to be stored in Database)
I want to relate to these objects with a means of possibly having them as database tables in the future, however for now they simply need to summarise the data in the main EfObject and make it more convenient to edit.

A: As CodeCaster suggested above. I was already using partial classes in order to persist my changes after code generation, however I was not familiar with the [NotMapped] attribute.
This has prevented EF from throwing it's toys out the pram!


text:
Q: Converting base64 Image to file object in JavaScript I am trying to create a file object from a base64 image which was cut from another image. I am able to do it but the resulting file size is almost thrice the actual size. Below is the function that I am using:
convertDataURItoFile(dataURI, fileName) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    // write the ArrayBuffer to a blob, and you're done
    var blob: any = new Blob([ia], { type: mimeString });

    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    blob.lastModifiedDate = new Date();
    blob.name = fileName;
    //Cast to a File() type
    return <File>blob;
  }

Any idea on why the file size increasing so drastically? How can I compress it? Thanks in advance.

A:
I am trying to create a file object from a base64 image which was cut
  from another image. I am able to do it but the resulting file size is
  almost thrice the actual size.

Cannot reproduce resulting .size of Blob being thrice the size of the content of input data URI. Do you mean the data URI .length can be thrice the size of Blob .size?

function convertDataURItoFile(dataURI, fileName) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ia], { type: mimeString });

    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    blob.lastModifiedDate = new Date();
    blob.name = fileName;
    //Cast to a File() type
    console.log(`input data size: ${datauriLength} Blob.size: ${blob.size}`);
    return blob;
  }

const [datauri, filename] = ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASoAAADCCAYAAAD+Wo90AAAABHNCSVQICAgIfAhkiAAAApVJREFUeJzt1DEBACAMwLCBf88ggZMeiYJeXTPnDEDY/h0A8GJUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkHcBRH8DgsmlTc8AAAAASUVORK5CYII=", "filename.png"];

const datauriLength = datauri.length;

const reader = new FileReader;
reader.onload = () => {
  console.log(`data URI: ${reader.result}`)
  document.querySelector("iframe").src = reader.result;
};

reader.readAsDataURL(convertDataURItoFile(datauri, filename));

If .name and .lastModifiedDate need to be added to Blob, you can substitute using File constructor for Blob, which expects file name parameter to be set at second parameter to File constructor, and optionally expected .lastModidied and or .lastModifiedDate parameters at third parameter to constructor.

function convertDataURItoFile(dataURI, fileName) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    // write the ArrayBuffer to a blob, and you're done
    // use `File` constructor here
    var blob = new File([ia], fileName, { type: mimeString, lastModifiedDate: new Date() });

    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    // blob.lastModifiedDate = new Date();
    // blob.name = fileName;
    //Cast to a File() type
    console.log(`input data size: ${datauriLength} Blob.size: ${blob.size}`);
    return blob;
  }

const [datauri, filename] = ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASoAAADCCAYAAAD+Wo90AAAABHNCSVQICAgIfAhkiAAAApVJREFUeJzt1DEBACAMwLCBf88ggZMeiYJeXTPnDEDY/h0A8GJUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkGdUQJ5RAXlGBeQZFZBnVECeUQF5RgXkGRWQZ1RAnlEBeUYF5BkVkHcBRH8DgsmlTc8AAAAASUVORK5CYII=", "filename.png"];

const datauriLength = datauri.length;

const reader = new FileReader;
reader.onload = () => {
  console.log(`data URI: ${reader.result}`)
  document.querySelector("iframe").src = reader.result;
};

reader.readAsDataURL(convertDataURItoFile(datauri, filename));

You can also utilize fetch() to create and get Blob representation of data URI, see Answer by @Endless at Creating a Blob from a base64 string in JavaScript


text:
Q: Regex for matching various forms of strings Let's say the input string is
s_in = 'auto encoder'

and the list of strings is
l_s = ['autoencoder', 'auto-encoder', 'auto', 'one']

My goal is to match s_in with its possible forms in l_s so that in return ill get all matched strings from the list.
In the example above the output must be ['autoencoder', 'auto-encoder']
Another example:
s_in = 'autoencoder'
l_s = ['auto-encoder', 'auto encoder', 'auto', 'one']

Output: ['auto-encoder', 'auto encoder']
Or
s_in = 'auto-encoder'
l_s = ['autoencoder', 'auto encoder', 'auto', 'one']

Output: ['autoencoder', 'auto encoder']
The regex I constructed looks like this:
re.match(r'^[a-zA-Z]+(?:(?:\s[a-zA-Z]+)+|(?:\-[a-zA-Z]+)|(?:[a-zA-Z]+))$', s)

It works well if I just iterate over list items, but doesn't work if I try to combine input string and list of strings.

A: You can compare the strings after removing all special characters, say, with [\W_]+ pattern:
import re
s_in = 'auto encoder'
l_s = ['autoencoder', 'auto-encoder', 'auto', 'one']

rx = re.compile(r'[\W_]+')  # Define the regex for non-alnum chars
s_check = rx.sub('', s_in)  # Input string without non-alnum chars
print( [x for x in l_s if s_check == rx.sub('', x)] ) # Print if equal after removing all non-alnum chars
# => ['autoencoder', 'auto-encoder']

See the Python demo.


text:
Q: How to make a test case ignore the constructor in xUnit? I have a test class that is using In Memory DB. So in the constructor we create the db context and pass it to the service constructor so that we can use this service instance in every test case:
private readonly IService _service;
private readonly Context _context;

public MyTestClass() {
    _context = CreateContext();
    _service = new Service(_context);
}

However, I would like to ignore that constructor setup in one specific test case so that I can populate the context the way I need and instantiate the service with that recently created context for that specific test case. Is it possible?

A: There is no proper way to get a TestContext that would let you know which test it's for within the constructor.
Best thing you can do is put another Test Class alongside (could even be in the same file) that houses the single test that needs the different behavior.
Alternately, if you do change _service to Lazy<IService> and do _service=new Lazy<IService>(() => new Service(CreateContext())), then you can have all but one test trigger the initialization with var service = service.Value` at the start of each test.