text:
Q: Which constructor is getting called for below string code? I was reading c++ primer and came across an example of list initialization for vector where the author mentioned that if list initialization isn't possible, the compiler then looks for other ways to initialize the object. Below is such an example for vector of string.
vector<string> v8{10, "hi"};

This creates a vector of 10 elements with value "hi". This I think is because list initialization falls back on below constructor to create the vector.
vector( size_type count, const T& value, const Allocator& alloc = Allocator());

I tried similar kind of list initialization for String
std::string s1{10, 'c'};

I was expecting it to create a string "cccccccccc" because there is a constructor available for it
basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );

But it prints only "c"? Which string constructor is getting used here?

A: The constructor taking std::initiazer_list gets called.
constexpr basic_string( std::initializer_list<CharT> ilist,
                        const Allocator& alloc = Allocator() );

10 is an int, which could convert to char implicitly, and std::initializer_list<char> could be constructed from {10, 'c'} as containing two chars, the 1st one with ASCII value 10, the 2nd one as c.
On the other hand for std::vector<std::string>, {10, "hi"} can't be used to construct std::initializer_list<std::string> since 10 can't be converted to std::string, then the constructor taking std::initializer_list<std::string> won't be used.

A: What's coming into play here are the rules for direct-list-initialization which has one of the syntax as
T object { arg1, arg2, ... };

Here, in the case of std::string s{10, 'c'}, T in the above syntax is std::string and the rule that applies is

Otherwise, the constructors of T are considered, in two phases: All
constructors that take std::initializer_list as the only argument, or
as the first argument if the remaining arguments have default values,
are examined, and matched by overload resolution against a single
argument of type std::initializer_list

Since there is a constructor of std::string that takes in an initializer list with the other arguments as default, namely constructor (9)
basic_string( std::initializer_list<CharT> ilist,
              const Allocator& alloc = Allocator() );

that participates in this resolution since 10 can be implicitly converted to char and what you get is a std::initializer_list<char> of {'\n', 'c'} of 2 characters.

In the case of std::vector<std::string> v{10. "hi"}, T is std::vector<std::string> in the syntax for direct-list-initialization as mentioned above.
Now, since 10 can't be implicitly converted to std::string, no such std::initializer_list<std::string> can be constructed and thus the next alternative for direct-list-initialization is

If the previous stage does not produce a match, all constructors of T
participate in overload resolution against the set of arguments that
consists of the elements of the braced-init-list, with the restriction
that only non-narrowing conversions are allowed.

This produces a match with constructor 3
explicit vector( size_type count,
                 const T& value = T(),
                 const Allocator& alloc = Allocator());

since neither of the conversions is non-narrowing.

Now coming to what you wanted to achieve with std::string s{10, 'c'}, that should be done using std::string s(10, c) where there is no list-initialization involved.
std::string s1{10, 'c'}, s2(10, 'c');
std::cout<<'['<<s1<<']'<<'['<<s2<<']'<<'\n';

Output:
[
c][cccccccccc]

Note that printing s1 produces a new line before the c since it's actually ['\n', 'c'], whereas s2 is exactly what you'd expect i.e. 10 c characters.


text:
Q: Using mfirstuc with hyperref I need to change the first letter in part of a link to uppercase. While I can easily do this for the label with \makefirstuc, I can't make it to work in the link itself. In the MWE below, the label is correctly changed from testname to Testname but the link becomes https://someaddresss/\makefirstuc {testname}.py
\documentclass{article}
\usepackage{mfirstuc}
\usepackage{hyperref}

\newcommand{\addlink}[1]
{
\href{https://someaddress/\makefirstuc{#1}.py}{\makefirstuc{#1}.py}
}

\begin{document}

    \addlink{testname}

    Label is changed as expected from \verb+testname+ to \verb+Testname+.

    Link stays \verb+https://someaddresss/\makefirstuc {testname}.py+
\end{document}

MWE output is:

Testname.py
Label is changed as expected from testname to Testname.
Link stays https://someaddresss/\makefirstuc {testname}.py

I suspect there is an easy answer, but I cannot find it... Thanks!

A: \documentclass[11pt]{book}

\usepackage{hyperref}

\ExplSyntaxOn
\cs_set_eq:NN\texttitlecasefirst\text_titlecase_first:n
\ExplSyntaxOff
\begin{document}

\href{https://someaddress/\texttitlecasefirst{blub}.py}{\texttitlecasefirst{blub}.py}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Large(5977x8340) canvas not showing on ios I am trying to display a canvas size 5977x8340 on a page and it is showing correctly on desktop and android but not showing on iPhone(safari,chrome). I have tried with less size like 854x1192 and it's working fine.
I have to show canvas with 5977 x 8340 size in iPhone as well. Please help me where i am doing wrong.


text:
Q: Determining decimal precision of a floating point number I have been searching the internet for days now and can't seem to find a generally accepted formula for determining the number of decimal digits that we can store in a floating point format without truncation error. The answer I came across the most often was:
Decimal precision = log₁₀(2ⁿ), where n = the number of bits in the mantissa.
Now, this lines up with everything I've seen with the single point and double point formats discussed in my CS book.
However, when I went to check this against the examples in my CS book, the numbers didn't line up.
The examples used an 8-bit format with a 4 bit mantissa. Given the formula above, I should only be able to store a decimal value with precision of up to 1.2 digits. However, according to the book (and confirmed by trying other decimal values) I can store a value such as 2.25 in a 4 bit mantissa with out truncation. 0.0625 can be stored as well without error. In both of these cases, the decimal digits exceed the 1.2 given from the equation above.
I can't help but wonder if there is something I am missing. Is there a way to determine decimal precision given a mantissa of any size? Does the formula above conflict with mantissa fields below a certain size?
Any clarity on the matter would be greatly appreciated.
Danny D.

A:
a generally accepted formula for determining the number of decimal digits that we can store in a floating point format without truncation error.

Research FLT_DIG, DBL_DIG, LDBL_DIG.  They are the number of significant decimal digits (as in text) that can be rounded into a floating-point type and back again for float, double, long double.
With binary bases and to generalize for OP, use
floor((significant_bits - 1) log10(base))

With base == 2 and a significant_bits == 5 bit signicand (4 explicitly encoded, 1 implied), this is floor(1.204...) or 1.
This means with decimal numbers of the form w.000 * 10power, all combinations of w (1-9) and power (in a min/max range) would "round-trip" from decimal text to OP_s_Floating_point_type to decimal text successfully.
If one tried to round-trip decimal text of the form w.y00 * 10power, for some combination of w,y, a failure would occur.  It does not mean all combinations of that form would fail, just some.
Consider trying to take decimal text "9.0", "9.1", "9.2", ... "9.9" and convert those 10 to OP's FP format.  In the 9 range, that format only supports encoding 9.0 and 9.5.  So mapping those 10 numbers would result in 2 different FP numbers.  Of course converting those 2 back to decimal form results in only 2 different answers.  The round-trip failed for 8 of those 10.

if there is something I am missing.
  Is there a way to determine decimal precision given a mantissa of any size?

The value of 1 derived from the above formula is the worst case and the worst case is the number usually reported for decimal precision.


text:
Q: Validate kannel configuration (aside from running kannel) Is there a way to make sure that a certain Kannel configuration is consistent?
Probably I could write a script that checks that all parameter groups have exactly one
'group = '

all mandatory groups are present, all included files are present and valid themselves, etc.
However, maybe there's a standard way already?

A: In Kannel configuration file, there are many groups for different purposes.
For admin details.
group = core

for modems where you define your USB modem configurations.
group = modems

If you are looking for a complete configuration file. You can get a complete configuration file from here.


text:
Q: How to assert Map contains Map with entry I have a unit test that needs to check for a nested map value.  I can get my assertion to work by pulling out the entry and matching the underlying Map, but I was looking for a clear way to show what the assertion is doing.  Here is a very simplified test:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class MapContainsMapTest {
    @Test
    public void testMapHasMap() {
        Map<String, Object> outerMap = new HashMap<String, Object>();
        Map<String, Object> nestedMap = new HashMap<String, Object>();
        nestedMap.put("foo", "bar");
        outerMap.put("nested", nestedMap);

        // works but murky
        assertThat((Map<String, Object>) outerMap.get("nested"), hasEntry("foo", "bar"));
        // fails but clear
        assertThat(outerMap, hasEntry("nested", hasEntry("foo", "bar")));
    }
}

It seems the problem is the outer map is being compared using hasEntry(K key, V value) while what I want to use is hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher).  I am not sure how to coerce the assertion to use the second form.
Thanks in advance.

A: If you only want to put Map<String, Object> as values in your outerMap adjust the declaration accordingly. Then you can do
@Test
public void testMapHasMap() {
    Map<String, Map<String, Object>> outerMap = new HashMap<>();
    Map<String, Object> nestedMap = new HashMap<String, Object>();
    nestedMap.put("foo", "bar");
    outerMap.put("nested", nestedMap);

    Object value = "bar";
    assertThat(outerMap, hasEntry(equalTo("nested"), hasEntry("foo", value)));
}

Object value = "bar"; is necessary for compile reasons. Alternatively you could use
assertThat(outerMap,
   hasEntry(equalTo("nested"), Matchers.<String, Object> hasEntry("foo", "bar")));

A: If You declare outerMap as Map<String, Map<String, Object>> you don't need the ugly cast. Like this:
public class MapContainsMapTest {

    @Test
    public void testMapHasMap() {
        Map<String, Map<String, Object>> outerMap = new HashMap<>();
        Map<String, Object> nestedMap = new HashMap<>();
        nestedMap.put("foo", "bar");
        outerMap.put("nested", nestedMap);

        assertThat(outerMap.get("nested"), hasEntry("foo", "bar"));
    }
}

A: I would probably extend a new Matcher for that, something like that (beware, NPEs lurking):
class SubMapMatcher extends BaseMatcher<Map<?,?>> {

private Object key;
private Object subMapKey;
private Object subMapValue;

public SubMapMatcher(Object key, Object subMapKey, Object subMapValue) {
    super();
    this.key = key;
    this.subMapKey = subMapKey;
    this.subMapValue = subMapValue;
}

@Override
public boolean matches(Object item) {

    Map<?,?> map = (Map<?,?>)item;

    if (!map.containsKey(key)) {
        return false;
    }

    Object o = map.get(key);

    if (!(o instanceof Map<?,?>)) {
        return false;
    }

    Map<?,?> subMap = (Map<?,?>)o;
    return subMap.containsKey(subMapKey) && subMap.get(subMapKey).equals(subMapValue);
}

@Override
public void describeTo(Description description) {
    description.appendText(String.format("contains %s -> %s : %s", key, subMapKey, subMapValue));
}

public static SubMapMatcher containsSubMapWithKeyValue(String key, String subMapKey, String subMapValue) {
    return new SubMapMatcher(key, subMapKey, subMapValue);
}

}

A: Try like this :
        assertThat(nestedMap).contains(Map.entry("foo", "bar"));
        assertThat(outerMap).contains(Map.entry("nested", nestedMap));


text:
Q: Can not connect to localhost while trying to run a dockerized spring application I have created a spring boot application. This works fine in localhost. But upon dockerizing the project I am facing issues in connecting to the localhost. Even in the CLI of the docker CLI it says:
sh-4.4# curl localhost:2008/store/products
curl: (7) Failed to connect to localhost port 2008: Connection refused

Yet I am getting no errors in the terminal. Whenever I try to access through localhost:2008/store/products there is no change in the terminal.
Controller
package org.assignments.dockerize;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "/store/")
class ProductsCategoriesController {

