Q: Get js localstorage items case insensitive After saving items in javascript local storage I want to retrieve them case insensitive based on the key saved in the localstorage.
For example if I have 'Test' as a key in local storage localstorage.getItem('test'); doesn't return the value of 'Test' cause it is case sensitive. I want to be able to get the item regardless.
Is there a way to do this without looping thourgh the local storage and using toLowerCase() function for each key I find as in the code below:
    for (var i = 0; i < localStorage.length; i++){
    if( localStorage.key(i).toLowerCase()==searchedKey.toLowerCase() ){
    matchingKey =true;
    break;
    }        }

A: localStorage is a Dictionary. It stores Key/Value pairs. Both Key and Value are string.
As Dictionary keys must be unique, values as Test and test are not the same, and therefore must be saved into Dictionary as 2 separate entries.
Also, localStorage has no functionality to get all added Keys or Values, unlike C# or Java. Don't know exact reason for this functionality being missed. It can be due to security, so that rogue JavaScript has no ability to interrogate the storage, or just to keep it simple.
The only way to get value by case insensitive Key, is to store them case insensitive.
You can use either toUpper or toLower on Key before adding it to localStorage. However, Microsoft says converting to upper case is safest: https://learn.microsoft.com/en-gb/visualstudio/code-quality/ca1308-normalize-strings-to-uppercase?view=vs-2015


Q: Nginx + php-fpm - Each php-fpm process 70-100% cpu when running I have a situation in which the following is taking place:

*

*We are on linode with 8-core, 8gb of ram , 2.6 ghz - using nginx + php-fpm - we are getting extremely high graphs of cpu usage (which we don't want to be such a bad VPS neighbor)...

*We have around less than 100 users on the site at a time - so this situation is also incredibly embarassing - that our cpu usage is very high.

*We are using a very unknown, possibly cpu intensive php-wise, questionably horrible Framework instead of well-known, well-documented, well-crafted other frameworks like wordpress or drupal in which there is LOTS of documentation about caching (as well as plugins that handle caching) php on a nginx + php_fpm platform.

*Thus, we have about 6 open php-fpm processes that when RUNNING, consume individually LARGE (30+, and often near 99%) amounts of cpu - and I haven't really the slightest idea how to stop them from using so much cpu. I can't tell which php scripts are causing these spikes because they are happening all the time... usually only 1 or 2 are running - but when all 6 run we maximize all 8 cpus.

*My pool.d/www.conf file has the following settings:
pm = dynamic
pm.max_children = 10
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6

*We did this ^ setup because, in the way that I am interpretting it, our memory is actually amazing (htop showing 472/7000+mb used, no swapping etc) and we could handle many more processes and break down the line waiting to get processed - BUT unfortunately, since each process is too intense on our cpu when running - we end up driving our CPU through the roof - so we can't handle enough processes.

*The question - what on earth can we do to reduce the process php-fpm cpu usage so that we can increase the settings in that pool conf file for php-fpm - and also yes, the /var/log/php5-fpm.log is yelling at us to increase our children and adjust/increase our min/max/start servers. But doing so makes our load average crazy as previously stated. How can we do so without necessarily using a cache or what are our options?

*My idea? I've read things about using cpulimit to ensure no process takes more than an allotted amount of cpu - but will that slow things down to be unusable? Or in doing so we could increase our ability to run more than a few processes - I also thought running two pools - one for our forward facing website (what customers experience) and another for a backend (which is affecting our forward facing site when time-consuming reports are being ran).

*I have been spending a few days researching, googling, etc on this topic - and it is difficult because everyone's situation is so unique to their system - the trouble is being on such a specific unheard-of, possibly poorly written - framework - is making it hard to find a solution. We can't just scrap this framework just yet either - I have to find a solution of some sort.

UPDATE: I have implemented memcache to store php sessions - because the framework heavily relies on user sessions and the nature of our system is that employees often use several tabs at a time - each checking back to the sessions to confirm abilities / user data / etc... so I am hoping to see some increase in performance from this - welcome to comment on that if you'd like - I'll see how it goes tomorrow when we get through our higher volume peak times.

A: A couple of things to consider (apologies in advance if you have already considered these):
First of all, make sure to optimize your nginx config and invoke php-fpm only when absolutely necessary. The last thing you want to do is let php handle things like static HTML pages (which it will happily do).
Secondly, since you're using php-fpm, I suggest to be more aggressive with how long php-fpm's children are allowed to live. You need to find the sweet spot between shortly lived threads/children and stability. The php-fpm defaults are way too generous for any production system, IMHO. The longer a worker is allowed to serve requests, the more unstable it will get. There's also a higher risk of memory leaks, and if this framework you refer to has bugs like infinite loops, which may be causing you grief with CPU load, this shouldn't hurt.
I'd reduce the number for pm.max_requests for your production pools. I think the default is 200. I'd start from 50 and see where that takes you.
Failing/complementary to that, you could also try these global options (AFAIK they are all disabled by default):
emergency_restart_threshold 3
emergency_restart_interval 1m
process_control_timeout 5s

What does this mean? If 3 PHP-FPM child processes exit with SIGSEGV or SIGBUS (i.e. crash) within 1 minute then PHP-FPM is supposed to restart automatically. The child processes waits 5s for a reaction on signals from master.
Here's a nice overview of all the config options I mentioned here, as well as others: http://myjeeva.com/php-fpm-configuration-101.html
Hope these tips help you! Remember to tweak and observe, unfortunately there doesn't seem to be a rule of thumb for all this, as you observed, there are too many variables that affect PHP's behaviour and stability.
Finally, the CPU limiting facility you inquired about is documented here, but I'd only resort to it if you exhaust every other option. If you do choose this path, I'd definitely watch out for possible interactions between PHP-FPM tweaks and your limits.conf configuration. At that point etckeeper may be a lifesaver! :)
Good luck!
Rouben

A: You are running opcode caching, right?
It used to be APC that was the go-to here, but it's been a buggy piece of for quite a while, and has been superseded by Zend Opcache, which is now part of PHP since 5.5, and has a backport in PECL for 5.3 and 5.4.


Q: How to skip duplicates and blank values from JSON dataframe and store into an array? The following code displays data from a JSON Line file.
import pandas as pd
import numpy

start = time.time()
with open('stela_zerrl_t01_201222_084053_test_edited.json', 'r') as fin:
    df = pd.read_json(fin, lines=True)
    parsed_data = df[["SRC/Word1"]].drop_duplicates().replace('', np.NAN).dropna().values.tolist()

print(parsed_data)

The output is:
[[' '], ['E1F25701'], ['E15511D7']]

Is there a way remove the blank data, duplicates, and store it as an array?

A: You can use .dropna(),.drop_duplicates().
parsed_data=parsed_data.drop.duplicates()
parsed_data.dropna(how='all', inplace = True)
# do operation inplace your dataframe and return None.

parsed_data= parsed_data.dropna(how='all')
# don't do operation inplace and return a dataframe as a result.
# Hence this result must be assigned to your dataframe

If directly .dropna() not working for you then you may use .replace('', numpy.NaN,inplace=True).
Or you can try this too:
json_df=json_df[json_df['SRC/Word1'].str.strip().astype(bool)]

This is faster then doing .replace(), if you have empty string.
And now we cleaned it, we can just use .values.tolist() to get those value in list.

A: Yup! Pandas has built-in functions for all of these operations:
import pandas as pd
df = pd.read_json('stela_zerrl_t01_201222_084053_test_edited.json', lines=True)
series = df['SRC/Word1']
no_dupes = series.drop_duplicates()
no_blanks = no_dupes.dropna()
final_list = no_blanks.tolist()

If you want an numpy array rather than a python list, you can change the last line to the following:
final_array = no_blanks.to_numpy()

A: Drop the duplicates, replace empty string by NaN, then create the list.
>>> df.drop_duplicates().replace('', np.NAN).dropna().values.tolist()
[['E1F25701'], ['E15511D7']]

PS: Since what you have is a dataframe so it will be a 2D List, if you want 1D list, you may do it for the specific column:
>>> df['SRC/Word1'].drop_duplicates().replace('', np.NAN).dropna().tolist()
['E1F25701', 'E15511D7']

What you have is not an empty string, but white space character, Try this: replace \s+ to np.NAN with regex=True:
>>>df['SRC/Word1'].drop_duplicates().replace('\s+', np.NAN, regex=True).dropna().tolist()
['E1F25701', 'E15511D7']

And apparently, below will also work:
df['SRC/Word1'].drop_duplicates().str.strip().replace('', np.NAN).dropna().tolist()
['E1F25701', 'E15511D7']


Q: Polars: Pivoting by Int64 column not keeping numeric order I have a column called VERSION_INDEX which is Int64 and is a proxy for keeping a list of semantic software versions ordered such that 0.2.0 comes after 0.13.0.  When I pivot, the column names created from the pivot are sorted alphanumerically.
pivot_df = merged_df.pivot(index=test_events_key_columns, columns='VERSION_INDEX', values='Status')
print(pivot_df)

Is it possible to keep the column order numeric during the pivot such that 9 comes before 87?
thx

A: In Polars, column names are always stored as strings, and hence you have the alphanumeric sorting rather than numeric. There is no way around the strings, so I think the best you can do is to compute the column order you want, and select the columns:
import polars as pl

df = pl.DataFrame({"version": [9, 85, 87], "testsuite": ["scan1", "scan2", "scan3"], "status": ["ok"] * 3})
wide = df.pivot(index="testsuite", columns='version', values='status')
cols = df["version"].cast(pl.Utf8).to_list()
wide[["testsuite"] + cols]

┌───────────┬──────┬──────┬──────┐
│ testsuite ┆ 9    ┆ 85   ┆ 87   │
│ ---       ┆ ---  ┆ ---  ┆ ---  │
│ str       ┆ str  ┆ str  ┆ str  │
╞═══════════╪══════╪══════╪══════╡
│ scan1     ┆ ok   ┆ null ┆ null │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ scan2     ┆ null ┆ ok   ┆ null │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ scan3     ┆ null ┆ null ┆ ok   │
└───────────┴──────┴──────┴──────┘


Q: Modifying website through email I wanted to try to do something where I can make changes to my site based on emails received to the sites email. Does anyone know how to do that?
I want something where if its from a specific email address, and follows a particular format, it will change a certain part of the site according to the contents of the email.

A: Sure you can.
You need:

*

*Script that parses emails on schedule and adds those changes to some type of database

*Script that executes updates from the temporary database and adds that data to live database

How to read email with PHP:
$mb = imap_open("{host:port/imap}","username", "password" );

$messageCount = imap_num_msg($mb);
for( $MID = 1; $MID <= $messageCount; $MID++ )
{
   $EmailHeaders = imap_headerinfo( $mb, $MID );
   $Body = imap_fetchbody( $mb, $MID, 1 );
   doSomething( $EmailHeaders, $Body );
}

read more

A: You would need some server side processing to be able to do this. This thread has a couple of ways of doing this using PHP, made easier with cPanel to make changes to the mail redirects. If you tell us more about your site and hosting environment, we may be able to give better suggestions.
The server side script would need to then parse your email and perform whatever updates your commands intend. Security is also very important, and it is trivial to forge the 'From' address when sending email.


Q: Laravel remote method is giving 404 (Not Found)error for title existed checking I am using Laravel framework. When I am trying to check if title already exists it is giving a 404 error. How to solve this error?
ServicesController.php
Controller:

public function checkEmail()
    {
        $service = Service::all()->where('title', Input::get('title'))->first();
        if ($service) {
            return Response::json(Input::get('title').'is already taken');
        } else {
            return Response::json(Input::get('title').'is available');
        }
    }

Routes.php:

Route::get('checkEmail','ServicesController@checkEmail');

view(create.blade.php):
$("#slider-form").validate({
  rules: {
    title: {
      required: true,
      remote: {
        url: "checkEmail",
        type: "get",
      }

    },
    ar_title: {
      required: true
    }
  },
  messages: {
    title: {
      required: "Please Enter Service Name",
      remote: "Service Already Exists"
    },
    ar_title: {
      required: "Please Enter Service Name in Arabic"
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});

A: AS your form is like this
<form class="form-horizontal tasi-form" method="post" name="user-form" action="{{url('services/store')}}" id="slider-form" enctype="multipart/form-data">

Add an route in your route file as
Route::post('services/store','ServicesController@checkEmail');

Modified:- Change
    <form class="form-horizontal tasi-form" method="post" name="user-form" action="services/store"
       id="slider-form" enctype="multipart/form-data">
Route::post('services/store','ServicesController@checkEmail');

Then try
It will work for you.


Q: Upgrade option is disabled while trying to upgrade to 14.04 using DVD I tried to upgrade my Ubuntu 13.10 to 14.04 using DVD. When I want to upgrade, upgrade option is disabled. It seems I have to erase 13.10, so all of programs will be deleted.
What's the problem? Why I can't upgarade?

A: I found the problem myself. I should first run the Live version and then upgrade using Ubuntu Live.


Q: Opening a modal component with a button in another ccomponent using Vuetify I have 2 components. Modal and Navbar. I'm trying to open Modal using a button in Navbar using vuex. I have a state called modalIsOpen. This states value changes from false to true when clicked on the button in Navbar but only a blank row is rendered as a modal and modal content is not shown. I could not figure out what is wrong.
At the beginning i thought it was a vuetify v-dialog problem. But ive tried other libraries too. And as i said nothing worked yet.
Here is the components ,app.vue and store.js.
AddUpdateModal.vue:
<template>
  <v-dialog>
    <v-card width="50%" height="50%">
      <v-card-title class="text-h5 grey lighten-2">
        Privacy Policy
      </v-card-title>
      <v-card-text>
        Lorem
      </v-card-text>
      <v-divider></v-divider>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn color="primary" text @click="dialog = false">
          I accept
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

NavBar.vue:
<template>

    <v-row>
      <v-btn color="primary" @click.stop="openModal" rounded>
        Add / Update
      </v-btn>
      <v-btn color="primary" @click="closeModal" rounded>
        Refresh
      </v-btn>
    </v-row>
    <v-row>
      <v-divider class="grey darken-4"></v-divider>
    </v-row>

</template>

App.vue:
<template>
  <v-app>
    <v-container>
      <NavBar />

        <v-btn @click="konsol">Konsol</v-btn>

          <template>
            <AddUpdateModal></AddUpdateModal>
          </template>

        <v-row>
          <v-col>
            <DataTable />
          </v-col>
          <v-divider class="grey darken-4" vertical inset></v-divider>
          <v-col>
            <PieChart />
          </v-col>
        </v-row>

    </v-container>
  </v-app>
</template>

store.js:
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    binance24HrData: [],
    modalIsOpen: false,
  },

    mutations: {
        initPortfolioDetails(state, newCoin) {
        state.binance24HrData = newCoin;
        },
        openModal(state) {
        state.modalIsOpen = true;
        },
        closeModal(state) {
        state.modalIsOpen = false;
        },
    },

    actions: {
        initApp(context) {
        axios
            .get("https://api2.binance.com/api/v3/ticker/24hr")
            .then((response) => {
            context.commit("initPortfolioDetails", response.data);
            console.log("Binance", response.data);
            });
        },

        openModal({ commit }) {
        commit("openModal");
        },

        closeModal({ commit }) {
        commit("closeModal");
        },
    },

    getters: {
        getCoinsDetails(state) {
        return state.binance24HrData;
        },
    },
});

export default store;

main.js:
import Vue from "vue";
import App from "./App.vue";
import vuetify from "./plugins/vuetify";
import store from "./store/store.js";

Vue.config.productionTip = false;

new Vue({
  vuetify,
  store,
  render: (h) => h(App),
}).$mount("#app");

A: I figured it out: all I had to do was add v-model to v-dialog. I thought  it was unnecessary because I already had a v-if that wrapped the component containing the v-dialog. I assumed that with this requirement fulfilled, it should render the child component, but it didn't because I didn't have v-model in v-dialog.


Q: When to trust the result of numerical integration in mathematica? How does one know when to trust the result of numerical integration, using NIntegrate, for higher (5 or 6) dimensional integrals in mathematica? For example, I get the following result
Integrate[ Exp[-a^2 - b^2 - c^2 - x^2 - y^2 - z^2], {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, {a, -2, 2}, {b, -2, 2}, {c, -2, 2}] // N

(* 30.1462 *)

whereas if I do the same integral numerically, I get
NIntegrate[ Exp[-a^2 - b^2 - c^2 - x^2 - y^2 - z^2], {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, {a, -2, 2}, {b, -2, 2}, {c, -2, 2}] // N

During evaluation of In[2]:= NIntegrate::eincr: The global error of the strategy
GlobalAdaptive has increased more than 2000 times. The global error is expected
to decrease monotonically after a number of integrand evaluations. Suspect one
of the following: the working precision is insufficient for the specified
precision goal; the integrand is highly oscillatory or it is not a (piecewise)
smooth function; or the true value of the integral is 0. Increasing the value of
the GlobalAdaptive option MaxErrorIncreases might lead to a convergent
numerical integration. NIntegrate obtained 30.14615590437465 and
0.0001823733624988688 for the integral and error estimates.

Out[2]= 30.1462

This seems to indicate that one can trust the result of NIntegrate if the error estimate is a small percentage (~1%) of the estimated value of the integral. If that's true then how would one understand the discrepancy in the values obtained in the following two cases when Mathematica does not report any errors.
NIntegrate[ Exp[-a^2 - b^2 - c^2 - x^2 + y^2], {x, -2, 2}, {y, -2, 2}, {a, -2, 2}, {b, -2, 2}, {c, -2, 2}, Method -> "AdaptiveMonteCarlo"] // N

(* 298.918 *)

NIntegrate[ Exp[-a^2 - b^2 - c^2 - x^2 + y^2], {x, -2, 2}, {y, -2, 2}, {a, -2, 2}, {b, -2, 2}, {c, -2, 2}, Method -> "MonteCarloRule"] // N

(* 313.592  *)

In the following example, I also get a result with an error bar that is a small (~2%) percentage of the value of the integral
In[7]:= NIntegrate[ Exp[-a^2 - b^2 - c^2 - x^2 - y^2 - z^2], {x, -5, 5}, {y, -5, 5}, {z, -5, 5}, {a, -5, 5}, {b, -5, 5}, {c, -5, 5}, Method -> "AdaptiveQuasiMonteCarlo"] // N

During evaluation of In[7]:= NIntegrate::maxp: The integral failed to converge
after 1000100 integrand evaluations. NIntegrate obtained 0.29686054547957375 and
0.005304460608762476 for the integral and error estimates.

Out[7]= 0.296861

but comparing it with the following analytic evaluation of the integral
Integrate[ Exp[-a^2 - b^2 - c^2 - x^2 - y^2 - z^2], {x, -5, 5}, {y, -5, 5}, {z, -5, 5}, {a, -5, 5}, {b, -5, 5}, {c, -5, 5}] // N

(* 31.0063 *)

we see that the answer is way off. Any guidance in this regard will be greatly appreciated.


Q: Is it possible to get the price of bitcoin in USD from the coinbase API for a specific time in the past? GET https://api.coinbase.com/v2/prices/:currency_pair/spot
This price seems to be the current price

A: This question already has answers. Copy and pasted from here: Coinbase API v2 Getting Historic Price for Multiple Days

Any reason you aren't using coinbase pro?

The new api is very easy to use. Simply add the get command you want followed by the parameters separated with a question mark. Here is the new historic rates api documentation: https://docs.pro.coinbase.com/#get-historic-rates

The get command with the new api most similar to prices is "candles". It requires three parameters to be identified, start and stop time in iso format and granularity which is in seconds. Here is an example:

https://api.pro.coinbase.com/products/BTC-USD/candles?start=2018-07-10T12:00:00&stop=2018-07-15T12:00:00&granularity=900

EDIT: also, note the time zone is not for your time zone, I believe its GMT.


Q: How to append to JSON with Java and Jackson I'm trying a simple test where the code appends a few json entries, however it is getting overwritten each time (the json file will only have 1 entry in it after running). I know I need to somehow create an array in JSON using '[]', but how would I go about doing that? Also, is there a better way to be doing this? I've been searching around and every library seems clunky with lots of user written code. Thanks
public class REEEE {

private static Staff createStaff() {

    Staff staff = new Staff();

    staff.setName("mkyong");
    staff.setAge(38);
    staff.setPosition(new String[] { "Founder", "CTO", "Writer" });
    Map<String, Double> salary = new HashMap() {
        {
            put("2010", 10000.69);
        }
    };
    staff.setSalary(salary);
    staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

    return staff;
}

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    File file = new File("src//j.json");
    for(int i = 0; i < 4; i++) {
        Staff staff = createStaff();

        try {
            // Java objects to JSON file
            mapper.writeValue(file, staff);

            // Java objects to JSON string - compact-print
            String jsonString = mapper.writeValueAsString(staff);

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

A: You can add staff in List and then write the list to file as below,
List<Staff> staffList = new LinkedList<>()
for(int i = 0; i < 4; i++) {
    Staff staff = createStaff();
    staffList.add(staff);
}
mapper.writeValue(file, staffList);

Hope it helps.

A: Jackson was implemented to parse and generate JSON payloads. All extra logic related with adding new element to array and writing back to file you need to implement yourself. It should not be hard to do:
class JsonFileAppender {
    private final ObjectMapper jsonMapper;

    public JsonFileAppender() {
        this.jsonMapper = JsonMapper.builder().build();
    }

    public void appendToArray(File jsonFile, Object value) throws IOException {
        Objects.requireNonNull(jsonFile);
        Objects.requireNonNull(value);
        if (jsonFile.isDirectory()) {
            throw new IllegalArgumentException("File can not be a directory!");
        }

        JsonNode node = readArrayOrCreateNew(jsonFile);
        if (node.isArray()) {
            ArrayNode array = (ArrayNode) node;
            array.addPOJO(value);
        } else {
            ArrayNode rootArray = jsonMapper.createArrayNode();
            rootArray.add(node);
            rootArray.addPOJO(value);
            node = rootArray;
        }
        jsonMapper.writeValue(jsonFile, node);
    }

    private JsonNode readArrayOrCreateNew(File jsonFile) throws IOException {
        if (jsonFile.exists() && jsonFile.length() > 0) {
            return jsonMapper.readTree(jsonFile);
        }

        return jsonMapper.createArrayNode();
    }
}

Example usage with some usecases:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        Path jsonTmpFile = Files.createTempFile("json", "array");
        JsonFileAppender jfa = new JsonFileAppender();

        // Add POJO
        jfa.appendToArray(jsonTmpFile.toFile(), createStaff());
        printContent(jsonTmpFile); //1

        // Add primitive
        jfa.appendToArray(jsonTmpFile.toFile(), "Jackson");
        printContent(jsonTmpFile); //2

        // Add another array
        jfa.appendToArray(jsonTmpFile.toFile(), Arrays.asList("Version: ", 2, 10, 0));
        printContent(jsonTmpFile); //3

        // Add another object
        jfa.appendToArray(jsonTmpFile.toFile(), Collections.singletonMap("simple", "object"));
        printContent(jsonTmpFile); //4
    }

    private static Staff createStaff() {
        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map<String, Double> salary = new HashMap<>();
        salary.put("2010", 10000.69);

        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;
    }

    private static void printContent(Path path) throws IOException {
        List<String> lines = Files.readAllLines(path);
        System.out.println(String.join("", lines));
    }
}

Above code prints 4 lines:
1
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]}]