    private final ProductsService productsService;
    private final CategoryService categoryService;

    @Autowired
    public ProductsCategoriesController(ProductsService productsService, CategoryService categoryService) {
        this.productsService = productsService;
        this.categoryService = categoryService;
    }

    @GetMapping(path = "/products")
    public List<Products> getProducts() {
        return productsService.getProducts();
    }
    @PostMapping(path = "/products")
    public Products addNewProduct(@RequestBody Products product) {
        return productsService.addNewProduct(product);
    }

    @GetMapping(path = "/products/{id}")
    public List<String> findProductByCategoryID(@PathVariable("id") Integer id) {
        return productsService.getProductsByCategoryID(id);
    }

    @GetMapping(path = "/categories")
    public List<Categories> getCategories() {
        return categoryService.getCategories();
    }
    @PostMapping(path = "/add/categories")
    public void addNewCategory(@RequestBody Categories category) {
        categoryService.addNewCategory(category);
    }
}

build.gradle
plugins {
    id 'org.springframework.boot' version '2.5.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'org.assignments'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'
def versionLog4j = '2.14.1'
def versionLombok = '1.18.20'
repositories {
    mavenCentral()
}

dependencies {
    implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: versionLog4j
    implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: versionLog4j
    implementation group: 'org.projectlombok', name: 'lombok', version: versionLombok
    annotationProcessor group: 'org.projectlombok', name: 'lombok', version: versionLombok
//    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'org.postgresql:postgresql'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

tasks.withType( JavaCompile ).configureEach {
    options.forkOptions.jvmArgs.addAll( ['--add-opens', 'jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED'] )
}

Dockerfile
FROM openjdk:16
EXPOSE 8899
ADD Assignment-14a/build/libs/*.jar dockerstore.jar
ENTRYPOINT ["java","-jar","dockerstore.jar"]

application.properties
server.port = 8090
spring.datasource.url = jdbc:postgresql://<myIP>:2006/store
spring.datasource.username = postgres
spring.datasource.password = *****
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql = true

Code to create image
docker build -f Assignemnt-14a/Dockerfile -t storeimage .

Code to run the container
docker run -p 8085:8085 docker-spring-boot

The container gets created successfully. The port is also shown.
C:\Users\master\Projects>docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS          PORTS                                       NAMES
3a3ad3d11b63   storeimage        "java -jar dockersto…"   31 minutes ago   Up 31 minutes   0.0.0.0:2008->8899/tcp, :::2008->8899/tcp   jovial_rosalind
4c7d9b67a7ac   postgres:latest   "docker-entrypoint.s…"   2 weeks ago      Up 2 hours      0.0.0.0:2006->5432/tcp, :::2006->5432/tcp   zs-intern-pgsql

C:\Users\master\Projects>docker port jovial_rosalind
8899/tcp -> 0.0.0.0:2008
8899/tcp -> :::2008

But when I try to open localhost:2008/store/products, it says This page isn't workinglocalhost didn't send any data. ERR_EMPTY_RESPONSE

A: It is hard to investigate the problem you are facing without having sources. The only thing I can suggest is to try to replace docker run -p 8085:8085 docker-spring-boot with docker run -p localhost:8085:localhost:8085 docker-spring-boot. Please let me know if it works.


text:
Q: Looping through a directory to find matching files I have a module that iterates through a directory and finds matching files, then does a transformation and sends an email. The module takes in the following command arguments:
startDate, endDate, and fundCodes and the format it will search for, will end up being something like this:
citco_unmapped_positions_PUPSEN_2018-07-01_2018-07-09.csv
My issue at the moment, is that the fundCodes argument will be an array of funds:
['PUPSEN', 'POSUF', 'AGE']
Which causes an issue in the following method:
def positions_file_search(self, fundCodes):
    # Get a list of the files
    files = set(os.listdir(self.unmappedDir))
    # loop through all the files and search for matching file
    for check_fund in fundCodes:
        # set a file pattern
        file_match = 'citco_unmapped_positions_{fund}_{start}_{end}.csv'.format(fund=check_fund, start=self.startDate, end=self.endDate)
        # look in the unmappeddir and see if there's a file with that name
        if file_match in files:
            # if there's a match, load unmapped positions as etl
            filename = os.path.join(self.unmappedDir, file_match)
            return self.read_file(filename)
        else:
            Logger.error('No file found with those dates/funds')

The problem with the method above is that it returns as soon as it finds a matching file and doesn't go through the rest of the funds.
I'm currently calling it like this in my __main__.py page:
unmapped_positions = alerter.positions_file_search(alerter.fundCodes)
    ... does something afterwards
It's working but, I need to figure out a way to do the same processing for each fund.
NOTE: I can't do something like:
for fund in alerter.fund:
     alerter.positions_file_search(fund)
    etc...

Since the email formatting would be repeated for each fund. I need to somehow modify my method instead. Any suggestions would be appreciated.

A: You could turn your function into a generator by replacing
return self.read_file(filename)

with
yield self.read_file(filename)

This would allow you to write:
for unmapped_positions in alerter.positions_file_search(alerter.fundCodes):
   ...

For more information on generators, see https://wiki.python.org/moin/Generators


text:
Q: Sentencia "else if" no funciona Tengo esta función para procesar una base de datos que estoy utilizando, el tema es que el resultado solo clasifica todo como "público" y parece no detecta la otra condición, ¿alguna sugerencia?
sectorlaboral = function (funcionariopublicoinstitucion) {
  if(becal_completo$funcionariopublicoinstitucion!="NO")
    return("publico")
  else if(becal_completo$funcionariopublicoinstitucion=="NO")
    return("privado")
}

La variable es "pertenencia a una institucion publica" entonces las respuestas son o "no" o el nombre de la institucion. Como tengo que calcular la cantidad de personas pertenecientes al sector privado y al publico estoy creando una nueva columna que clasifique los no como privado y lo demas como publico.

A: Eventualmente no necesitás hacer una función nueva para lo que buscas, puede utilizar la función base ifelse() de la siguiente forma:
becal_completo$Institucion <- ifelse(becal_completo$funcionariopublicoinstitucion == "NO", "privado", "publico")

A: Encontre la solucion, por si sirva a alguien, el problema era como indique mi variable dentro de la funcion, no hacia falta hacer referencia al dataframe con $:
sectorlaboral = function (funcionariopublicoinstitucion) {

  if (funcionariopublicoinstitucion=="NO" | funcionariopublicoinstitucion=="NO ")

    return ("privado")

 else

    return ("publico")
}


text:
Q: WCF service to multiple endpoints How do I go about making sure that my WCF service can be accessed from any other language(Java, PHP, whatever iOS uses, etc.)?
I have kept everything as httpbinding plus not used any of the .net roles/membership authentication for the clients. But there are some things that I am not sure of. Like, can I return a generic List that is readable by those other languages?

A: You cannot be 100% sure if you don't have any control over the client technology that is used to consume your services. But you can be very confident if your web service (WSDL) conforms to the WS-I basic profile v1.1. This standard is very widely supported and mature. You can use the excellent SoapUI test tool to test your WSDL for conformance.

A: Any of the WCF bindings that don't start with net (netTcp, netMsmq etc.) should be fine - they're designed to be interoperable.
The most basic one is basicHttpBinding which is pretty much plain HTTP - nothing much can be added to it. You should be able to call this from any scripting language (PHP etc.).
The more advanced binding is wsHttpBinding which implements lots of the WS-* standards and can be called from other languages where the networking stack can handle WS-* - stuff like Java etc.
And then there's the webHttpBinding which exposes your service not via SOAP, but via a REST endpoint. This should be callable from just about any language, any device, any place.
And of course, you get the best coverage if you expose multiple endpoints from your service, offering a variety of choices to anyone trying to call you. All this is done simply in config - no code change necessary to support multiple endpoints, multiple bindings etc.
As for lists and stuff: WCF exchanges serialized messages - basically XML - which is governed by a XML schema. The combination of a WSDL and XSD is totally interoperable and can be understood by a wide variety of other languages.
A List<T> in .NET will be turned into an array in your XML structure, and that's totally interoperable - don't worry. The client might just get back an array instead of a list  - but that's not a problem.
The only problem is that you cannot really model a generic list, since the XML schema doesn't support generics - you need to be explicit about what it is you're sending back. A List<T> won't work - a List<Customer> will (if your Customer object is part of your data contract and marked as such)


text:
Q: Run CPanel from account domain We have one server running WHM/CPanel with quite a few (~60) low traffic sites we can't be bothered to put on a proper hosting platform.
CPanel is accessible on every domain at http://example.com/cpanel, however this redirects to http://servers-fqdn:2083/. I've worked on other CPanel servers where the /cpanel link redirects to http://example.com:2083/ so each CPanel is running under its own domain but I couldn't seem to find any documentation on how to get this to work.
Two reasons this would be useful;

*

*I frequently access the CPanel sites, but because they all redirect to the servers main hostname (and CPanel uses HTTP authentication) I can only save one username/password combination, having it on different domains would let me save each username/password individually.

*I would look better when our actual users log on, since the servers primary (FQDN) is reeaaallllly long

So yeah this is more for convenience than anything practical but still.
Short form;
Lots of sites with CPanel but when accessing it
http://example1.com/cpanel redirects to http://server-fqdn:2083/
http://example2.com/cpanel redirects to http://server-fqdn:2083/
[etc]

we want
http://example1.com/cpanel redirects to http://example1.com:2083/
http://example2.com/cpanel redirects to http://example2.com:2083/

Full root access to the server (I'm a real sysadmin, but users like CPanel), WHM version WHM 11.30.5, RedHat Enterprise Linux 5.5

A: The reason why it redirects to the server hostname is so that you only have to get one SSL certificate. It is recommended to keep it at the hostname and force SSL.
That said to make it so that you can have it the way you wanted.
Login to WHM > Tweak Settings > Redirection

*

*Always redirect to SSL = OFF

*Non-SSL redirect destination = Origin Domain Name

*SSL redirect destination = SSL Certificate Name


text:
Q: Access specified product on custom URL Greetings StackExchange.
I' have a task where I cannot google anything on the subject.
I want to create a copy of the standard Magento product view but it should be accessible on a custom URL.
I have created a small module that loads up a empty template page on the URL myshop.test/productoftheday.
Is there a way i can use the following to my benefit?

*

*I have succeeded to reuse the layout and template files of catalog_product_view.

*In my php-error.log the following is showing:

Uncaught Error: Call to a member function getId() in
  /app/code/core/Mage/Review/Block/Product/View/List.php:40"

*Is there anything in the controller app/core/mage/catalog/controllers/productcontroller I can use to load the view correct regarding list item 2?

A: In your Block file, you can create below function
public function getProdcut() {
    $productId = 11; //your specific prodcut ID
    $product = Mage::getModel('catalog/product')->load($productId);
    return $product;
}

Now in your new layout PHTML file, you should get your product like below
<?php $product = $this->getProdcut() ?>

Here it's your specific product.
$product


text:
Q: Word decomposition algorithm Let A be a finite alphabet and A* the set of all the finite strigns you can form from that alphabet. You are then given a set F of some strings from A* (tipically a lot smaller than A*) that contains the alphabet itself (A), and a string S beloging to A*.
Is there a polynomial time algorithm to find the minimum decomposition of S in terms of strings that belong to F?
By decomposition I mean a writing of S = F1...Fk of concatenated strings Fj that belong to F, and you are trying to minimize the number k.

A: We can solve this in polynomial time using dynamic programming as follows.
Let D[i] be the minimum decomposition of the first i letters i of your string S.
If n is the length of S, and f is the total length of all strings in F, we can compute D in time O(n.f) by iterating over i.
For each value of i we try all choices in F for the end of the string and pick the one that results in the minimum decomposition.
Once we have done this, the answer to the original question is contained in D[n].
Python code
F=['abcd','de','a','b','c','d']
S='abcde'

D = [ [] ]
for i in range(1,len(S)+1):
    s = S[:i]
    best = None
    for f in F:
        if s.endswith(f):
            a = D[i-len(f)]
            if a is None:
                continue
            if best is None or len(a) < len(best):
                best = a + [f]
    D.append(best)

print D[len(S)]

prints:
['a', 'b', 'c', 'de']


text:
Q: Error while coloring the table I am trying to color the rows in the table. I used both \cellcolor{blue!25} and \rowcolor options.
The packages are included in the main file are given below...
\usepackage{color}
\usepackage{xcolor}

but it shows the error as "Undefined control sequence".
can anybody tell how to solve my problem...

A: You don't need to load color and xcolor (just xcolor if you want the ! syntax) The table colour commands are defined in colortbl which you can load explicitly or, better in this case, by adding [tables] option to xcolor


text:
Q: Add a Java file in a Jpanel of another file I have 2 Java files, the first one is the main java code behind the program. And second is a jfx.Webview. I've been trying for forever to include the jfx.Webview in a JPanel that I have on the first Java file. I'm new to Java, and it's definitely not as easy as i thought. Please, if someone with a better understanding could explain to me the proper way to get this done, that would be of great help.
Here are the 2 Java files after some cleaning up:
public class Xzibit07 {

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

private static void generateUI(){

    XzibitUI program = new XzibitUI();
    program.setVisible(true);
    program.setTitle("Xzibit");

    ImageIcon logoIcon = new ImageIcon(new ImageIcon("Data/Images/Logo.jpg").getImage().getScaledInstance(program.logoLabel.getWidth(), program.logoLabel.getHeight(), Image.SCALE_DEFAULT));
    program.logoLabel.setIcon(logoIcon);
    program.logoLabel.setBounds((program.logoPanel.getWidth()/2 - program.logoLabel.getWidth()/2), 0, 0, 0);

    ImageIcon settingsIcon = new ImageIcon(new ImageIcon("Data/Images/Settings.png").getImage().getScaledInstance((program.logoPanel.getHeight()/4), (program.logoPanel.getHeight()/4), Image.SCALE_DEFAULT));
    program.settingsLabel.setIcon(settingsIcon);

    program.getContentPane().setBackground(Color.WHITE);
    program.logoPanel.setBackground(Color.WHITE);
}
}

And the second:
public class XzibitWeb implements Runnable {

public String webPage = "http://www.example.com";

public static void main(String[] args) {

    SwingUtilities.invokeLater(new XzibitWeb());

}

@Override
public void run() {

    JFXPanel jfxPanel = new JFXPanel();

    Platform.runLater(() -> {

        WebView view = new WebView();
        jfxPanel.setScene(new Scene(view, 1024, 400));
        view.getEngine().load(webPage);
    });
    }
}

A: I think you are trying to do this
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm
From your code i think you are not adding the jfxPanel to the frame.


text:
Q: Самый простой способ очистить List от дубликатов по конкретной проперти например
List<Student> StudentsGroup = new List<Student>();

StudentsGroup.add(new Student(){Name="Vasia", Surname="Andrienko"});
StudentsGroup.add(new Student(){Name="Vasia", Surname="Potapenko"});
StudentsGroup.add(new Student(){Name="Fedia", Surname="Matsenko"});
StudentsGroup.add(new Student(){Name="Kolia", Surname="Mischenknko"});
StudentsGroup.add(new Student(){Name="Vasilisa", Surname="Vynnychenko"});
StudentsGroup.add(new Student(){Name="Vasilisa", Surname="Onoprienko"});

после очистки по Name должно выдать только следующие данные
{Name="Vasia", Surname="Andrienko"}//иль второго студента
{Name="Fedia", Surname="Matsenko"}
{Name="Kolia", Surname="Mischenknko"}
{Name="Vasilisa", Surname="Vynnychenko"}//иль второго студента

A: Без использования сторонних библиотек
StudentsGroup = StudentsGroup.GroupBy(x => x.Name).Select(x => x.First()).ToList();

Взято с англоязычного SO

A: Еще один вариант, воспользоваться перегрузкой Distinct, принимающей вторым параметром IEqualityComparer<T>
Например:
class StudentComparer : IEqualityComparer<Student>
{
    // Students are equal if their names are equal.
    public bool Equals(Student x, Student y)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the Student's properties are equal.
        return x.Name == y.Name;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(Student student)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(student, null)) return 0;

        //Get hash code for the Name field if it is not null.
        return student.Name == null ? 0 : student.Name.GetHashCode();
    }
}

Пример использования:
IEnumerable<Student> noduplicates = StudentsGroup.Distinct(new StudentComparer());

A: Можно воспользоваться перегрузкой метода Distinct, принимающей IEqualityComparer<T>
Вместо полной реализации IEqualityComparer<Student> можно делегировать все стандартной реализации, оставив себе только обращение к свойству Name:
class StudentByNameComparer : IEqualityComparer<Student> {
  private readonly IEqualityComparer<string> cmp;

  public StudentByNameComparer(IEqualityComparer<string> cmp) {
    this.cmp = cmp;
  }

  public static StudentByNameComparer Default { get; }
      = new StudentByNameComparer(EqualityComparer<string>.Default);
      // Также тут можно использовать StringComparer

  public bool Equals(Student x, Student y)
      => cmp.Equals(x?.Name, y?.Name);

  public int GetHashCode(Student x)
      => cmp.GetHashCode(x?.Name);
}

Пример использования:
IEnumerable<Student> noduplicates = StudentsGroup.Distinct(StudentByNameComparer.Default);

A: Если коллекцию формируете вы, и свойство для проверки всегда одно, используйте HashSet для этих целей, и дубликаты просто не добавятся. Не забудьте, что надо будет переопределить GetHashCode для составления хэша только по изменяющемуся свойству
class Student
{
... /// существующий код
     public override int GetHashCode()
     {
          unchecked
          {
             int hash = 13; // любое простое число
              return 13* Name.GetHashCode();
          }
     }
}


text:
Q: Make a simple fade in animation in Swift? I am trying to make a simple animation in Swift. It is a fade in.
I attempted:
self.myFirstLabel.alpha = 0
self.myFirstButton.alpha = 0
self.mySecondButton.alpha = 0

Then, I have:
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(mySecondButton)

And then:
UIView.animateWithDuration(1.5, animations: {
 self.myFirstLabel.alpha = 1.0
 self.myFirstButton.alpha = 1.0
 self.mySecondButton.alpha = 1.0
})

I have all of this in my viewDidLoad function.
How do I make this work?

A: Swift only solution
Similar to Luca's anwer, I use a UIView extension. Compared to his solution I use DispatchQueue.main.async to make sure animations are done on the main thread, alpha parameter for fading to a specific value and optional duration parameters for cleaner code.
extension UIView {
  func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
    DispatchQueue.main.async {
      UIView.animate(withDuration: duration) {
        self.alpha = alpha
      }
    }
  }

  func fadeIn(_ duration: TimeInterval = 0.3) {
    fadeTo(1.0, duration: duration)
  }

  func fadeOut(_ duration: TimeInterval = 0.3) {
    fadeTo(0.0, duration: duration)
  }
}

How to use it:
// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn()     // uses default duration of 0.3
yourView.fadeIn(1.0)  // uses custom duration (1.0 in this example)

// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut()    // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)

// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5)  // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)

A: If you want repeatable fade animation you can do that by using CABasicAnimation like below :
First create handy UIView extension :
extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:
    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

A: 0x7ffffff's answer is ok and definitely exhaustive.
As a plus, I suggest you to make an UIView extension, in this way:
public extension UIView {

  /**
  Fade in a view with a duration

  - parameter duration: custom animation duration
  */
  func fadeIn(duration duration: NSTimeInterval = 1.0) {
    UIView.animateWithDuration(duration, animations: {
        self.alpha = 1.0
    })
  }

  /**
  Fade out a view with a duration

  - parameter duration: custom animation duration
  */
  func fadeOut(duration duration: NSTimeInterval = 1.0) {
    UIView.animateWithDuration(duration, animations: {
        self.alpha = 0.0
    })
  }

}

Swift-3
/// Fade in a view with a duration
///
/// Parameter duration: custom animation duration
func fadeIn(withDuration duration: TimeInterval = 1.0) {
    UIView.animate(withDuration: duration, animations: {
        self.alpha = 1.0
    })
}

/// Fade out a view with a duration
///
/// - Parameter duration: custom animation duration
func fadeOut(withDuration duration: TimeInterval = 1.0) {
    UIView.animate(withDuration: duration, animations: {
        self.alpha = 0.0
    })
}

Swift-5
public extension UIView {

/**
 Fade in a view with a duration

 - parameter duration: custom animation duration
 */
 func fadeIn(duration: TimeInterval = 1.0) {
     UIView.animate(withDuration: duration, animations: {
        self.alpha = 1.0
     })
 }

/**
 Fade out a view with a duration

 - parameter duration: custom animation duration
 */
func fadeOut(duration: TimeInterval = 1.0) {
    UIView.animate(withDuration: duration, animations: {
        self.alpha = 0.0
    })
  }

}

In this way you can do this wherever in your code:
let newImage = UIImage(named: "")
newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0)
self.view.addSubview(newImage)
...
newImage.fadeIn()