2
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson"]

3
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0]]

4
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0],{"simple":"object"}]


Q: What's the most efficient way to find if a mac address is in range? I have a large range of number of strings that are mac addresses. If they're in a certain range, I want to be able to go to a certain case statement.
For example, "78:A1:83:24:00:00 to 78:A1:83:24:0F:FF"
I have my code going so that it removes the last two hex and selects off that such as below:
 'remove last three characters
    mac = mac.TrimEnd()
    mac = mac.Substring(0, mac.Length - 3)

    'convert
    Select Case mac

        'Advidia
       Case "78:A1:83:40:00", "78:A1:83:40:01", "78:A1:83:40:02", "78:A1:83:40:03", _
             "78:A1:83:40:04", "78:A1:83:40:05", "78:A1:83:40:06", "78:A1:83:40:07", _
            "78:A1:83:40:08", "78:A1:83:40:09", "78:A1:83:40:0A", "78:A1:83:40:0B"
             ' it continues
            Return "VP-1"

But this just looks like I'm wasting space. What's a better way to this?

A: A MAC address is nothing more than a number represented by 6 bytes written in hexdecimal form.
So, converting the lower and upper limit of the MAC address could give you a manageable range of values to check with a single IF
Sub Main
    Dim lowRange = "78:A1:83:24:40:00"
    Dim upRange = "78:A1:83:24:40:FF"

    Dim startVal = GetValue(lowRange)
    Dim endVal = GetValue(upRange)
    Console.WriteLine(startVal)   ' 132635085258752
    Console.WriteLine(endVal)     ' 132635085259007

    Dim macToCheck = "78:A1:83:24:40:B0"
    Dim checkVal = GetValue(macToCheck)
    Console.WriteLine(checkVal)   ' 132635085258928

    if checkVal >= startVal AndAlso checkVal <= endVal Then
        ' VP-1
        Console.WriteLine("In range")
    End If

End SUb

Function GetValue(mac as String ) as Long
    Dim clearText = mac.Replace(":", "")
    Dim result
    Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result)
    return result
End Function

Now, as an example to avoid a long list of IF you could use a Dictionary filled with your ranges and then apply a simple For Each logic to find your ranges
Sub Main
    Dim dc as New Dictionary(Of String, MacRange)()
    dc.Add("VP-1", new MacRange() with
    {
        .Lower = "78:A1:83:24:40:00",
        .Upper = "78:A1:83:24:40:FF"
    })

    dc.Add("VP-2", new MacRange() with
    {
        .Lower = "78:A1:83:24:41:00",
        .Upper = "78:A1:83:24:41:FF"
    })

    dc.Add("VP-3", new MacRange() with
    {
        .Lower = "78:A1:83:24:42:00",
        .Upper = "78:A1:83:24:42:FF"
    })

    Dim result = ""
    Dim macToCheck = "78:A1:83:24:42:B0"
    Dim checkVal = GetValue(macToCheck)
    'For Each k in dc
    '    Dim lower = GetValue(k.Value.Lower)
    '    Dim upper = GetValue(k.Value.Upper)
    '    if checkVal >= lower AndAlso checkVal <= upper Then
    '        result = k.Key
    '        Exit For
    '    End If
    'Next
    'Console.WriteLine(result)   ' VP-3

    ' The loop above could be replaced by this LINQ expression
    Dim m = dc.FirstOrDefault(Function(x) checkVal >= GetValue(x.Value.Lower) AndAlso _
                                          checkVal <= GetValue(x.Value.Upper))
    If m IsNot Nothing Then
         Console.WriteLine(m.Key)  ' VP-3
    Else
         Console.WriteLine("Range not found")
    End If

End Sub

Class MacRange
    Public Lower as String
    Public Upper as String
End Class

Function GetValue(mac as String ) as Long
    Dim clearText = mac.Replace(":", "")
    Dim result
    Long.TryParse(clearText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, result)
    return result
End Function

A: There aren't existing functions that provide such utility. You could just split each string and create your ranges manually.

A: I'd use some sort of regex (Regular Expression) validation for various ranges.
http://regexlib.com/Search.aspx?k=mac%20address&AspxAutoDetectCookieSupport=1
will give you a good starting point.


Q: Determine the most general Mobius transform that... Determine the most general Mobius transform that satisfies:
i) two fixed points z=0 and z=1;
ii) maps the unit circle $|z|=1$ and the bisector of first and third quarter to lines.
My guess is: $$\frac{cz(1 \pm \frac{1}{\sqrt{2}}(1+i))}{cz \pm \frac{c}{\sqrt{2}}(1+i)}$$ where $c \in \mathbb{C}$
May you tell me if it's correct?
edit:
In the (ii) i want to say that the Mobius $$\frac{az+b}{cz+d}$$ transformations takes the points of the complex plane $|z|=1$ and $z(t) = t e^{i \frac{\pi}{4}}$ in lines (so I infer that the point $-\frac{d}{c}$ is one of the two points of intersection between $|z|=1$ and $z(t) = t$.

A: In order to satisfy condition (i) we can write the transformation as $$w=\frac{az}{z+a-1}$$ for some $a\in\mathbb{C}$
We can rearrange and write this as $$z=\frac{w-aw}{w-a}$$
In order to apply the conditions in (ii), we can set $w=u+iv$ and $a=p+iq$
Firstly, the locus $|z|=1$ becomes $|w-aw|=|w-a|$ which is equivalent to $$(u(1-p)+qv)^2+(v(1-p)-qu)^2=(u-p)^2+(v-q)^2$$
For this to represent a line, we require the coefficients of $u^2$ and $v^2$ to be zero, each of which give the relation $$(1-p)^2+q^2=1$$
In addition the coefficient of $uv$ is identically zero.
Secondly, we require the image of the locus $Re(z)=Im(z)$ also to be a line, and after a few lines of algebra, we get $$q=p-1$$
So the possible values of $a$ are $$1\pm\frac{1}{\sqrt{2}}(1+i)$$


Q: Method lookup in Ruby's interrelation diagram? Can someone explain the relation between the Ruby class interrelation diagram and the way method lookup is done in the actual Ruby C code?
Interrelation diagram from https://ruby-doc.org/core-2.5.3/Class.html:
                     +---------+             +-...
                     |         |             |
     BasicObject-----|-->(BasicObject)-------|-...
         ^           |         ^             |
         |           |         |             |
      Object---------|----->(Object)---------|-...
         ^           |         ^             |
         |           |         |             |
         +-------+   |         +--------+    |
         |       |   |         |        |    |
         |    Module-|---------|--->(Module)-|-...
         |       ^   |         |        ^    |
         |       |   |         |        |    |
         |     Class-|---------|---->(Class)-|-...
         |       ^   |         |        ^    |
         |       +---+         |        +----+
         |                     |
 obj--->OtherClass---------->(OtherClass)-----------...

and the lookup in Ruby code seems to traverse RClass's super member as a flat list here: pseudocode
while (!st_lookup(RCLASS(klass)->m_tbl, ...)) {
    klass = RCLASS(klass)->super;
    ...
}

Where in the above diagram would the internal RClass.super and RBasic.klass (C structures)
 pointer-arrows be mapped ?  Which path would the method lookup take in this diagram? In particular the diagram seems to contain cycles. How is that to be interpreted? What does the ... in
obj--->OtherClass---------->(OtherClass)-----------...

mean (singleton of a singleton ?), how is singleton of a singleton accessed in Ruby  and how is it  modeled in the C implementation?

A: I diggged around a bit and the  ancestor function seem to traverse the RClass.super c-struct member, the same as the method looup does. So when I do a
class OtherClass end
obj = OtherClass.new
obj.class.singleton_class.singleton_class.ancestors =>
[#<Class:#<Class:OtherClass>>, \
 #<Class:#<Class:Object>>, \
 #<Class:#<Class:BasicObject>>, \
 #<Class:Class>, \
 #<Class:Module>, \
 #<Class:Object>, \
 #<Class:BasicObject>, \
 Class, \
 Module, \
 Object, \
 Kernel, \
 BasicObject]

     BasicObject
          ^           +---------+                 +--------+
          |           |         |                 |        |
      Kernel          | #<Class:BasicObject>      | #<Class:#<Class:BasicObject>>
          ^           |         ^                 |        ^
          |           |         |                 |        |
       Object         |   #<Class:Object>         | #<Class:#<Class:Object>>
          ^           |         ^                 |        ^
          |           |         |                 |        |
          +-------+   |         +--------+        |        |
                  |   |                  |        |        |
               Module |           #<Class:Module> |        |
                  ^   |                  ^        |        |
                  |   |                  |        |        |
                Class |           #<Class:Class>  |        |
                  ^   |                  ^        |        |
                  +---+                  +--------+        |
                                                           |
obj--->OtherClass --->#<Class:OtherClass>--->#<Class:#<Class:OtherClass>>

That means the vertical arrows in the diagram can be seen as the RClass.super c-member traversal.  The horizontal arrows on the other hand should be related to RBasic.klass,  however the Ruby code seems asymetric.
             ...
              |
obj--->   OtherClass

When a singleton class is created the former RBasic.klass will get the RClass.super of the new singleton class.
             ...                           ...
            Object                   #<Class:Object>
              ^                             ^
              |                             |
          OtherClass                        |
              ^                             |
              |                             |
obj--->#<Class:#OtherClass:0x...> ->#<Class:OtherClass> -+
                                                       ^-+

and going one step futher a singleton of a singleton then looks like:
             ...                         ...                        ...
            Object                  #<Class:Object>          #Class<#<Class:Object>>
              ^                           ^                          ^
              |                           |                          |
          OtherClass                      |                          |
              ^                           |                          |
              |                           |                          |
obj-->#<Class:#OtherClass:0x...>-->#<Class:OtherClass>-->#<Class:#<Class:OtherClass>>-+
                                                                                ^-+

The meaning/usage of a singleton class is understandable, however there meaning/usage of the metaclasses is a bit esoteric.


Q: Search history in elasticsearch Is there any way to check search history in elasticsearch?
I'm wondering how seek someone responsible for data leakage in organization if it happen.


Q: Why don't my fabric control parameters work? Here is my fabric function:
def replace_config(vim_sig, bash_sig):
    """ replace remote server config with local config
    """
    default_path = change_path('config', default_path='~/')

    if vim_sig:
        local("scp %s.vimrc admin@%s:~/vimrc" % (default_path, env.host))
        sudo("cp /home/admin/vimrc /home/admin/.vimrc")
        sudo("cp  /home/admin/vimrc /root/.vimrc")
        sudo("rm /home/admin/vimrc")

    if bash_sig:
        local("scp %s.bashrc admin@%s:~/bashrc" % (default_path, env.host))
        sudo("cp /home/admin/bashrc /home/admin/.bashrc")
        sudo("cp  /home/admin/bashrc /root/.bashrc")
        sudo("rm /home/admin/bashrc")

# Some other code was omitted here

I executed it with fab replace_config:vim_sig=False,bash_sig=True, fab replace_config:False,True, and fab replace_config:0,1, but these commands copy vimrc to remote host and ignore the if vim_sig statement.
Why did this happen? How can I fix it?
My fabric version is 1.10.1, and the way I execute the fab with parameters was taken from here.


Q: Standard deviation formula confusion I'm having trouble understanding the formula for standard deviation .
I know how to calculate standard deviation,  but I cant understand some parts of the formula . I'll give you an example
$$\sigma=\sqrt{\frac 1N \sum_{i=1}^N(x_i-\mu)^2}$$
Say we have a bunch of numbers like $9, 2, 5, 4, 15$
This part of the formula says subtract the Mean and square the result
$(x_i-\mu)^2$
The mean is 7  and when I subtract and square I get
4,  25,  4, 9, 64
This is where I get stuck - I know I have to add up all the values then divide by how many
$\displaystyle \frac 1N \sum_{i=1}^N$
but how does this part of the formula say that?
I know the sigma means add up
but what does the $N$ on top of sigma mean?
what does the $i=1$ at the bottom of sigma mean ?

A: This might be the kind of operation best explained by an example.  I'll refer you to wikipedia, but also write out an example.  The $i$ is an index variable, $i=1$ down below means you start counting with $i$ at $1$ and the $N$ on top means you stop counting when $i$ reaches $N$.  So for example,
$$\sum_{i = 1}^3 (x_i - \mu)^2 = (x_1 - \mu)^2 + (x_2 - \mu)^2 + (x_3 -\mu)^2$$
In your particular case, the $x_i$ are the sample values you have, $x_1 = 4, x_2 =25$, etc.  Does that make sense?

A: You have $9,2,5,4,15$. There are five numbers here, so $N=5$.
\begin{align}
x_1 & = 9 & & \text{In this case, $i$=1.} \\
x_2 & = 2 & & \text{In this case, $i$=2.} \\
x_3 & = 5 & & \text{In this case, $i$=3.} \\
x_4 & = 4 & & \text{In this case, $i$=4.} \\
x_5 & = 15 & &  \text{In this case, $i=5=N$.}
\end{align}
$$
\overbrace{\frac 1 N\sum_{i=1}^N (x_i-\mu)^2 = \frac 1 5 \sum_{i=1}^5(x_i-\mu)^2}^{\text{This is true because $N=5$.}}
$$
$$
\frac 1 5 \sum_{i=1}^5(x_i-\mu)^2=\frac 1 5 \Big( (x_1-\mu)^2 + (x_2-\mu)^2 + (x_3-\mu)^2+(x_4-\mu)^2+(x_5-\mu)^2 \Big)
$$
$$
\frac 1 5 \sum_{i=1}^5(x_i-7)^2=\frac 1 5 \Big( (x_1-7)^2 + (x_2-7)^2 + (x_3-7)^2+(x_4-7)^2+(x_5-7)^2 \Big)
$$
$$
\frac 1 5 \sum_{i=1}^5(x_i-7)^2=\frac 1 5 \Big( (9-7)^2 + (2-7)^2 + (5-7)^2+(4-7)^2+(15-7)^2 \Big)
$$

A: The i at the bottom tells you where to start adding up. If the bottom of the sigma has $i=1$, then start adding the stuff to the right of the sigma, but substitute any i's in the equation for 1. After you do that i becomes 2. Add everything to the right, but substitute any i's in the equation with 2. Keep doing that until you reach a new i equal to the top part of the sigma plus one. The top part tells you when to stop adding. In this case its N. So you add until you reach the number of samples you have to add. One more thing. $x_i$ refers to the ith variable that you are considering. If you have a list like $2,3,7$, $x_3$ refers to 7. Keep that in mind when using the sigma.

A: I am not sure if I completely understand your questions but, i = 1 on the bottom and the N on the top of the sum are simply the number of terms that are in the sequence for example: $$\sum_{i = 0}^{3} i = 0 + 1 + 2 + 3 = 6$$ for your equation your given a set of numbers 9, 2, 5, 4, 15 the $x_i$ are these numbers so $x_1 = 9$, $x_2 = 2$, etc. I hope that sort of helps


Q: Get elements and count of Array of unknown type Let's say we have an Array, assigned to a variable with the type Any
let something: Any = ["one", "two", "three"]

Let's also assume we don't know if it's an array or something entirely else. And we also don't know what kind of Array.Element we are dealing with exactly.
Now we want to find out if it's an array.
let isArray = something is Array // compiler error
let isArray = (something as? [Any?] != nil) // does not work (array is [String] and not [Any?])

Is there any elegant solution to tickle the following information out of the swift type system:

*

*Is the given object an Array

*What's the count of the array

*Give me the elements of the array

(bridging to NSArray is not a solution for me, because my array could also be of type [Any?] and contain nil-values)

A: I love @stefreak's question and his solution. Bearing in mind @dfri's excellent answer about Swift's runtime introspection, however, we can simplify and generalise @stefreak's "type tagging" approach to some extent:
protocol AnySequenceType {
    var anyElements: [Any?] { get }
}

extension AnySequenceType where Self : SequenceType {
    var anyElements: [Any?] {
        return map{
            $0 is NilLiteralConvertible ? Mirror(reflecting: $0).children.first?.value : $0
        }
    }
}

extension Array : AnySequenceType {}
extension Set   : AnySequenceType {}
//    ... Dictionary, etc.

Use:
let things:  Any = [1, 2]
let maybies: Any = [1, nil] as [Int?]

(things  as? AnySequenceType)?.anyElements // [{Some 1}, {Some 2}]
(maybies as? AnySequenceType)?.anyElements // [{Some 1}, nil]

See Swift Evolution mailing list discussion on the possibility of allowing protocol extensions along the lines of:
extension<T> Sequence where Element == T?

In current practice, however, the more common and somewhat anticlimactic solution would be to:
things as? AnyObject as? [AnyObject] // [1, 2]

// ... which at present (Swift 2.2) passes through `NSArray`, i.e. as if we:

import Foundation
things as? NSArray  // [1, 2]

// ... which is also why this fails for `mabyies`
maybies as? NSArray // nil

At any rate, what all this drives home for me is that once you loose type information there is no going back. Even if you reflect on the Mirror you still end up with a dynamicType which you must switch through to an expected type so you can cast the value and use it as such... all at runtime, all forever outside the compile time checks and sanity.

A: As an alternative to @milos and OP:s protocol conformance check, I'll add a method using runtime introspection of something (foo and bar in examples below).
/* returns an array if argument is an array, otherwise, nil */
func getAsCleanArray(something: Any) -> [Any]? {
    let mirr = Mirror(reflecting: something)
    var somethingAsArray : [Any] = []
    guard let disp = mirr.displayStyle where disp == .Collection else {
        return nil // not array
    }

    /* OK, is array: add element into a mutable that
     the compiler actually treats as an array */
    for (_, val) in Mirror(reflecting: something).children {
        somethingAsArray.append(val)
    }

    return somethingAsArray
}

Example usage:
/* example usage */
let foo: Any = ["one", 2, "three"]
let bar: [Any?] = ["one", 2, "three", nil, "five"]

if let foobar = getAsCleanArray(foo) {
    print("Count: \(foobar.count)\n--------")
    foobar.forEach { print($0) }
} /* Count: 3
     --------
     one
     2
     three      */

if let foobar = getAsCleanArray(bar) {
    print("Count: \(foobar.count)\n-------------")
    foobar.forEach { print($0) }
} /* Count: 5
     -------------
     Optional("one")
     Optional(2)
     Optional("three")
     nil
     Optional("five")  */

A: The only solution I came up with is the following, but I don't know if it's the most elegant one :)
protocol AnyOptional {
    var anyOptionalValue: Optional<Any> { get }
}
extension Optional: AnyOptional {
    var anyOptionalValue: Optional<Any> {
        return self
    }
}
protocol AnyArray {
    var count: Int { get }
    var allElementsAsOptional: [Any?] { get }
}
extension Array: AnyArray {
    var allElementsAsOptional: [Any?] {
        return self.map {
            if let optional = $0 as? AnyOptional {
                return optional.anyOptionalValue
            }
            return $0 as Any?
        }
    }
}

Now you can just say
if let array = something as? AnyArray {
    print(array.count)
    print(array.allElementsAsOptional)
}

A: This works for me on a playground:
// Generate fake data of random stuff
let array: [Any?] = ["one", "two", "three", nil, 1]
// Cast to Any to simulate unknown object received
let something: Any = array as Any

// Use if let to see if we can cast that object into an array
if let newArray = something as? [Any?] {
    // You now know that newArray is your received object cast as an
    // array and can get the count or the elements
} else {
    // Your object is not an array, handle however you need.
}

A: I found that casting to AnyObject works for an array of objects.  Still working on a solution for value types.
let something: Any = ["one", "two", "three"]

if let aThing = something as? [Any] {
    print(aThing.dynamicType) // doesn't enter
}

if let aThing = something as? AnyObject {
    if let theThing = aThing as? [AnyObject] {
        print(theThing.dynamicType) // Array<AnyObject>
    }
}


Q: Convert Array of object to json in javascript I want to Convert Arraylist of object to json in javascript to use it in highchart and angularjs.
Can Anyone  help me how can i do that?
data should look like that
                                [
                                    ['Firefox',   45.0],
                                    ['IE',       26.8],
                                    ['Safari',    8.5],
                                    ['Opera',     6.2],
                                    ['Others',   0.7]
                                ]

A: You can use JSON.stringify(array) if you just need to create a string out of an array


Q: How to get the mean value of the Gaussian basis functions comprising $x$ when solving $Ax=b$ problem? For the linear equation
$$
Ax=b,
$$
where $A$ is a 100 x 64 matrix, $b$ is a 100 x 1 vector, $x$ is a 64 x 1 vector, unknown.
In my situation, x consists of no more than 5 Gaussian basis.
$$
x=\Sigma_{i=1}^5 F_i \exp\left(-\frac{(T-T \mathrm{mean}_i)^2}{W_i}\right)
$$
Here T is a known 64 x 1 vector, $W_i$ controls the width of the distribution and $F_i$ is the amplitude of the Gaussian basis. $F_i$, $W_i$ and $T\mathrm{mean}_i$ are undetermined parameters.
$A$,$b$,$T$ are attached here.
What I am interested in is the $T\mathrm{mean}_i$, i.e. the number of Gaussian basis and the center of the existing Gaussian ($A_i>0$).


Q: Automatically resize tabular to avoid it being pushed to next page Context
My document has one title phrase and one table containing texts. I would like to have them both on one page.

*