Code reuse is important!

A: The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.
What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

A: Swift 5
Other answers are correct, but in my case I need to handle other properties also (alpha, animate, completion). Because of this, I modified a bit to expose these parameters as below:
extension UIView {
    /// Helper function to update view's alpha with animation
    /// - Parameter alpha: View's alpha
    /// - Parameter animate: Indicate alpha changing with animation or not
    /// - Parameter duration: Indicate time for animation
    /// - Parameter completion: Completion block after alpha changing is finished
    func set(alpha: CGFloat, animate: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
        let animation = { (view: UIView) in
            view.alpha = alpha
        }

        if animate {
            UIView.animate(withDuration: duration, animations: {
                animation(self)
            }, completion: { finished in
                completion?(finished)
            })
        } else {
            layer.removeAllAnimations()
            animation(self)
            completion?(true)
        }
    }
}

A: import UIKit

/*
 Here is simple subclass for CAAnimation which create a fadeIn animation
 */

class FadeInAdnimation: CABasicAnimation {
    override init() {
        super.init()
        keyPath = "opacity"
        duration = 2.0
        fromValue = 0
        toValue = 1
        fillMode = CAMediaTimingFillMode.forwards
        isRemovedOnCompletion = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

/*
 Example of usage
 */

class ViewController: UIViewController {

    weak var label: UILabel!

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.alpha = 0
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black
        view.addSubview(label)
        self.label = label

        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 250, width: 300, height: 100)
        button.setTitle("Press to Start FadeIn", for: UIControl.State())
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(startFadeIn), for: .touchUpInside)
        view.addSubview(button)