*The table's content may change (sometimes more or less 2-or-3-lines-texts cells), but there are always 2 columns and 20 rows. I have put a minimal row height of 0.5 cm for readability.

*I do not want to split the table over the next page

*But I want the text to be as big as possible.
Attempts
If I use a smaller size, (like \normalsize instead of \large) then it fits, but the font is much smaller and actually a bit too small, whereas a large blank space is left at the bottom of the page.
So, as I want to resize (or scale?) it automatically, I thought the answer would be here and wanted to use the adjustbox package, but I can't seem to make it work the way I want. I'm a bit lost about all the keys and values meanings. Anyway, neither \adjustbox{max width=\columnwidth} nor \adjustbox{max width=\textwidth} provide a solution. I couldn't find any solution using max height or max totalheight.
Also, I wonder if my problem has to do with the more general problem of the position of a float environment. Not sure because if the table is too large, I understand LaTeX will "push" it to the next page. But if yes, how to deal with it in this situation?
Finally I wonder if it's at all possible to achieve what I want to (moreover, using tabular).
Code producing the problem
\documentclass[a4paper,fleqn,12pt]{article}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[british]{babel}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{geometry}
\usepackage{array}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{adjustbox}

% Page layout
\geometry{hmargin=1.5cm, vmargin=1.5cm}
\setlength{\parindent}{0cm}
\pagestyle{empty}

\begin{document}
\LARGE
\textbf{Mental calculation: mini-problems}
\newline \newline \large
\adjustbox{max width=\textwidth}{
\begin{tabular}{|>{\centering}m{14 cm}|>{\centering}m{4 cm}@{}m{0pt}@{}|}
\hline
My golden goose laid 4 eggs each day during 9 days. How many eggs has she laid?&
 & \tabularnewline
 [0.5cm] \hline
Mya has 40 marbles. She gives them out to 5 friends. How many marbles will get each friend?&
 & \tabularnewline
 [0.5cm] \hline
We have 4 sheep. Our neighbours have 7 times more sheep than us. How many sheep do they have?&
 & \tabularnewline
 [0.5cm] \hline
I will give out 72 candies to the 8 friends that I invited at my birthday's party. How many candies will receive each of my friends?&
 & \tabularnewline
 [0.5cm] \hline
I had to fill this can with 18$~\text{L}$ of water. There was 7$~\text{L}$ left in it. How much does it contain?&
...............$~\text{L}$ & \tabularnewline
 [0.5cm] \hline
We have loaded 64$~\text{kg}$ of flour, shared in 8 packets. How heavy is one packet?&
...............$~\text{kg}$ & \tabularnewline
 [0.5cm] \hline
A market gardener had 72 cabbages in his vegetable garden, and harvested 54 of them last week. How many cabbages are still in the garden?&
 & \tabularnewline
 [0.5cm] \hline
9$~\text{m}^{2}$ of this wall are already painted. 7$~\text{m}^{2}$ are still missing to have the wall completely painted. What is its area?&
...............$~\text{m}^{2}$ & \tabularnewline
 [0.5cm] \hline
I already rode 84$~\text{km}$ out of 98$~\text{km}$. How long do I still have to go cycling?&
...............$~\text{km}$ & \tabularnewline
 [0.5cm] \hline
Lily gets 6 £ pocket money every month. If she doesn't spend it during 7 months, how much will she spare?&
...............~£ & \tabularnewline
 [0.5cm] \hline
Yesterday, my golden goose laid 8 eggs. That's 11 less than today. How many eggs has she laid today?&
 & \tabularnewline
 [0.5cm] \hline
Janet bought 8 boxes of 7 pencils. How many pens did she buy?&
 & \tabularnewline
 [0.5cm] \hline
A market gardener had 78 cabbages in his vegetable garden, and harvested 56 of them last week. How many cabbages are still in the garden?&
 & \tabularnewline
 [0.5cm] \hline
I will give out 49 candies to the 7 friends that I invited at my birthday's party. How many candies will receive each of my friends?&
 & \tabularnewline
 [0.5cm] \hline
Jerry has 17 marbles. Elijah has 17 marbles more than Jerry. How many marbles has Elijah?&
 & \tabularnewline
 [0.5cm] \hline
Isabel has prepared 30 truffles splitted in 5 packets. How many truffles is there in one packet?&
 & \tabularnewline
 [0.5cm] \hline
The gardener has planted 16 cabbages last week, and 5 cabbages more this week. How many cabbages did he plant altogether?&
 & \tabularnewline
 [0.5cm] \hline
Our neighbours have 98 sheep. That's 70 more than us. How many sheep do we have?&
 & \tabularnewline
 [0.5cm] \hline
Layla bought 9 pens at 7 £. How much did she pay?&
...............~£ & \tabularnewline
 [0.5cm] \hline
My bike ride is 73$~\text{km}$ long and I already rode 36$~\text{km}$. How long do I still have to go cycling?&
...............$~\text{km}$ & \tabularnewline
 [0.5cm] \hline
\end{tabular}
}

\end{document}

A: I can understand your reluctance to split tabular material across pages. However, if the choice is between (a) allowing a page break in the middle of the tabular material and (b) shrinking the tabular material to make it fit in the available space on a page (and risking the material becoming tiny and virtually unreadable!), the former choice may well be far preferable.
Below is a solution that uses a longtable environment instead of the tabular environment. If \normalsize is in effect, the entire table can fit in a single page; in contrast, if \large or \Large are in effect, a page break is required. Observe the division of relative row widths, viz., 5:1, in the example code; you're free, of course, to set the relative row widths to suit your needs.
Observe further that I also advocate giving the tabular material a much more open look, mainly by getting rid of all vertical lines. Instead of text, the cells could also hold images inserted via \includegraphics statements. And, do consider using the \SI and \si macros of the siunitx package to enforce a consistent appearance of units and of number/unit pairs.