        self.view = view
    }

    /*
     Animation in action
     */
    @objc private func startFadeIn() {
        label.layer.add(FadeInAdnimation(), forKey: "fadeIn")
    }

}


text:
Q: Is this function periodic function?
Let $f:\mathbb{R}\rightarrow \mathbb{R}$, where $f(x)=1$ if $x$ is rational number and $0$ if $x$ is irrational number. Is $f$ a periodic function.

A hour ago, in this post, I said that this function is not periodic, then Kenny Lau told that I am wrong. He also said that "well, any rational number is a period... $f(x+r)=f(x)$ if $r\in\mathbb{Q}$".
Now, I am totally confused about periodic functions. It means there must infinitely many periods.
It would be very helpful if someone explain it elaborately.

A: A periodic function doesn't necessarily have a minimal period. As long as it repeats itself ($\exists c>0: \forall x \in \Bbb R: f(x+c) = f(x)$), then it is periodic.


text:
Q: Attempted downgrade from GRUB2 to GRUB; can't boot into ubuntu anymore So I just did a clean install of windows 7 ultimate and installed ubuntu 12.10 beside it. I kept the windows bootloader in the mbr at the advice if my tutorial (i used easyBCD to enable an option for grub2) and installed grub2 to the /boot partition that I made for sda5. If it matters, I set / as sda6, /home as sda7 and swap as sda8. I wanted to encrypt my windows partition with truecrypt, and I read to downgrade from grub2 to grub first, so I did (or at least attempted to). the code I used to replace grub2 with grub came from post #4 on this thread: http://ubuntuforums.org/showthread.php?t=1330347#4
However, it leads me into a command line titled "GNU GRUB version 2.00-7ubuntu11". I don't know why it still says version 2. Anyways, I can't even boot into Ubuntu now. From what I understand of grub (a very limited understanding admittedly), I need to use the root, kernel, and boot command to boot up ubuntu. But the problem is that root and kernel don't even exist as commands in the grub terminal. I pressed tab to list all the commands and they weren't among them. Typing them into the terminal yields no result. How do I get into ubuntu now?

A: In grub2, the commands you are looking for are linux, initrd, and boot.  For example:
linux /boot/vmlinuz-3.5.0-26-generic root=/dev/sda1
initrd /boot/initrd.img-3.5.0-26-generic
boot

A: Use the Recommended Repair of Boot-Repair.


text:
Q: ReactiveUI SelectMany form of CreateDerivedCollection Using ReactiveUI 6.5, I'm trying achieve something like a SelectMany LINQ expression with the CreateDerivedCollection feature of RxUI. The objects in my source collection (type 'A') have an IsSelected property, as well as another collection property where the items are of type 'B'. I want to end up with an IReactiveDerivedList<B> which is a flattened list of all of the B objects from the A's that are selected. Hopefully that makes sense.
To make it a little more concrete, let's use an example of an app for browsing log files. Say we have a LogFileViewModel type and our main screen's view model has a list of these. Each instance in the list represents a log file on the system, and we present a list of these that the user can select. It's a multi-select list so they can select more than one at a time.
The LogFileViewModel then has an IsSelected boolean property, which will be set to true/false as the user selects or deselects the corresponding item in the list. And it has a property which is a List<LogEntry>. Each LogEntry object of course represents one entry in the corresponding log file.
What I want to do then is have a reactive list in the main view model which is a list of all of the LogEntry objects for all of the currently selected LogFileViewModel objects. The ReactiveList of selected log files is easy, but I'm stuck on the second part. Here's what the main view model would basically look like:
public class MainViewModel
{
    public MainViewModel()
    {
        //This gets initialized with the log files somehow, doesn't matter
        LogFiles = new List<LogFileViewModel(...);

        SelectedLogFiles = LogFiles.CreateDerivedCollection(l => l, l => l.IsSelected);
        SelectedLogFileEntries = ? //How to create this one?
    }

    public List<LogFileViewModel> LogFiles { get; private set; }
    public IReactiveDerivedList<LogFileViewModel> SelectedLogFiles { get; private set; }
    public IReactiveDerivedList<LogEntry> SelectedLogFileEntries { get; private set; }
}

Is there a known way to do this that I'm just not seeing? If not, any clever ideas to achieve this behavior? :-)
Edit :
Looks like I missed this question in my initial search. Paul provided the "clever" solution to this problem about 2 years ago. So my question now ... is this still the best way to achieve this behavior?


text:
Q: Be $\tau_{1}$ and $\tau_{2}$ topologies over $\mathbb{N}$ Be $\tau_{1}$ and $\tau_{2}$ topologies over $\mathbb{N}$ defined by:
$\tau_{1}=\{\{m\in \mathbb{N}:m<n\}:n\in \mathbb{N}\}\cup \{\mathbb{N}\}\}$ and $\tau_{2}=\{A\subseteq \mathbb{N}: 0\in A\}\cup \{\emptyset\}$.
Check who are these topologies and prove which is the finest.

A: The topology consisting of all subsets containing a fixed point $x$ is called the particular/included point topology. In your case $x=0$. You can simply say that $\tau_1\subset \tau_2$ i.e. $\tau_2$ is strictly finer than $\tau_1$ since:

*

*For all subsets $S\ne\emptyset\in\tau_1,0\in S\subseteq\Bbb N$ and thus $S\in\tau_2$, so $\tau_1\subseteq \tau_2$.

*$\{0,2\}\in\tau_2$ but does not belong to $\tau_1$. Hence $\tau_1\ne\tau_2$.

A: If $U\in\tau_1$, then since $0\in U$, or $U=\emptyset$,  $U\in\tau_2$.  That is, $\tau_2$ is finer.


text:
Q: Unable to import pom.xml in eclipse I am trying to import a maven project into eclipse. But for some reason unable to import pom.xml(all other modules get imported properly).
The way I am doing it is by selecting the 'Existing maven project as an option'.
I tried by deleting the complete project and importing again but pom.xml doesn't get included in it.
Also can a pom.xml be imported separately?


text:
Q: auctex with sumatra pdf I am syncing AUCTeX with Sumatra PDF on MSWindows.
I used the instructions in Sync Emacs AUCTeX with Sumatra PDF (modulo the fact that I use customization instead of writing the setq in the init file, and the fact that the path to sumatra is different on my machine: see https://www.barik.net/archive/2012/07/18/154432/ for the customization)
(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-view-program-list
  '(("Sumatra PDF" ("\"C:/bin86/SumatraPDF/SumatraPDF.exe\" -reuse-instance"
                      (mode-io-correlate " -forward-search %b %n ") " %o"))))
 (setq TeX-view-program-selection
      '(((output-dvi style-pstricks) "dvips and start") (output-dvi "Yap")
       (output-pdf "Sumatra PDF") (output-html "start")))

However, when there is a space in the file name (e.g. "example 1.tex"), the syncing has problems: when from Emacs I do CRTL-c CRTL-v, it opens both the the file "example 1.pdf" and a dummy "123" file, where 123 is the line number in the source file.
Any suggestions on how to solve this problem?


text:
Q: Why some libraries are loaded only under administrator privileges? On Windows, I have an executable that depends on some third-party libraries.
If I try to run it under cmd, an error windows appear saying "program can't start because some_third_party_library.dll is missing"
However if I try to run it under a cmd with administrative privileges, the libraries are loaded correctly and the program starts.
Looking on my system variables, these libraries path are placed inside the %Path% variables and even inside the user %Path% variable. I've check it with  echo %Path%
At first, I though that it was related to some permission reason so I bring Full Control to all users, but it didn't works.
So, ¿why I need to execute that program from console with administrative privileges?

A: Your user account might not have the permission of
"Read & execute" on these DLLs.
Right-click one such DLL, choose Properties, Security tab, and verify the permissions for your account or for the generic Users account.
You may add permissions by using the Edit button.
For more information see this Microsoft article.


text:
Q: Volume Cost Standard Deviation Calculation In my trial to find the dispersion in the variable cost for a production process, below table is a sample indicating the recorded different output of the process in volume of production and costs.
Records Volume  Cost
Volume-Cost outputs of a production process
What is the best approach to measure the standard deviation of the variable cost given that the volume sample data isn't fixed as per the above table.


text:
Q: Free centralized system monitoring for Ubuntu Canonical's Landscape service seems really nice. Is there any free alternatives? If not directly, what would you recommend to administer number of Ubuntu (and Debian) servers? Main use cases would be to see that all machines are running and doing fine (disk space, memory usage, some important processes, etc).
If this would be business critical I would be happy to pay Canonical to provide the service, but this is just for personal use.

A: Nagios for the monitoring/alerting, Puppet for the centralised management.

A: You can install nagios or munin on a server to do something similar.

A: We use -

*

*Groundworks - for network monitoring (groundworks is Nagios with a web frontend)

*Splunk - for logfile analysis

*Puppet - for rolling out changes to ubuntu servers; very useful for load-balancing servers

*Tripwire  - for intrusion detection

All are free, if you spend some time configuring them we find them very effective.
Groundworks/Nagios requires the use of the nrpe agent to allow monitoring of processes, disk space etc on remote servers. This is reasonably easy to configure though.
If all you want to do is CPU/disk/Memory usage then an snmp monitor like cacti is also an option.

A: I currently use the following:

*

*Munin - network and server stats monitoring (and noting else!). I use it over Nagios, as it's dead simple to set up. Install munin on one machine and munin-node and edit /etc/munin/munin-node.conf on all others.

*Logcheck - scans all logs for "bad" words and filters out known-OK's. Has reasonable (and working!) default setup. After a few days, I usually end up spending an hour or so tweaking the filters to remove extra known-OK noise.

*I've looked at Puppet, but I haven't gotten around to do anything serious about it (hints, anybody?).

A: so many different ways... most of them already mentioned, but if you google for free opensource linux server monitoring you'll come across lots more options


text:
Q: Making a simple calculator with ATMEGA32 I try to create a calculator with ATMEGA32 but it did not work correctly! For example it do operations like this (2/1=0),(5*6=12808),(22+88=12746). I know that something is wrong but I cannot find it so I need your help. Many thinks
while (1)
  {
  // Fkeypad is a function which read the keypad. Its output is character.
  a=Fkeypad();
    d=(int) a;
// I do not know the number of digits so try to make a counter (i)
   if(a=='1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9')
   i++;
   switch (i){
   case 1:
   temp1=d; //uint temp1
   break;
   case 2:
   temp1=temp1*10+(d);
   break;
   case 3:
   temp1=temp1*100+(d);
   break;
   case 4:
   temp1=temp1*1000+(d);
   break;
   }
  switch (a){
//if user push a sign(*/-+) it means that he try to write the second number so I put the first number in temp2 and save the sign in temp3 for when I need to do operation
  case '*':
  i=0;
  temp2=temp1; //uint temp2
  temp3=a; //char temp3
  break;
  case '+':
  i=0;
  temp2=temp1;
  temp3=a;
  break;
  case '-':
  i=0;
  temp2=temp1;
  temp3=a;
  break;
  case '/':
  i=0;
  temp2=temp1;
  temp3=a;
  break;
  case '=':
 {
 i=0;
  if(temp3== '*')
  calc=temp1*temp2;
  if(temp3=='+')
  calc=temp1+temp2;
  if(temp3== '-')
  calc=temp1-temp2;
  if(temp3=='/')
  calc= temp1/temp2;
  sprintf(f,"%0000d",calc); //uint calc
  lcd_puts(f); // char f[5]
   break;
  }
  case 'c':
  {
  i=0;
  lcd_clear();
break;
}

A: There are several problems with these first few lines.
a=Fkeypad();
d=(int) a;
if(a=='1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9')

I'm assuming that Fkeypad() returns an ASCII character value.  If that's not correct then you've got other problems and the rest of this answer is wrong.
First read about operator precedence of == and ||.  The if statement that you wrote does not do what you intend because of operator precedence.  Also see this question.
The following if statement does what you intend.
if ((a >= '0') && (a <= '9'))

Second, simply casting an ASCII numeric character value to (int) does not convert it to its integer equivalent.  Instead you should subtract ASCII '0' from the ASCII numerical character value.
This code will give you the proper integer value d.  But you may have additional problems elsewhere in your code.
a=Fkeypad();
if ((a >= '0') && (a <= '9')) // Is this a numerical character?
{
    int d = a - '0';          // convert from ASCII to integer
    ...
}


text:
Q: My program doesn't print a string I'm making a program to delete extra spaces in c and count how many extra space it deletes. The program counts the extra spaces but it doesn't print the string that doesn't have extra spaces. I'll show you my code:
#include <stdio.h>
#include <stdlib.h>

/*
 *
 */
char delete_spaces(char oracion[100])
{
    int i;
    for (i=0;oracion[i]!='\0';i++){
        if (oracion[i]==' '&&oracion[i+1]==' '){
            oracion[i]=oracion[i+1];
        }
    }
    return(oracion[100]);
}

int count_spaces(char oracion[100])
{
    int i,number_spaces=0;
    for (i=0;oracion[i]!='\0';i++){
        if (oracion[i]==' '&&oracion[i+1]==' '){
            number_spaces+=1;
        }
    }
    return(number_spaces);
}

int main(void){
    char frase[100],frase2[100];
    int num_spaces;
    printf("Write here the phrase:");
    gets(frase);
    frase2[100]=delete_spaces(frase);
    num_spaces=count_spaces(frase);
    printf("%s",frase2);
    printf("%d",num_spaces);
    return 0;
}

A: In addition to Barmar's suggestion above, you probably want frase2 to actually be a char* type, and you want to assign it not to the index 100, but the pointer itself:
int main(void) {
    char frase[100];
    char *frase2;
    ...
    frase2 = delete_spaces(frase);
    ...
}

A: You can't assign to an array the way you're trying to do it. You should pass frase2 as a second argument to the function. Then it can copy from one array to the other, skipping over duplicate spaces.
int delete_spaces(char oracion[100], char oracion2[100])
{
    int deletions = 0;
    int i;
    int dest = 0;
    for (i=0; oracion[i]!='\0'; i++){
        if (oracion[i]==' '&&oracion[i+1]==' '){
            deletions++;
        } else {
            oracion2[dest++] = oracion[i];
        }
    }
    oracion2[dest] = '\0'; // don't forget to terminate the string
    return deletions;
}

Notice that this does the counting as it's deleting, so you don't need a separate function for this.
Then you would call it from main as:
num_spaces = delete_spaces(frase, frase2);

A: Could be this what you need?:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int delete_spaces(char *s1,char *s2){

    int found = 0;
    int i = 0, j = 0;

    while(s1[i] != '\0'){
        if (((s1[i] == ' ') && (s1[i+1] == ' ')) || ((s1[i] == '\t') && (s1[i+1] == '\t'))){
            found++;
        } else {
            s2[j++] = s1[i];
        }
        i++;
    }
    s2[j] = '\0';

    printf("s2 = %s\n",s2);
    return found;
}

int main(void){
    char frase[100], frase2[100];
    int num_spaces;

    printf("Write here the phrase:");
    if((fgets(frase,99,stdin)) == NULL){
        printf("Error\n");
    }

    num_spaces=delete_spaces(frase,frase2);
    printf("Number of deleted spaces = %d\n",num_spaces);
    return 0;
}

Output:
I'm going    to sleep now           Goodbye
s2 = I'm going to sleep now Goodbye

Number of deleted spaces = 13

A: #include <stdio.h>
#include <stdlib.h>

typedef struct sentence {//wrap by struct
    char oracion[100];
} sentence;

sentence delete_spaces(sentence frase)//make copy
{
    int i, j;
    for (j=i=0; frase.oracion[i] != '\0'; i++){
        if(j && frase.oracion[j-1] == ' ' && frase.oracion[i] == ' '){
            continue;
        }
        frase.oracion[j++] = frase.oracion[i];
    }
    frase.oracion[j] = '\0';
    return frase;
}

int count_spaces(sentence frase)
{
    int i, j, number_spaces = 0;
    for (j=i=0; frase.oracion[i] != '\0'; i++){
        if(j && frase.oracion[j-1] == ' ' && frase.oracion[i] == ' '){
            number_spaces += 1;
            continue;
        }
        frase.oracion[j++] = frase.oracion[i];
    }
    return number_spaces;
}

int main(void){
    sentence frase, frase2;
    int num_spaces;

    printf("Write here the phrase:");
    scanf("%99[^\n]%*c", frase.oracion);
    frase2 = delete_spaces(frase);//make copy to frase2
    num_spaces = count_spaces(frase);
    printf("%s\n", frase2.oracion);
    printf("%d\n", num_spaces);

    return 0;
}


text:
Q: Best way to transfer and store variables from PHP to JS/jQuery I have various important variables that I need transfering from PHP to JS on the same page load. I am currently storing these variables in DOM element attributes and using jQuery to grab them out.
This works fine, although as some of the information is quite important I would rather this wasn't publicly visible in the DOM and 'hidden from prying eyes'.
So my question is: How to you transfer variables to JS or the DOM from PHP and keep them hidden from sight?
Cheers guys, hope you can help!

A: Everything going on in JS is potentially visible to the end user. If it is secure data you are trying to hide, perhaps you need to re-engineer your approach.

A: use an ajax request on page load. Here is a shell for jQuery:
$(function()
{
    $.ajax("http://yoursite.com/phpscript.php",
        {
            method: "post",
            dataType: "json",
            success: function(data)
                {
                    // do what you will with the data here
                }
        });
});

all information has to be downloaded to the person's computer at some point. You can keep it "hidden" in javascript but the end user can easily use firebug or something similar to view that data.

A: So you want data to be sent to user and not sent to user simultaneously?

A: If the data is sensitive, there is no way to hand it over for client-side processing while keeping it secure. That simply isn't how the web works. Everything you hand over to the client must necessarily be readable by the client. You can use technologies like SSL to protect data from being intercepted, but the intended recipient must be able to read it. You should be processing any sensitive data server-side, and outputting only the results intended for public consumption.
If you simply want to make data available to the page while hidding messy implementation details, there are many options:

*

*use an <input type="hidden" /> field

*store your values directly in JavaScript by outputting something like var myValue = <?= $serverside_value ?> or using json_encode

*request the values via AJAX

A: It's not very good to give important information to the client side (HTML/JS).
But to answer your question - you can use jQuery's AJAX methods to post a request to PHP and from PHP, you can return json_encode()'ed data back to jQuery.
And if you want to keep them hidden from sight, or lets say "encrypted enough" you can run this through an SSL channel.
Another option is to make the encryption yourself or use some public libraries for public-private key encryption.
For example with jQuery post :
$.post("script.php",
{requestKey : "requestValue"}, // $_POST["requestKey"] == "requestValue"
function(response) {
 // if you receive JSON encoded data
 // you should use JSON decoder for javasript
 // or var obj = eval('(' + response + ')');
},
"json");

In PHP it will be :
$data = $_POST["requestKey"];
// do something
echo json_encode($result);


text:
Q: RNN L2 Regularization stops learning I use Bidirectional RNN to detect an event of unbalanced occurence. The positive class is 100times less often than the negative class.
While no regularization use I can get 100% accuracy on train set and 30% on validation set.
I turn on l2 regularization and the result is only 30% accuracy on train set too instead of longer learning and 100% accuracy on validation set.
I was thinking that maybe my data is too small so just for experiment I merged train set with test set which I did not use before. Situation was the same as I would use l2 regularization, which I did not now. I get 30% accuracy on train+test and validation.
In use 128hidden units and 80 timesteps in the mentioned experiments
When I increased the number of hidden units to 256 I can again overfit on train+test set to get 100% accuracy but still only 30% on validation set.
I did try so many options for hyperparameters and almost no result. Maybe the weighted cross entropy is causing the problem, in given experiments the weight on positive class is 5. While trying larger weights the results are often worse around 20% of accuracy.
I tried LSTM and GRU cells, no difference.
The best results I got. I tried 2 hidden layers with 256 hidden units, it took around 3 days of computation and 8GB of GPU memory. I got around 40-50% accuracy before it starts overfitting again while l2 regularization was on but no so strong.
Is there some general guideline what to do in this situation? I was not able to find anything.

A: Too much hidden units can overfit your model. You can try with smaller number of hidden units. As you mentioned, training with more data might improve the performance. If you don't have enough data, you can generate some artificial data. Researchers add distortions to their training data to increase their data size but in a controlled way. This type of strategy is pretty good for image data but certainly if you are dealing with text data, probably you can use some knowledge base that can improve the performance.
There are many works going on using Knowledge-bases to solve NLP and deep learning related tasks.


text:
Q: Scheduled IOS local notifications repeat every minute I have an IOS app that schedules a local notification on the day the app is opened, and every day at roughly the same time for the next 7 days. What happens is each notification is repeated the number of days I schedule for, so in this case each notification is repeated 8 times, one per minute on each day rather than one each day for 8 days. I thought it may be due to the identifier but i have tried to make that as unique as possible, heres my code:
Where scheduleDate is an array of Dates that I loop over:
func getNextNDays(numberOfDays: Int) -> [Date] {
    let today = Date()
    var days = [Date]()

    for i in 1...numberOfDays {
        let nextNDay = Calendar.current.date(byAdding: .day, value: i, to: today) ?? Date()
        days.append(nextNDay)
    }

    return days
}

let numberOfDaysForNotifications = 7
let nextNDays = getNextNDays(numberOfDays: numberOfDaysForNotifications)

for nextDate in nextNDays {
    scheduleNotification(scheduleDate: nextDate)
}

// nextNDays contains
[2021-04-15 17:03:54 +0000, 2021-04-16 17:03:54 +0000, 2021-04-17 17:03:54 +0000, 2021-04-18 17:03:54 +0000, 2021-04-19 17:03:54 +0000, 2021-04-20 17:03:54 +0000, 2021-04-21 17:03:54 +0000]

func scheduleNotification(scheduleDate: Date) {
    let date = scheduleDate
    let triggerDate = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "Some title"
    content.body = "Some body"
    content.badge = 0
    content.sound = UNNotificationSound.default

    let formatter = DateFormatter()
    formatter.dateFormat = "HHmmEdMMMy"

    let identifier = notificationTitle + formatter.string(from: scheduleDate) + UUID().uuidString
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    notificationCenter.add(request) { (error) in
        if let error = error {
            print("Error scheduling notification \(error.localizedDescription)")
        }
    }
}

Any ideas what could be wrong here?


text:
Q: JMeter Java HEAP issue seen after finished test plan execution JMeter Test seems to finish fine.
But the next output after "14:48:37 [info] Completed Test: needs_gcs_load_test.jmx" is missing because of the heap issue.
Next lines should normally be,
[INFO] Test Results:
[INFO]
[INFO] Tests Run: 1, Failures: 0

Any ideas...?
Have increased heap to 2048. Also removed debug in jmx.log file.
HEAP issue.
14:48:37 [info]   Interpreted + native   Method
14:48:37 [info] 100.0%     0  + 27207    java.net.PlainDatagramSocketImpl.receive0
14:48:37 [info] 100.0%     0  + 27207    Total interpreted
14:48:37 [info]
14:48:37 [info]
14:48:37 [info] Global summary of 301.00 seconds:
14:48:37 [info] 100.0% 27326             Received ticks
14:48:37 [info]   0.2%    46             Received GC ticks
14:48:37 [info]   6.5%  1785             Compilation
14:48:37 [info]   0.0%     1             Deoptimization
14:48:37 [info]   0.0%     2             Other VM operations
14:48:37 [info]   0.0%     8             Class loader
14:48:37 [info]   0.0%     6             Unknown code
14:48:37 [info] Completed Test: needs_gcs_load_test.jmx
14:48:38 [ERROR] Java heap space -> [Help 1]
14:48:38 java.lang.OutOfMemoryError: Java heap space
14:48:38    at java.nio.HeapCharBuffer.<init>(HeapCharBuffer.java:57)
14:48:38    at java.nio.CharBuffer.allocate(CharBuffer.java:335)
14:48:38    at java.util.Scanner.makeSpace(Scanner.java:840)
14:48:38    at java.util.Scanner.readInput(Scanner.java:795)
14:48:38    at java.util.Scanner.findWithinHorizon(Scanner.java:1685)
14:48:38    at com.lazerycode.jmeter.FailureScanner.hasTestFailed(FailureScanner.java:36)
14:48:38    at com.lazerycode.jmeter.JMeterMojo.parseTestResults(JMeterMojo.java:70)
14:48:38    at com.lazerycode.jmeter.JMeterMojo.execute(JMeterMojo.java:54)
14:48:38    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
14:48:38    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
14:48:38    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
14:48:38    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
14:48:38    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
14:48:38    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
14:48:38    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
14:48:38    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
14:48:38    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
14:48:38    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
14:48:38    at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:117)
14:48:38    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
14:48:38    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
14:48:38    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
14:48:38    at java.lang.reflect.Method.invoke(Method.java:497)
14:48:38    at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329)
14:48:38    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239)
14:48:38    at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:181)
14:48:38    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
14:48:38    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
14:48:38    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
14:48:38    at java.lang.reflect.Method.invoke(Method.java:497)
14:48:38    at hudson.maven.Maven3Builder.call(Maven3Builder.java:136)
14:48:38    at hudson.maven.Maven3Builder.call(Maven3Builder.java:71)
14:48:38 [ERROR]
14:48:38 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
14:48:38 [ERROR]
14:48:38 [ERROR] For more information about the errors and possible solutions, please read the following articles:
14:48:38 [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/OutOfMemoryError
14:48:38 channel stopped
14:48:38 Archiving artifacts
14:48:40 Performance: Percentage of errors greater or equal than 1% sets the build as unstable
14:48:40 Performance: Percentage of errors greater or equal than 2% sets the build as failure
14:48:40
14:48:40
14:48:40
14:48:40 Finished: FAILURE


text:
Q: valgrind detects memory leak but application works I wrote an application able to read in sqlite database thanks to this function:
struct query_res excucute_sql_statement(char *database, char *zSQL){
    sqlite3 *conn;
    sqlite3_stmt    *res;
    const char      *tail, *buf, *zErrMsg;
    struct query_res q_res;
    char table[MAXSTMTNUM][MAXCOLNUM][MAXSTRINGLEN];
    q_res.table = table;
    q_res.num = 0;
    int maxtry = 5, try = 0;

    while (sqlite3_open(database, &conn)) {
        if (try > maxtry)
            break;
        printf("Can not open database \'%s\'. %s\n", database, sqlite3_errmsg(conn));
        usleep(50000);
        try ++;
    }

    if (sqlite3_exec(conn, zSQL, callback, &q_res, &zErrMsg)){
        printf("Excecuting %s\n", zSQL);
        printf("We did not get any data! error %s\n",zErrMsg);
        if(sqlite3_finalize(conn))
            printf("Can not finalize database. %s\n", sqlite3_errmsg(conn));
        if(sqlite3_close(conn))
            printf("Can not close database. %s\n", sqlite3_errmsg(conn));
        return q_res;
    }

    sqlite3_free(zSQL);

    if(sqlite3_close(conn))
        printf("Can not close database. %s\n", sqlite3_errmsg(conn));

    return q_res;
}

For each line returned the function callback is called:
static int callback(void *buf, int argc, char **argv, char **azColName){
    int i;
    struct query_res *q_res;
    q_res = (struct query_res *)buf;
    if (q_res->num >= MAXSTMTNUM)
        return 0;

    q_res->table[q_res->num] = calloc(argc, sizeof(char *));

    for(i=0; i<argc; i++){
        if (i >= MAXCOLNUM)
            break;
        q_res->table[q_res->num][i] = calloc(((strlen(argv[i]) < MAXSTRINGLEN) ? strlen(argv[i]) : MAXSTRINGLEN), sizeof(char));
        strncpy(q_res->table[q_res->num][i], argv[i], ((strlen(argv[i]) < MAXSTRINGLEN) ? strlen(argv[i]) : MAXSTRINGLEN));
    }
    q_res->num ++;

    return 0;
}

Here is the extract of the code where excucute_sql_statement is called:
struct query_res    res;
res = excucute_sql_statement(database, zSQL);

directions = malloc(sizeof (struct direction_list));
directions->directions = calloc(5,  sizeof (struct direction));

double cur_dist, min_dist = 30;
float s_lat, s_lon, e_lat, e_lon;
directions->direction_num = 0;

//printf("Res table num %d\n", res.num);

//printf("First elem %s\n", res.table[0][0]);

for (i = 0 ; i < res.num ; i++){
    //printf("%d. %s|%s|%s|%s|%s|%s\n", i, res.table[i][0], res.table[i][1], res.table[i][2], res.table[i][3], res.table[i][4], res.table[i][5]);
    sscanf(res.table[i][1], "%g", &s_lat);
    sscanf(res.table[i][2], "%g", &s_lon);
    sscanf(res.table[i][3], "%g", &e_lat);
    sscanf(res.table[i][4], "%g", &e_lon);
    sscanf(res.table[i][0], "%d", &rs);
    sscanf(res.table[i][5], "%d", &rp);
    //printf("New seg start: %g,%g end %g,%g rs %d rp %d\n", s_lat, s_lon, e_lat, e_lon, rs, rp);
    cur_dist = (gps_distance(location.lat, location.lon, s_lat, s_lon)
        + gps_distance(location.lat, location.lon, e_lat, e_lon)) / 2;
    //printf("Current direction num %d \n", directions->direction_num);
    //printf("cur_dist %f\n", cur_dist);
    if (cur_dist < min_dist){
        directions->directions[0] = fill_direction(rs, rp, database);
        directions->direction_num = 1;
        min_dist = cur_dist;
    }
    else if (cur_dist == min_dist){
        directions->directions[directions->direction_num] = fill_direction(rs, rp, database);
        directions->direction_num ++;
    }
}

These functions works fine and give the expected result but when running valgrind, I have the following output:
==22808== Thread 2:
==22808== Invalid read of size 4
==22808==    at 0x804946B: get_all_possible_directions (util.c:240)
==22808==    by 0x8049D73: start_direction_detection (direction_detection.c:293)
==22808==    by 0x40C41C88: ???
==22808==  Address 0x4f03690 is not stack'd, malloc'd or (recently) free'd
==22808==
==22808== Invalid read of size 1
==22808==    at 0x402F5C3: __GI___rawmemchr (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==22808==    by 0x40C246E: _IO_str_init_static_internal (strops.c:44)
==22808==    by 0x8049D73: start_direction_detection (direction_detection.c:293)
==22808==    by 0x40C41C88: ???
==22808==  Address 0x45aa01b is 0 bytes after a block of size 11 alloc'd
==22808==    at 0x402B965: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==22808==    by 0x8048F59: callback (util.c:57)
==22808==
==22808== Invalid read of size 4
==22808==    at 0x8049487: get_all_possible_directions (util.c:241)
==22808==    by 0x8049D73: start_direction_detection (direction_detection.c:293)
==22808==    by 0x40C41C88: ???
==22808==  Address 0x4f03690 is not stack'd, malloc'd or (recently) free'd

and so on ...
Note that line 240 corresponds to the first scanf statement.
I think there is something wrong with my table initialization. Maybe here:
q_res->table[q_res->num] = calloc(argc, sizeof(char *));

Do you have any idea why valgrind is triggering this error?
Thanks

[update from comment:]
struct query_res is composed of char ***table and int num.

A: In excucute_sql_statement(), here
q_res.table = table;

you are copying a reference to stack-local storage (table) into the stucture returned by the function.
Stack-local storage becomes invalid as soon as the function returns, so the structure's member table refers to invalid (unallocated) memory after the function has returned.
To fix this modifiy excucute_sql_statement()
struct query_res excucute_sql_statement(char *database, char *zSQL)
{
  [...]

  /* char table[MAXSTMTNUM][MAXCOLNUM][MAXSTRINGLEN]; */ /* Delete this line. */
  q_res.table = NULL;
  q_res.num = 0;

and callback()
static int callback(void *buf, int argc, char **argv, char **azColName)
{
  size_t i;
  struct query_res * q_res = (struct query_res *) buf;

  /* Resize statement table, adding one new entry. */
  q_res->table = realloc(q_res->table, (q_res->num + 1) * sizeof(*q_res->table));

  /* Allocate new argument table. */
  /* (Allocate +1 for a stopper element which stays NULL to be able to detect the end of the table.) */
  q_res->table[q_res->num] = calloc(argc + 1, sizeof(*q_res->table[q_res->num]));

  for(i=0; i<argc; ++i)
  {
    /* Allocate entry for argument, that is characters for argument. */
    q_res->table[q_res->num][i] = malloc(strlen(argv[i]) + 1);
    /* Copy argument. */
    strcpy(q_res->table[q_res->num][i], argv[i]);
  }

  q_res->num++;

  return 0;
}

(untested)
Also please note that the whole code (yours and mine) is missing proper error checking. Here especially the retuned values of the allocating calls to malooc/calloc/reallocshall be tested against NULL!


text:
Q: Why is it not possible to go into BIOS on a cloud server? I am trialling cloudsigma, and they claim to use a KVM Hypervisor. I have a trial server, but cannot boot it from BIOS. Is this the case with all cloud servers?
The company claims I can run Hyper-V or ESX, but I would not be able to without going into BIOS first.
Thanks

A: ESX/i lets any VM go into BIOS - speak to them about this ok.

A: There isn't a BIOS in most VMs (and certainly not in KVM).  I mean, there's something that works as a BIOS, but it's not going to be the "press F2 to set some stuff up" BIOS that you're used to.
If you're wanting to set boot parameters or something, they'll have to do it for you.


text:
Q: Incorrect linear interpolation with large x values using Math.Net Numerics I'm trying to use Math.NET Numerics to do interpolation of a DateTime - Value series. I started off with linear interpolation, but am getting some very off looking results.
Running this test:
public class script{

public void check_numerics()
  {
    var ticks = DateTime.Now.Ticks;
    Console.WriteLine("Ticks: " + ticks);
    var xValues = new double[] { ticks, ticks + 1000, ticks + 2000, ticks + 3000, ticks + 4000, ticks + 5000 };
    var yValues = new double[] {0, 1, 2, 3, 4, 5};
    var spline = Interpolate.LinearBetweenPoints(xValues, yValues);
    var ticks2 = ticks;
    for (int i = 0; i < 10; i++)
    {
      ticks2 += 500;
      Console.WriteLine(spline.Interpolate(ticks2));
    }
  }
}

This gives:
Ticks: 635385235576843379
0.5
1
1.5
2
2.42857142857143 // this should be 2.5
3
3.5
4
4.5
5

Notice that 2.4285 is fairly wrong. At a different time (different ticks value) a different value will be "wrong". Is there a "bug" with large x values in Math.NET or am I expecting too much?

A: Just confirming the comments above as the maintainer of Math.NET Numerics:
The distance (epsilon) between the closest numbers of this magnitude that can be represented at double precision is 128:
Precision.EpsilonOf(ticks); // 128

This means that if you add or substract 128/2-1 = 63 from this number, you get back exactly the same number:
long ticks = DateTime.Now.Ticks // 635385606515570758
((long)(double)ticks)           // 635385606515570816
((long)(63+(double)ticks))      // 635385606515570816
((long)(-63+(double)ticks))     // 635385606515570816
((long)(65+(double)ticks))      // 635385606515570944
((long)(-65+(double)ticks))     // 635385606515570688

The incremental steps of 500 are very close to these 128 and effectively get rounded to multiples of 128 (e.g. 512), so it's not surprising that there will be some artifacts like this.
If you reduce the time precision to milliseconds by dividing the ticks by 10000, as suggested by James, you get an epsilon of 0.0078125, and accurate results even for steps of 1 instead of 500.
Precision.EpsilonOf(ticks/10000); // 0.0078125


text:
Q: Page not Found after pulling from GitHub in CodeIgniter 3 I have been working on a Project in CodeIgniter 3 and everything is working fine. I have decided to continue the project in another system. But when I pulled the project from GitHub into the second system, only the default_controller route works while other defined routes will always redirect me to 404 Page not Found.
I have checked everything from the first system and its looking good but I keep getting the Page Not Found! Please any help? ...


text:
Q: where to place registers in VHDL modules I'm a software guy by trade and I have been dabbling in digital design on FPGA using the open source toolchain. I have made a few designs and generally understand how the handle verilog and VHDL.
One of the things I'm wondering is not really a black and white question but rather I'm wondering whether there is a "best practice".
I generally divide the designs I make into modules. For example I have a uart that I can include in a design. Now the transmit part of the uart has a feedback mechanism that indicates whether it is ready to receive another 8 bit word to transmit.
Now I could choose to make either the input or the output registered essentially forcing a pipeline. However this would have some impact on users of the design. If I register the input or the output the feedback is always delayed by 1 clock cycle. This is not so bad and might even be what you want. But If both input and output are registered the feedback is delayed by 2 clock cycles which might be confusing for users.
Is there some kind of best-practice to follow here. As in most of the time register your input or your output?
Any help is appreciated!

A: UART might not be the best example to drive this question, since the external activities associated with a UART are generally so slow relative to the other activities internal to the FPGA that an extra clock or two in a handshake hardly makes any difference at all.
However, in the high-speed video signal processing pipelines that I build (the bulk of my work these days, it seems), I generally register the outputs of each module. Then any modules receiving these signals can use combinatorial logic on them without worrying about excessive input delays, glitches, etc.
Inputs get registered only if they are known to be coming from a different clock domain or a completely asynchronous source, in which case, I have a library of CDC (clock domain crossing) modules that I use.


text:
Q: ASP.NET Rich UI - What do you use? I'm looking for feedback on what other people use on their ASP.NET projects to provide a rich user interface experience while still remaining as productive as possible.
I'm developing an ASP.NET 3.5 web based application however I'm looking to make the UI in this project as rich as possible e.g.

*

*minimisation of postbacks and full page refreshes

*Use of AJAX where appropriate

*Ability to apply own theme/skin to any third party components.
I am very good at CSS/Javascript,am getting more and more proffcient in Jquery and have a pretty good knowledge of ASP.NET. However in terms of the Xhtml and client side technologies I have to be aware that not everyone coming to work on future projects will be as clued up on the Xhtml/CSS/Script side. Hence another key requirement is

*

*If possible get good design time support in Visual studio for the above

At the moment I'm looking into the bog standard search ane edit type screens e.g. search for some data and drill down and edit. Using ListView/GridView out of the box with no AJAX isn't an option as the user experience is too poor.
but am struggling between what I see as three different options.

*

*Use the out of the box controls ASP.NET controls but with an updatepanel to minimise postbacks. I am not sure about this though as I have read the update panel is not very efficient (e.g. if you have a grid and put it into edit more ALL of the grids markup will be fetched from the server again.)

*Give up on the ASP.NET controls and use a third party grid like Developer express grids. I've had a play with these and like the searching and grouping parts of this but when it comes to editing I'm not so sure.

*Come up with a cunning plan of my own. I'm thinking of a web service returning JSON etc etc. This appeals to me but if I was going down this route I would need to convince my bosses that this could be productive and tie into as much exsiting stuff as possible. I've looked briefly at ADO.NET Data Services for instance.

Anyway as I said the aim of this question is to try and get a feel for  what other people use on their ASP.NET projects to provide a rich user interface experience while still remaining as productive as possible.

A: For a grid you could use DataTables.  It has multi column filtering and sorting, row based events, paging, and can work with the DOM or accept data via Ajax call.
If you are looking for a good resource for jQuery and the postback cycle you should read Dave Ward's blog.  He covers different techniques regarding PageMethods and web services.
You also be interested in mirco-templates, where you can use a template language such as jTemplates to process client side updates to the DOM.  Using this type of technique can reduce your reliance on ViewState and postbacks.
Finally, there is a nice plugin called SimplyModal that will allow you to create modal dialog boxes.  Here's a good example.

A: We use a combination of updatepanels and raw ajax.
Updatepanels are as you say not very efficient, but they are nice when a large portion of the screen needs to be refreshed.
For javascript/ajax we mainly use jQuery (totally sweet) , and use MS Asp.Net Ajax to communicate with web services on the web server. The web services typically return our own custom ServiceResult objects tagged with  [DataContract(Namespace = "")] with properties tagged with [DataMember]. when these objects are received on the js side they are js-objects. One of the props is the datacontainer which is a json-serialized object that can be deserialized on the js-side using
Sys.Serialization.JavaScriptSerializer.deserialize(resultObject.ResultString)

A: Do you have a budget? We use the Telerik AJAX components at my employer, and have been pretty happy with the features and performance.


text:
Q: iPhone: Camera following player in cocos2d I'm making an iPhone game in cocos2d.
I was wondering how I would make the camera / the view follow a specific sprite?
would I use the CCCamera class?

A: use CCFollow actions
Like these :-
[self runAction:[CCFollow actionWithTarget:(u r hero) worldBoundary:CGRectMake(0,0,1050,350)]];

it will helps

A: Yes, CCCamera would work. However, it has some drawbacks that make it undesirable for some uses. Moving the layers respectively all other objects relative to that sprite may be a better solution. It depends on the game.
First, read up what the different approaches and their drawbacks are, you can get a lot out of this cocos2d forum thread:
http://www.cocos2d-iphone.org/forum/topic/5363
It would be helpful if you could describe what your game is about and why you need the camera attached to that sprite.
For example, if you're thinking of a running game like Canabalt, i would not use the camera to scroll over the world, but instead scroll everything relative to the player (towards him) with the player sticking at about the same x coordinate while running. Perfect examples of games where you would not move the camera at all are the iCopter games, they are basically simplified versions of Canabalt. Notice that the player sprite always stays at the exact same x coordinate, and the game world just scrolls
Scrolling the camera itself in my opinion makes the most sense if you have a large game world that the player can traverse in all directions, and the number of objects are simply too numerous and also moving about in various directions, so updating their positions individually each frame would be both overkill and prone to errors. And since the game world is so huge, you would want to use the camera's position to limit what is drawn on screen.


text:
Q: How to use Sass::Engine's render_with_sourcemap After looking at the documentation for render_with_sourcemap (and unfortunately unable to find any example uses of this), I was under the impression that the following should work:
@source_dir = './sass/'
@target_dir = './css/'
@output = Sass::Engine.new(File.read(@source_dir + 'style.scss'), {
        cache_location: @source_dir + '.sass-cache',
        style: :compressed,
        syntax: :scss
}).render_with_sourcemap(@target_dir + 'style.css.map')

However, the error I'm getting is:
Error generating source map: couldn't determine public URL for the source stylesheet. (Sass::SyntaxError)
No filename is available so there's nothing for the source map to link to.

It works by simply using render (which doesn't need a parameter) instead of render_with_sourcemap, so I'm led to believe my filename is erroneous - however, I don't see what I'm doing wrong. I also tried /style.css.map, ./style.css.map and @target_dir + style.css.map, all with no success (getting the same error)

A: Looking at the source code of the Engine class, I found that the error is thrown from _render_with_sourcemap if @options[:filename] is nil - initializing the function with that option resulted in successfully generating the sourcemap.
The following code is the entire code needed to generate a css file and sourcemap for future reference
@source = './sass/'
@target = './css/'
@output = Sass::Engine.new(File.read(@source + 'style.scss'), {
    cache_location: @source + '.sass-cache',
    filename: 'style.css',
    style: :compressed,
    syntax: :scss
}).render_with_sourcemap(@target + 'style.css.map')

# write css to file
File.write(@target, @output[0])

# write sourcemap to file
sourcemap_options = {
  :css_path => @target,
  :sourcemap_path => @target + 'style.css.map'
}
File.write(@target + 'style.css.map', @output[1].to_json(sourcemap_options))

A: Even if it is not documented you should set the filename variable. After that you should get a sourcemap object.


text:
Q: Telegram bot api custom keyboard message I've got telegram bot in php, and I show custom keyboard doing :
$replyMarkup = array(
      'keyboard' => array(
           array('/help')
       )
);

$keyboard = json_encode($replyMarkup)

$this->client->request('POST', 'sendmessage', ['query' => ['chat_id' => $chatId, 'text' => $text, 'reply_markup' => $keyboard]]);

All works right.
My question is : is there a way to map a keyboard command to a different message?
So in this case i want to show custom keyboard that shows "Help" and on click send /help.
Thanks.

A: For now, custom keyboard's buttons are simply templates for messages, so "No, it's not possible".

A: Using InlineKeyboardMarkup can solve this issue.
Basic usage for C#
   public static InlineKeyboardMarkup TestInlineKeyboard { get; } = new InlineKeyboardMarkup
    {
        InlineKeyboard = new []{new[] {new InlineKeyboardButton("Text1","Data1"),
                                       new InlineKeyboardButton("text1","data2")} }
    };

where "Text1" and "text1" is captions on inline buttons, "Data1" and "data2" is CallbackQuery text that your bot will recieve when user clicks inline button. Note that bot not send any message to user when he clicks inline button. If you need to send any message at that moment - you can do that programmatically.
  Warning: Inline keyboards are currently being tested and are not available in channels yet. For now, feel free to use them in one-on-one chats or groups. but very good to know.

Taked from this post.


text:
Q: How can the NamedSQLQueryDefinition class be used dynamically as a sql-query equivalent? I need to dynamically add named queries to the NHibernate configuration object. The search engines return few hits referencing NamedSQLQueryDefinition or NamedQueryDefinition. Below is what I'm attempting to do. I don't know what to provide to the NamedSQLQueryDefinition constructor to successfully create a query. Can anyone provide a sample of how to create a new NamedSQLQueryDefinition the right way? Thanks!!
Session initializer:
    private static ISessionFactory CreateSessionFactory()
    {
        var configuration = new Configuration();

        return Fluently.Configure(configuration.Configure())
            .ExposeConfiguration(AddQueries)
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
            .Mappings(m => m.HbmMappings.AddFromAssemblyOf<Program>())
            .BuildConfiguration()
            .BuildSessionFactory();
    }

The AddQueries would look something like this:
    private static void AddQueries(Configuration cfg)
    {
        var nameQuery = new NamedSQLQueryDefinition("exec pr_GETCustomer ?", ...)

        cfg.NamedSQLQueries.Add("pr_GETCustomer", nameQuery);
        var cust = cfg.GetClassMapping(typeof (Customer));

        cust.LoaderName = "pr_GETCustomer";
    }

PS: I'm trying this route because Fluent NHibernate does not implement a way to configuring the loader & sql-query elements from the hbm file.

A: The AddQueries method would be implemented as follows below to "fix" the Fluent NHibernate lack of Loader support. The trick is to properly set up the INativeSQLQueryReturn[] value to contain the mapping from the table columns to the entity properties. It should mimic the contents of the return element of sql-query in the HBM file where the class (with namespace) and property mappings are defined (see XML below). Thanks to @jimbobmcgee for getting me started in this direction!
private static void AddQueries(Configuration cfg)
{
    var namedQuery = new NamedSQLQueryDefinition(
        "exec dbo.pr_GETCustomers @CustomerID=?",
        new INativeSQLQueryReturn[]
            {
                new NativeSQLQueryRootReturn(
                    "Customers",
                    "VehicleInfo.Entities.Customers",
                    new Dictionary<string, string[]>
                        {
                                    {"CustomerID", new[] {"CustomerID"}},
                                    {"CompanyName", new[] {"CompanyName"}}
                    },
                    LockMode.Read)
            },
        new List<string> { "dbo.Customers" },
        true,
        null,
        15,
        1000,
        FlushMode.Auto,
        CacheMode.Normal,
        false,
        "",
        null,
        true);

    cfg.NamedSQLQueries.Add("pr_GETCustomers", namedQuery);
    var cust = cfg.GetClassMapping(typeof(Customers));

    cust.LoaderName = "pr_GETCustomers";
}

Sample HBM file that does the same thing:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    default-access="property" auto-import="true"
    default-cascade="none" default-lazy="true">
    <class xmlns="urn:nhibernate-mapping-2.2"
        mutable="true" name="VehicleInfo.Entities.Customers, VehicleInfo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Customers">
        <id name="CustomerID" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <column name="CustomerID" />
            <generator class="assigned" />
        </id>

        <property name="CompanyName" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <column name="CompanyName" />
        </property>

        <loader query-ref="pr_GETCustomers"/>

        <sql-insert callable="true" check="none">exec dbo.pr_INSERTCustomers @CompanyName=?, @CustomerID=?</sql-insert>
        <sql-update callable="true" check="none">exec dbo.pr_UPDATECustomers @CompanyName=?, @CustomerID=?</sql-update>
        <sql-delete callable="true" check="none">exec dbo.pr_DELETECustomers @CustomerID=?</sql-delete>
    </class>
    <sql-query name="pr_GETCustomers">
        <return alias="cust" class="VehicleInfo.Entities.Customers, VehicleInfo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
            <return-property name="CustomerID" column="CustomerID"></return-property>
            <return-property name="CompanyName" column="CompanyName"></return-property>
        </return>
        exec dbo.pr_GETCustomers @CustomerID=?
    </sql-query>
</hibernate-mapping>

A: I'm pretty new to this but most of the parameters look to be determinable from the attributes you can provide in the HBM file.  That said, I'm not too sure what QuerySpaces are.  The closest I've got to what I think you are trying to achieve is to use the following (untested):
ISQLQuery q = session.CreateSQLQuery("exec pr_GETCustomer :p1");

if (q is SqlQueryImpl)
{
    IDictionary<string, TypedValue> namedParams = new Dictionary<string, TypedValue>();
    namedParams.Add("p1", new TypedValue(NHibernateUtil.Int32, 12345);

    IDictionary<string, string> paramTypes = new Dictionary<string, string>();

    NativeSQLQuerySpecification spec =
        (q as SqlQueryImpl).GenerateQuerySpecification(namedParams);

    NativeSQLQueryDefiniton def = new NativeSQLQueryDefiniton(
        spec.QueryString,
        spec.SqlQueryReturns,
        spec.QuerySpaces,
        false,
        null,
        -1,
        -1,
        FlushMode.Never,
        CacheMode.Normal,
        true,
        "blah",
        paramTypes,
        false
    );
}

Obviously, I don't like the cast to SqlQueryImpl.  I'm hoping that, once one of us has done it once, obscure properties like querySpaces can be understood, so you won't have to.
Not that I expect it to 100% work, but it may be more achievable from here.


text:
Q: how can I open .ipynb(jupyter notebook) on chrome? I'm learning python now, and I don't figure out how to open .ipynb on chrome.
When I try to, the cells appear for just a second but disappear and a message something went wrong with displaying webpage comes out.
I can open another .ipynb on chrome via jupyter notebook home screen.
What's more, I confirmed that kernel started.
how can i fix this???


text:
Q: Adding Javascript to button in Click funnels for AdRolls I am hoping someone can help me.  I am creating a funnel in clickfunnels and am using retargeting with AdRolls. I set up 2 event tracking audiences and need to add javascript to 2 buttons.  They won't tell me how to do it, but I do know we have to put the javascript in external files and then call it (can I put both event pixels in that file or do they have to be separate?).  The event pixel should be triggered through the onClick function of the button on the page(s) where the event occurs.
This is the code for the pixel...so i'd have to create 2 and change the ID number in both:
    try{
        __adroll.record_user({"adroll_segments": "25c14f39"})
    } catch(err) {}

And the first button ID Selector is: #tmp_button-90712-129 and the 2nd one is: #tmp_button-90712 . Both are default names for the buttons.  Can someone help me?  Thank you sooooo much!!