\documentclass[a4paper,fleqn,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[british]{babel}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{geometry}
\usepackage{array}
\usepackage{amssymb}
\usepackage{amsmath}

\usepackage{longtable,ragged2e,siunitx}
\newcolumntype{L}[1]{>{\RaggedRight\arraybackslash}p{#1}}
\newcolumntype{R}[1]{>{\RaggedLeft\arraybackslash}p{#1}}
\setlength\extrarowheight{3pt} % provide some visual "breathing space"

% Page layout
\geometry{margin=1.5cm}
\setlength{\parindent}{0cm}
\pagestyle{empty}

\begin{document}
\large % or: \Large, \huge, or whatever

\begingroup % localize the effect of the following \setlength instruction
\setlength\tabcolsep{0pt}
\begin{longtable}{L{0.833\textwidth}R{0.167\textwidth}}

\caption{Mental calculation: Mini-problems} \label{tab:mini}\\
\multicolumn{2}{r}{Answer}\\
\hline
\endfirsthead

\caption*{Table \ref{tab:mini}, continued} \\
\multicolumn{2}{r}{Answer}\\
\hline
\endhead

\hline
\multicolumn{2}{r}{\small (Continued on the following page)}\\
\endfoot

\hline
\endlastfoot

My golden goose laid 4 eggs each day during 9 days. How many eggs has she laid?&\\
\hline
Mya has 40 marbles. She gives them out to 5 friends. How many marbles will each friend get?&\\
\hline
We have 4 sheep. Our neighbours have 7 times more sheep than us. How many sheep do they have?&\\
\hline
I will give out 72 candies to the 8 friends that I invited at my birthday party. How many candies will each of my friends receive?&\\
\hline
I had to fill this can with \SI{18}{\liter} of water. There was \SI{7}{\liter} left in it. How much does it contain?&
\si{\liter}\\
\hline
We have loaded \SI{64}{\kilogram} of flour, shared in 8 packets. How heavy is one packet?&
~\si{\kilogram}\\
\hline
A market gardener had 72 cabbages in his vegetable garden, and harvested 54 of them last week. How many cabbages are still in the garden?&\\
\hline
\SI{9}{\meter\squared} of this wall are already painted. \SI{7}{\meter\squared} are still missing to have the wall completely painted. What is its area?&
~\si{\meter\squared}\\
\hline
I already rode \SI{84}{\kilo\meter} out of \SI{98}{\kilo\meter}. How long do I still have to go cycling?&
~\si{\kilo\meter}\\
\hline
Lily gets 6\,£ pocket money every month. If she doesn't spend it during 7 months, how much will she spare?&
~£\\
\hline
Yesterday, my golden goose laid 8 eggs. That's 11 less than today. How many eggs has she laid today?&\\
\hline
Janet bought 8 boxes of 7 pencils. How many pens did she buy?&\\
\hline
A market gardener had 78 cabbages in his vegetable garden, and harvested 56 of them last week. How many cabbages are still in the garden?&\\
\hline
I will give out 49 candies to the 7 friends that I invited at my birthday's party. How many candies will receive each of my friends?&\\
\hline
Jerry has 17 marbles. Elijah has 17 marbles more than Jerry. How many marbles has Elijah?&\\
\hline
Isabel has prepared 30 truffles splitted in 5 packets. How many truffles are there in one packet?&\\
\hline
The gardener planted 16 cabbages last week and 5 cabbages more this week. How many cabbages did he plant altogether?&\\
\hline
Our neighbours have 98 sheep. That's 70 more than us. How many sheep do we have?&\\
\hline
Layla bought 9 pens at 7\,£. How much did she pay?&
~£\\
\hline
My bike ride is \SI{73}{\kilo\meter} long and I already rode \SI{36}{\kilo\meter}. How long do I still have to go cycling?&
~\si{\kilo\meter}\\
\end{longtable}
\endgroup
\end{document}

A: If you want your text readable (which you do 111% in a test), you really don't want to shrink it. Therefore you have to split it into two pages. Together with de-tabularizing your list, the code could look like this:
\documentclass[a4paper,12pt]{article}
\usepackage[british]{babel}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{geometry}
\usepackage{calc}
\usepackage{siunitx}

% Page layout
\geometry{hmargin=1.5cm, vmargin=1.5cm}

\newenvironment{problems}{
    \newcommand\problem[2][]{
        \par
        \noindent\rule{\linewidth}{0.4pt}
        \\\nobreak\ignorespaces
        ##2
        % Borrowed from amsthm.sty
        \leavevmode\unskip\penalty9999\hbox{}\nobreak\hfill\quad
        % Lower the box so that the lines of the paragraph are not disturbed
        \raisebox{-\fboxsep-\fboxrule}{\fbox{\hbox to 2cm{\strut\hfil\si{##1}}}}
        \par
    }
}{}

\begin{document}

\subsection*{Mental calculation: mini-problems}

\begin{problems}
\problem{My golden goose laid 4~eggs each day during 9~days. How many eggs has she laid?}
\problem{Mya has 40~marbles. She gives them out to 5~friends. How many marbles will get each friend?}
\problem{We have 4~sheep. Our neighbours have 7~times more sheep than us. How many sheep do they have?}
\problem{I will give out 72~candies to the 8~friends that I invited at my birthday's party. How many candies will receive each of my friends?}
\problem[L]{I had to fill this can with \SI{18}{L} of water. There was \SI{7}{L} left in it. How much does it contain?}
\problem[kg]{We have loaded \SI{64}{kg} of flour, shared in 8~packets. How heavy is one packet?}
\problem{A market gardener had 72~cabbages in his vegetable garden, and harvested 54~of them last week. How many cabbages are still in the garden?}
\problem[m^2]{\SI{9}{m^2} of this wall are already painted. \SI{7}{m^2} are still missing to have the wall completely painted. What is its area?}
\problem[km]{I already rode \SI{84}{km} out of \SI{98}{km}. How long do I still have to go cycling?}
\problem[\textsterling]{Lily gets \SI{6}{\textsterling} pocket money every month. If she doesn't spend it during 7~months, how much will she spare?}
\problem{Yesterday, my golden goose laid 8~eggs. That's 11~less than today. How many eggs has she laid today?}
\problem{Janet bought 8~boxes of 7~pencils. How many pens did she buy?}
\problem{A market gardener had 78~cabbages in his vegetable garden, and harvested 56~of them last week. How many cabbages are still in the garden?}
\problem{I will give out 49~candies to the 7~friends that I invited at my birthday's party. How many candies will receive each of my friends?}
\problem{Jerry has 17~marbles. Elijah has 17~marbles more than Jerry. How many marbles has Elijah?}
\problem{Isabel has prepared 30~truffles splitted in 5~packets. How many truffles is there in one packet?}
\problem{The gardener has planted 16~cabbages last week, and 5~cabbages more this week. How many cabbages did he plant altogether?}
\problem{Our neighbours have 98~sheep. That's 70~more than us. How many sheep do we have?}
\problem[\textsterling]{Layla bought 9~pens at \SI{7}{\textsterling}. How much did she pay?}
\problem[km]{My bike ride is \SI{73}{km} long and I already rode \SI{36}{km}. How long do I still have to go cycling?}
\end{problems}

\end{document}

Note that I did couple more changes:

*

*used siunitx

*used \subsection* rather than \textbf{\LARGE stuff

*removed unnecessary packages

*changed £ to \textsterling so that utf8x nor ucs is necessary (I'm strongly against using unicode for non-letters in pdflatex)

*added ~ after all the amounts

A: Here's an alternative answer, which differs from my earlier answer mainly by the use of a tabular environment. To ensure that the tabular material and the header material fit on a single page while using a \large relative font size, it will in general be necessary to decrease the widths of the vertical margins relative to what you've specified in the posting (1.5cm).

\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[british]{babel}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{geometry}
\usepackage{array}
\usepackage{amssymb}
\usepackage[fleqn]{amsmath}

\usepackage{ragged2e,siunitx}
\newcolumntype{L}[1]{>{\RaggedRight\arraybackslash}p{#1}}
\newcolumntype{R}[1]{>{\RaggedLeft\arraybackslash}p{#1}}
\setlength\extrarowheight{3pt}

% Page layout
\geometry{hmargin=1.5cm,vmargin=0.75cm}
\setlength{\parindent}{0cm}
\setlength\tabcolsep{0pt}
\pagestyle{empty}

\begin{document}
\large % or: \Large, \huge, or whatever

\textbf{Mental calculation: Mini-problems}

\smallskip
\begin{tabular}{L{0.88\textwidth}R{0.12\textwidth}}
\multicolumn{2}{r}{Answer}\\
\hline
My golden goose laid 4 eggs each day during 9 days. How many eggs has she laid?&\\
\hline
Mya has 40 marbles. She gives them out to 5 friends. How many marbles will each friend get?&\\
\hline
We have 4 sheep. Our neighbours have 7 times more sheep than us. How many sheep do they have?&\\
\hline
I will give out 72 candies to the 8 friends that I invited at my birthday party. How many candies will each of my friends receive?&\\
\hline
I had to fill this can with \SI{18}{\liter} of water. There was \SI{7}{\liter} left in it. How much does it contain?&
\si{\liter}\\
\hline
We have loaded \SI{64}{\kilogram} of flour, shared in 8 packets. How heavy is one packet?&
~\si{\kilogram}\\
\hline
A market gardener had 72 cabbages in his vegetable garden, and harvested 54 of them last week. How many cabbages are still in the garden?&\\
\hline
\SI{9}{\meter\squared} of this wall are already painted. \SI{7}{\meter\squared} are still missing to have the wall completely painted. What is its area?&
~\si{\meter\squared}\\
\hline
I already rode \SI{84}{\kilo\meter} out of \SI{98}{\kilo\meter}. How long do I still have to go cycling?&
~\si{\kilo\meter}\\
\hline
Lily gets 6\,£ pocket money every month. If she doesn't spend it during 7 months, how much will she spare?&
~£\\
\hline
Yesterday, my golden goose laid 8 eggs. That's 11 less than today. How many eggs has she laid today?&\\
\hline
Janet bought 8 boxes of 7 pencils. How many pens did she buy?&\\
\hline
A market gardener had 78 cabbages in his vegetable garden, and harvested 56 of them last week. How many cabbages are still in the garden?&\\
\hline
I will give out 49 candies to the 7 friends that I invited to my birthday party. How many candies will receive each of my friends?&\\
\hline
Jerry has 17 marbles. Elijah has 17 marbles more than Jerry. How many marbles has Elijah?&\\
\hline
Isabel has prepared 30 truffles splitted in 5 packets. How many truffles are there in one packet?&\\
\hline
The gardener planted 16 cabbages last week and 5 cabbages more this week. How many cabbages did he plant altogether?&\\
\hline
Our neighbours have 98 sheep. That's 70 more than us. How many sheep do we have?&\\
\hline
Layla bought 9 pens at 7\,£. How much did she pay?&
~£\\
\hline
My bike ride is \SI{73}{\kilo\meter} long and I already rode \SI{36}{\kilo\meter}. How long do I still have to go cycling?&
~\si{\kilo\meter}\\
\hline
\end{tabular}
\end{document}


Q: How to remove incorrectly added apt-get repositories I'm completely new at this, trying to deploy a meteor app. I'm trying without much success at this point to add node 0.10.40 to Ubuntu 14.04. What I have managed to do is add a bunch of non existing repositories.
How do I get rid of them?
These are the repositories I would like to get rid of:
Err https://deb.nodesource.com trusty/main amd64 Packages
  HttpError404
Err https://deb.nodesource.com trusty/main i386 Packages
  HttpError404
Ign https://deb.nodesource.com trusty/main Translation-en
W: Failed to fetch https://deb.nodesource.com/v0.10.40/dists/trusty/main/binary-amd64/Packages  HttpError404

W: Failed to fetch https://deb.nodesource.com/v0.10.40/dists/trusty/main/binary-i386/Packages  HttpError404

Where did I add these repositories to? They are not in /etc/apt/sources.list.d. In that folder I do see a repository added via the command add-apt-repository ppa:chris-lea/node.js

A: It would be easiest if you could remember the exact command with which you installed the invalid repositories. Otherwise just run this to find out in which file the lines are:
grep -r --include '*.list' 'deb.nodesource.com' /etc/apt

If they're the only lines in the file that do not start with an #, you can delete the entire file. Else just remove these specific lines. You can also just disable the lines by commenting them out. To do that, simply write an # in the very beginning of each line.


Q: PHP - Fatal Error - is any way to not stop script? I have a simple script:
<?php

$source = '../path/img.jpg';
$image = imagecreatefromjpeg($source);

?>

Finally I got:

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted

But when I try do something like that:
<?php

$source = '../path/img.jpg';

$image = @imagecreatefromjpeg($source); // Mute Fatal Error
if ( !$image )
{
    die('Image file is too large');
}

?>

but it doesn't work. Fatal error is stopping my script. Is any way to change this situation? I would like to know when fatal error is exist (then i got FALSE as $image) and then I would like to stop script, but first I want to print an information about it.
Thanks.

A: Fatal errors can't be muted or catched. You need to raise amount of memory allowed for PHP script by using memory_limit setting in php.ini


Q: Windows 10 refuses stop readding printer We several months back replaced the main network printer due too it jamming excessively, and for the first month or 2 everything has worked fine. Now one of the computers has begun too re-add the old printers too itself for no reason i can see. Every time I remove it, it will respawn again.
Printers are shared from and pushed out from the DC, and i have removed the driver and all instances of the old printers from here, and the group policy which pushes out printers are only pushing out the correct ones, but this pc ONLY adds a bunch more (Including duplicates of the new one)
I have tried :

*

*Removing them from the really useless "printers and scanners" UI within windows 10.

*Uninstalling them from device manager.

*Deleting everything from printers and even all the drivers from C:\Windows\System32\Spool\Drivers and all from the print queue.

*Checking if they are in registry (Couldn't see them there)

*Removing the computer from the domain and putting it back on.

*Different users.

*Checked appwiz.cpl for any software which might be adding them back due to old config.

*Checked startup for anything which could be re-adding them.
And none of these things have had any impact on the issue.
I checked properties in device manager on them to see what is adding them and all I got was
Under location:
\Users\S-1-5-21-1288031120-1378624092-2130640294-1174\Printers\^\^\[DC name]^
And when i go under details configuration ID says:
printqueue.inf:PRINTENUM\LocalPrintQueue,NO_DRV_LOCAL

When I go into notepad and try too print to one of these they are not visible.
What am i missing here? Is this just a particularly irksome windows 10 bug again, or is there another way to remove these printers that I've not tried?


Q: RETURN cannot have a parameter in function returning set; use RETURN NEXT at or near "QUERY" Postgres When I try to compile this function:
CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint)
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35))
AS $$
    BEGIN
        RETURN QUERY SELECT select sr_number,product_serial_number from temp_table where sr_number=sr_num
    END;
$$
LANGUAGE 'plpgsql' VOLATILE;

Why do I get this error?

RETURN cannot have a parameter in function returning set; use RETURN NEXT at or near "QUERY"

I am using postgres version 8.4.

A: Aside from a typo (you duplicated select, and you didn't terminate the RETURN statement with a semicolon), I think you were quite close - just needed to disambiguate the table columns within the query by qualifying them with the table name.  Try this (reformatted hopefully to improve readability):
CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint)
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$
  BEGIN
    RETURN QUERY
      SELECT
        temp_table.sr_number, temp_table.product_serial_number
      from temp_table
      where temp_table.sr_number=sr_num;
  END;
$$ LANGUAGE 'plpgsql' VOLATILE;

Caveat: I only tested this in PG 9.4, so haven't tested it in your version yet (which is no longer supported, I might add).  In case there are issues regarding PLPGSQL implementation between your version and 9.4, you can try this form as an alternative:
CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint)
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$
  BEGIN
    FOR sr_number, product_serial_number IN
      SELECT
        temp_table.sr_number, temp_table.product_serial_number
      from temp_table
      where temp_table.sr_number=sr_num
    LOOP
      RETURN NEXT;
    END LOOP;
    RETURN;
  END;
$$ LANGUAGE 'plpgsql' VOLATILE;

A small sanity check using a table I populated with dummy data:
postgres=# select * from temp_table;
 sr_number | product_serial_number
-----------+-----------------------
         1 | product 1
         2 | product 2
         2 | another product 2
(3 rows)

postgres=# select * from test_proc4(1);
 sr_number | product_serial_number
-----------+-----------------------
         1 | product 1
(1 row)

postgres=# select * from test_proc4(2);
 sr_number | product_serial_number
-----------+-----------------------
         2 | product 2
         2 | another product 2
(2 rows)


Q: Chemfig polymer brackets without compiling twice I'm working on the following picture:
\documentclass{standalone}

\usepackage{tikz}
\usepackage{chemfig}

\begin{document}
    \schemestart
    n \quad \chemfig{C(-[3]H)(-[5]H)=C(-[1]H)(-[7]H)}
    \arrow
    \chemfig{-[@{op,.60}]C(-[2]H)(-[6]H)-C(-[2]H)(-[6]H)-[@{cl,0.40}]}
    \schemestop
    \polymerdelim[delimiters ={[]}, height = 30pt, depth = 30pt, indice = \!\!n]{op}{cl}
\end{document}

It seems that I need to compile the document twice in order for the brackets to appear. According to the Chemfig manual, some things seem to require a feature called "picture remembering", and I think it is probably related to this. I assume that the location for the brackets is saved on the first run and used on the second run.
Chemfig manual says (not about brackets but about electron movements):

It is assumed that the viewer supports “picture remembering” and that the compilation is done twice.

My questions are:

*

*Why do brackets require compiling twice when most other features do not?

*How can I create polymer brackets without having to compile twice?

*What does it mean for a viewer to support “picture remembering”? Does this refer to the pdf viewer?
I would like to avoid compiling twice, because I'm compiling a lot of pictures on a server and if I would set it to compile twice, that would double the compile time for all pictures. That's why I would prefer a solution that would require compiling only once.


Q: wx.Image from image URL Well I've been doing a ton of searching and there doesn't seem to be too many people talking about this. With the help of the documentation for wxPython, I've got this far. I'm looking to create a wx.Image widget from an image URL. http://wxpython.org/docs/api/wx-module.html#ImageFromStream
imgStream = urllib2.urlopen(captchaURL).read()
captchaImg = wx.Image(wx.ImageFromStream(wx.InputStream(imgStream)), wx.BITMAP_TYPE_ANY)

Does anybody have some advice for me? Much appreciated.
Oh, the error I'm getting is TypeError: Not a file-like object, with the code snippet above.

A: buf = urllib2.urlopen(URL).read()
sbuf = StringIO.StringIO(buf)
Image = wx.ImageFromStream(sbuf).ConvertToBitmap()
wx.StaticBitmap(Panel, -1, Image, (10,10))

A: import requests
import io

url = ""
content = requests.get(url).content
io_bytes = io.BytesIO(content)
image = wx.Image(io_bytes).ConvertToBitmap()
staticImage = wx.StaticBitmap(Panel, wx.ID_ANY, image, wx.DefaultPosition, wx.DefaultSize, 0)

replace url and Panel with your url and panel object


Q: What physical properties are invariant under relativistic transformation? Most of the familiar physical properties vary according to the relativistic observer's reference frame - speed, mass, energy, time, length, etc. Which properties remain invariant, so everybody will always measure the same value?
Electric and colour charges appear to be. Width, orthogonal to any resultant gravitational/velocity vector, appears to be. Causality is in practice, although there is some debate over the niceties of interactions with entangled states. Is this list correct, and are there any others?
(Possibly relevant; This question asks about "objects" rather than properties in general, but has not been answered yet)


Q: Can't get Jest expo app to work with react-navigation I am trying to snapshot test with Jest, Expo, React Navigation and my whole app uses hooks only. I'd like to eventually make these into e2e tests where Jest clicks through and snapshot tests everything but I can't even get react navigation to render. My snapshot after the expo loader always shows "null." I followed the basic example from the tabs starter that comes with expo init but the way it outlines how to setup the mocks simply doesn't work for my app. I've tried all sorts of things but nothing works.
App.tsx
import { Ionicons } from '@expo/vector-icons';
import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { YellowBox } from 'react-native';
import { Provider as PaperProvider } from 'react-native-paper';
import { useScreens } from 'react-native-screens';
import { Provider as RxProvider } from 'reactive-react-redux';
import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import SnackBar from './components/UI/Snackbar';
import { socketMiddleware } from './lib/socketMiddleware';
import SwitchNavigator from './navigation/AppNavigator';
import rootReducer from './reducers/rootReducer';
import { theme } from './Theme';

const middleware = [thunk, socketMiddleware()];
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore<iAppState, any, any, any>(
  rootReducer,
  composeEnhancers(applyMiddleware(...middleware))
);

// Must be called prior to navigation stack rendering
useScreens();

YellowBox.ignoreWarnings(['Require cycle:']);

const App = (props) => {
  const [isLoadingComplete, setLoadingComplete] = useState(false);

  if (!isLoadingComplete && !props.skipLoadingScreen) {
    return (
      <AppLoading
        startAsync={loadResourcesAsync}
        onError={handleLoadingError}
        onFinish={() => handleFinishLoading(setLoadingComplete)}
      />
    );
  } else {
    return (
      <RxProvider store={store}>
        <PaperProvider theme={theme}>
          <SwitchNavigator />
          <SnackBar />
        </PaperProvider>
      </RxProvider>
    );
  }
};

const loadResourcesAsync = async () => {
  await Promise.all([
    Asset.loadAsync([
      //nothing
    ]),
    Font.loadAsync({
      ...Ionicons.font,
      TitilliumText250: require('./assets/fonts/TitilliumText22L-250wt.otf'),
      TitilliumText800: require('./assets/fonts/TitilliumText22L-800wt.otf')
    })
  ]);
};

const handleLoadingError = (error: Error) => {
  console.warn(error);
};

const handleFinishLoading = (setLoadingComplete) => {
  setLoadingComplete(true);
};

export default App;

App.test.tsx:
import React from 'react';
import { Provider as PaperProvider } from 'react-native-paper';
import NavigationTestUtils from 'react-navigation/NavigationTestUtils';
import renderer from 'react-test-renderer';
import App from './App';
import { theme } from './Theme';

jest.mock('expo', () => ({
  AppLoading: 'AppLoading'
}));
jest.mock('react-native-screens');
jest.mock('react-native-paper');
jest.mock('redux');
jest.mock('reactive-react-redux');
jest.mock('./navigation/AppNavigator', () => 'SwitchNavigator');

describe('App', () => {
  jest.useFakeTimers();

  beforeEach(() => {
    NavigationTestUtils.resetInternalState();
  });

  // success
  it(`renders the loading screen`, () => {
    const tree = renderer.create(<App />).toJSON();
    expect(tree).toMatchSnapshot();
  });

  // this snapshot is always null
  it(`renders the root without loading screen`, () => {
    const tree = renderer
      .create(
        <PaperProvider theme={theme}>
          <App skipLoadingScreen></App>
        </PaperProvider>
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

/navigation/AppNavigator.tsx:
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import LoginStack from './LoginStack';
import TabStack from './TabStack';

/** The most root navigator which allocates to the others. */
const SwitchNavigator = createAppContainer(
  createSwitchNavigator(
    {
      LoginStack: LoginStack,
      TabStack: TabStack
    },
    {
      initialRouteName: 'LoginStack'
    }
  )
);

export default SwitchNavigator;

A: I was having a similar issue and found a fix via: https://github.com/expo/expo/issues/7155#issuecomment-592681861
Seems like the act() worked magically for me to stop it from returning null (not sure how)
Update your test to use it like this:
import { act, create } from 'react-test-renderer';

it('renders the root without loading screen', () => {
    let tree;

    act(() => {
      tree = create(
        <PaperProvider theme={theme}>
          <App skipLoadingScreen></App>
        </PaperProvider>
      );
    });

    expect(tree.toJSON()).toMatchSnapshot();
  });

Note: When I changed how I was using the imports from 'react-test-renderer' my tests couldn't find act() as a function, a simple re-install of npm packages solved this problem!


Q: How can I check that a label has fallen off the screen? I have a question about UIKit Dynamics. Let's say I'm designing some interactivity, and when the user taps, I want a label with some text to fall off the screen (at which point, I'll destroy it, and a new label will spawn and fall from the top, snap to center, and when the user taps, that too falls off the screen, and on it goes.)
import UIKit

class ViewController: UIViewController {

var myLabel: UILabel!
var gravity: UIGravityBehavior!
var animator: UIDynamicAnimator!

override func viewDidLoad() {
    super.viewDidLoad()

    myLabel = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
    myLabel.backgroundColor = UIColor.blueColor()
    myLabel.text = "Some sample text."
    view.addSubview(myLabel)

    animator = UIDynamicAnimator(referenceView: view)
    gravity = UIGravityBehavior(items: [myLabel])
    animator.addBehavior(gravity)

}

The code above will spawn a UILabel and make it drop off the screen. I understand how to do all of that. However, I'm at a loss concerning how to determine whether or when the label has fallen completely from view, at which point it is removedFromSuperView, and my new label can spawn and fall from the top.
Should I be using a method to determine if the label is intersecting with the view (like CGRectIntersectsRect() )? Or should I try and check whether the center point of the label is inside the bounds of the screen? I've tried hacking together a solution using both of those options but so far nothing has worked. Any suggestions?


Q: Unable to build with electron-packager within electron-forge I have created a default project with electron-forge. When I try to package my project with the command electron-forge, the process exits with the following error.
What am I doing wrong? I followed the instructions to a tee at electron-forge.
$ electron-forge package
✔ Checking your system
✔ Preparing to Package Application for arch: x64
✔ Compiling Application
✔ Preparing native dependencies
⠦ Packaging Application
An unhandled rejection has occurred inside Forge:
Command failed: npm prune --production
npm WARN electron-example@1.0.0 No repository field.

npm ERR! May not delete: /tmp/electron-packager/linux-x64/electron-example-linux-x64/resources/app/node_modules/.bin

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/maxchehab/.npm/_logs/2017-07-21T04_40_37_618Z-debug.log

Error: Command failed: npm prune --production
npm WARN electron-example@1.0.0 No repository field.

npm ERR! May not delete: /tmp/electron-packager/linux-x64/electron-example-linux-x64/resources/app/node_modules/.bin

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/maxchehab/.npm/_logs/2017-07-21T04_40_37_618Z-debug.log

    at ChildProcess.exithandler (child_process.js:270:12)
    at emitTwo (events.js:125:13)
    at ChildProcess.emit (events.js:213:7)
    at maybeClose (internal/child_process.js:921:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)

Thank you for your time.

A: It looks like the latest version of npm has introduced a bug for the electron make process. Issue is being tracked here.
Github Issue
Try this workaround for a possible fix(untested):
rm -rf node_modules
npm install --production --ignore-scripts
npm install --no-save electron-rebuild --ignore-scripts
node_modules/.bin/electron-rebuild
npm remove electron-rebuild --ignore-scripts

Or downgrade your npm to a version less than 5.3(tested, works).
npm i -g npm@5.2

A: Problem is solved in later versions of npm, please consider upgrading to the latest v ( > 5.4.2) instead of downgrading to 5.2:
npm i -g npm


Q: Post Authentication custom response to client from Cognito We have lambda triggers set up in Cognito for Pre-Authentication/Post-Authentication, and Post Confirmation.
In all the triggers we are checking against our DynamoDB in order to proceed and the db entries are coming properly as expected.
However, we also want to send some details from our database back to the client at the time of login.
In this case, it's a user object containing our DynamoDB user's uuid.
Our iOS developer is using AWSAuthUIViewController and is expecting to access our custom response here:
AWSAuthUIViewController
.presentViewController(with: self.navigationController!,
              configuration: config,
          completionHandler: { (provider: AWSSignInProvider, error: Error?) in
                                 //...

                                 let user = AWSCognitoUserPoolsSignInProvider
                                           .sharedInstance()
                                           .getUserPool()
                                           .currentUser()

                                           /*
                                              do something to access custom
                                              response of user object
                                            */
})

We've looked at Custom Message Lambda Trigger documentation but this one relates to MFA so it's not what we're looking for.
The main question is how to have Cognito respond to the client with a custom object containing entries from our DynamoDB.

A: A better flow to use is probably the Custom Authentication Flow. It is not supported in the AWSAuthUIViewController, but you may use the AWSCognitoIdentityUserPool to perform the flow. The custom challenge could be leveraged to pass information back to the client before ending the flow.


Q: How can I define unique epsilons with bounded range for floating point analysis? I'd like to use Mathematica for analyzing error bounds in floating point code.  To do this, we can use the standard model for floating point error:
$$flt(a\oplus b) = (a\oplus b)(1+\epsilon_i)$$
Where $|\epsilon_i| < k$ where k is some small constant (depending on the operation).
So, I could write FltAdd, FltSub, FltMul, FltDiv, etc functions that compute the result with the extra error term.  but the trick is that the epsilon for each separate term has to be unique, so e.g. I can't use $\epsilon_0$ for A+B and C+D because in actuality they'll have different errors.  If I used the same error, an expression such as (A+B)/(C+D) would have the error cancel which isn't what happens.
So, I think I need to somehow build error terms with unique symbols, but I need them to be predictable enough that I can bound all the "sum" errors by e.g. $u$ and all the div terms by e.g. $u-2u^2$.
But, I'm not nearly good enough at Mathematica to do that so I thought I'd see what people suggest in terms of approaching this.

A: $Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global`*"]

Use Around (EXPERIMENTAL function introduced in v12.0)
Around[a, ϵ]

Format[ϵ[n_]] := Subscript[ϵ, n]

{#, #[Around[a, ϵ[1]], Around[b, ϵ[2]]]} & /@
  {Plus, Subtract, Times, Divide, Power} //
 Grid[#, Frame -> All] &

Assuming[ϵ > 0,
  {#, #[Around[a, ϵ]]} & /@
    {Sin, Tan, Sqrt, Exp, Log} //
   Simplify] //
 Grid[#, Frame -> All] &

EDIT : From the documentation, "For linear computations, Around[x, δ] behaves like a number whose values are distributed according to the normal distribution NormalDistribution[x, δ]."
TransformedDistribution[x + y,
 {x \[Distributed] NormalDistribution[a, ϵ[1]],
  y \[Distributed] NormalDistribution[b, ϵ[2]]}]


Q: How to remove Baidu's cookie How to remove viglink & baidu's cookie.
I create a empty html file and testing on my Chrome
I notice there are 3 files is reading from baidu 2 from viglink
I use Chrome Network to check this what files are reading.
I'm not sure what are those files for, r those secure?
I check cookies and try to remove it from Chrome
but it comeing back.
hm.js?3d143f0a07b6487f65609d8411e5464f
hm.baidu.com

vglnk.js
cdn.viglink.com/api

ping?format=jsonp&key=084c74521c465af0d8f08b63422103cc&loc=http%3A%2F%2Flocalhost%2Fz.php&v=1&ref=http%3A%2F%2Flocalhost%2F&jsonp=vglnk_jsonp_13800321595965
api.viglink.com/api

hm.gif?cc=1&ck=1&cl=32-bit&ds=1920x1080&ep=59502%2C7996&et=3&fl=11.8&ja=1&ln=zh-TW&lo=0&lt=1380031859&nv=0&rnd=632137474&si=3d143f0a07b6487f65609d8411e5464f&st=4&su=http%3A%2F%2Flocalhost%2F&v=1.0.47&lv=3&u=http%3A%2F%2Flocalhost%2Fz.php
hm.baidu.com

hm.gif?cc=1&ck=1&cl=32-bit&ds=1920x1080&et=0&fl=11.8&ja=1&ln=zh-TW&lo=0&lt=1380031859&nv=0&rnd=998891479&si=3d143f0a07b6487f65609d8411e5464f&st=4&su=http%3A%2F%2Flocalhost%2F&v=1.0.47&lv=3
hm.baidu.com


Q: Error converting bytecode to dex: Cause: java.lang.RuntimeException: Exception parsing classes - Android studio 2.0 beta 6 I updated to the last version of Android studio 2.0 Beta 6 with the gradle :
dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0-beta6'
}

The app works perfectly fine on emulator and devices I tested every thing and it works fine.
I got many errors only when I try to Generate Signed APK,
I got some errors in dependencies, all of them solved when i excluded vector drawable, vector animate drawable and Support-v4 library
Now i dont have any dependencies error.
now my gradle.build for the app module looks like this:
apply plugin: 'com.android.application'

android {
    configurations {
        //all*.exclude group: 'com.android.support', module: 'support-v4'
        all*.exclude module: 'animated-vector-drawable'
        all*.exclude module: 'support-vector-drawable'
        //all*.exclude module: 'support-v4'

    }
    repositories {
        maven { url "https://jitpack.io" }

    }
    compileSdkVersion 23
    buildToolsVersion '23.0.2'
    defaultConfig {
        applicationId "com.test.test"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1"

//        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile('com.github.afollestad.material-dialogs:commons:0.8.5.5@aar') {
        transitive = true
        exclude module: 'support-v4'
        exclude module: 'appcompat-v7'
        exclude module: 'recyclerview-v7'
    }
    compile('com.google.android.gms:play-services-ads:8.4.0') {
        exclude module: 'support-v4'
    }
    compile('com.google.android.gms:play-services-analytics:8.4.0') {
        exclude module: 'support-v4'
    }
    compile('com.android.support:appcompat-v7:23.2.0') {
        exclude module: 'support-v4'
        exclude module: 'animated-vector-drawable'
        exclude module: 'support-vector-drawable'
    }
    compile('com.android.support:support-v4:23.2.0') {
        exclude module: 'animated-vector-drawable'
        exclude module: 'support-vector-drawable'
    }
    compile('com.android.support:palette-v7:23.2.0') {
        exclude module: 'support-v4'
    }
    compile('com.android.support:cardview-v7:23.2.0') {
        exclude module: 'support-v4'
    }
    compile('com.android.support:recyclerview-v7:23.2.0') {
        exclude module: 'support-v4'
    }
    compile('com.android.support:design:23.2.0') {
        exclude module: 'support-v4'
    }
    compile('com.nineoldandroids:library:2.4.0') {
        exclude module: 'support-v4'
    }
    compile('com.baoyz.swipemenulistview:library:1.2.1') {
        exclude module: 'support-v4'
        exclude module: 'appcompat-v7'
        exclude module: 'recyclerview-v7'
    }
    compile('com.squareup.picasso:picasso:2.5.2') {
        exclude module: 'support-v4'
    }
    compile('com.nononsenseapps:filepicker:2.5.0') {
        exclude module: 'support-v4'
        exclude module: 'appcompat-v7'
        exclude module: 'recyclerview-v7'

    }
    compile 'com.google.code.gson:gson:2.6.1'
}

The errors shows up only when I build for release:
This is the error when i turn on multiDex:
Error:Execution failed for task ':app:transformClassesWithMultidexlistForRelease'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

And this is the error when i turn it off:
:app:transformClassesWithDexForRelease
Error:Error converting bytecode to dex:
Cause: java.lang.RuntimeException: Exception parsing classes

Error:Execution failed for task ':app:transformClassesWithDexForRelease'.

> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

I tried to change the buildToolsVersion '23.0.2' to every possible version and nothing changed.
when i put the version 22.0.1 i got this error:
Error:Error converting bytecode to dex:
Cause: com.android.dx.cf.iface.ParseException: name already added: string{"a"}

Error:Execution failed for task ':app:transformClassesWithDexForRelease'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

I tried with all possible support libraries version and same result.
I tried with Java 1.6 and 1.7 and nothing has changed !
what can be other possible solution please ?

A: just do Build > Clean Project
Wait for Cleaning Ends and then Build > Rebuild Project, and the error was gone. that's it.

A: I also faced the same error, and i was searching through many existing answers with duplicate dependencies or multidex etc. but none worked. (Android studio 2.0 Beta 6, Build tools 23.0.2, no multidex)
It turned out that i once used a package names which didn't match the package name that is depicted in the Manifest.
In other ParseException lines, i found out that i had files in different modules whith similiar package names/paths that possibly conflicted the dexer.
Example:
Module A: com.example.xyz.ticketing.modulea.Interface.java
Module B: com.example.Xyz.ticketing.moduleb.Enumerations.java
Module C: Has dependencies on A and B
After fixing "Xyz" to lowercase, the dexer was fine again.
How to find out:
When i looked through the output of the gradle console for the ParseExceptions that looks like this:
AGPBI: {"kind":"error","text":"Error converting bytecode to dex:\nCause: java.lang.RuntimeException: Exception parsing classes"
I scrolled close to the end of the exception. There is a part in that long exception line that actually mentions the cause:
Caused by: com.android.dx.cf.iface.ParseException: class name (at/dummycompany/mFGM/hata/hwp/BuildConfig) does not match path (at/dummycompany/mfgm/hata/hwp/BuildConfig.class)
This way i found out where to search for missmatching package names/paths

A: I had a wrong package name in one of the helper class,hence I was having the error.So check all the Classes and make sure you have correct package name.

A: My solution was different, I was added these lines in proguard-rules.pro
-optimizationpasses 5
-overloadaggressively
-repackageclasses ''
-allowaccessmodification

Make sure to update everything from SDK manager as well.

A: If your targetSdkVersion is 25 or higher version and you use JDK 8 you have to add in your build.gradle file the following:
android {
   compileSdkVersion 26
   buildToolsVersion "26.0.0"

    defaultConfig {
        ...
        jackOptions {
            enabled true
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

More info: https://stackoverflow.com/a/37294741

A: The solution for me is to modifing the Build Gradle file.
I found out, that the problem is a GC overhead (out of memory).
So I add some code to my configuration
android {
  dexOptions {
    incremental = true;
    preDexLibraries = false
    javaMaxHeapSize "2g"
  }
}

There is some other problem with proguard.
You've to set minifyEnabled to false also.

A: Removing -overloadaggressively from my proguard-rules.pro fixed this for me.
Alternatively, adding -useuniqueclassmembernames also fixed it.

A: I tried ./gradlew clean build, Invalidating studio cache, restarting machine. But what solved the issue is turning Instant run off

A: Got this issue while using the Android studio template for Login activity.
I've selected "activity" package to put my activity into.
The template in AndroidManifest.xml, instead of .activity.LoginActivity used the .LoginActivity thus causing the error.

A: If you faced this error, certainly your package in manifest differ from the others that you have set in your classes. be careful.

A: I ran into the same issue today and the problem was that in my Constants.java classed I have defined (by mistake)
public static final class Checkout {
.......
}

and
public static final class CHECKOUT {
......
}

A: In my case, there was a class that I made that I didn't use yet. So I have to delete the class or use the class.

A: I faced the same error. Appears that its due to renaming a package to lower case and a class had the previous case wording.

A: Your gradle.build file will contain
compile files('libs/httpclient-4.2.1.jar')

compile 'org.apache.httpcomponents:httpclient:4.5'

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

By removing this line from file.
compile files('libs/httpclient-4.2.1.jar')

It will work fine.