Kendo UI - How to add request parameters to proxyURL?

Question: According to the Kendo UI API, the pdf.proxyURL of kendo.ui.Grid will post a request with the following parameters:

contentType: The MIME type of the file
base64: The base-64 encoded file content
fileName: The file name, as requested by the caller

How do I add parameters to this request?
In my case, I need to add CSRF param (i.e. _csrf.parameterName=_csrf.token) for Spring Security purposes.
Answer: As I read the code in Kendo, It will add the CRSF token from meta automatically, So you just need put the token to meta in head
kendo.antiForgeryTokens = function() {
            var tokens = { },
                csrf_token = $("meta[name=csrf-token],meta[name=_csrf]").attr("content"),
                csrf_param = $("meta[name=csrf-param],meta[name=_csrf_header]").attr("content");

            $("input[name^='__RequestVerificationToken']").each(function() {
                tokens[this.name] = this.value;
            });

        if (csrf_param !== undefined && csrf_token !== undefined) {
          tokens[csrf_param] = csrf_token;
        }

    return tokens;
};

Or you can override the antiForgeryTokens function, and return a object, the object will be added before request the proxyURl.
Comment: @James How about it ?


How do I install bully and mdk3 on Ubuntu 16.04 (Xenial Xerus)?

Question: How do I find and install the Bully and Mdk3 tools from Kali Linux on Ubuntu 16.04?
Answer: Bully can be installed from the default Ubuntu repositories in Ubuntu 21.10 and later by running these commands:
sudo apt update
sudo apt install bully

Bully can be installed in Ubuntu 21.04 and earlier by running the following commands:
sudo apt -y install libpcap-dev libssl-dev aircrack-ng unzip
wget https://salsa.debian.org/pkg-security-team/bully/-/archive/debian/master/bully-debian-master.zip
unzip bully-debian-master.zip
cd bully-*/
cd src
make # makes a file named bully
sudo make install

mdk3 can be installed in Ubuntu 17.10 and later from the default Ubuntu repositories. Open the terminal and type:
sudo apt install mdk3

In Ubuntu 17.04 and earlier mdk3_6.0-4_amd64.deb can be downloaded from Ubuntu — Package Download Selection — mdk3_6.0-4_amd64.deb. Open a terminal, use cd to change directories to the directory where mdk3_6.0-4_amd64.deb is located and install it using the following command:
sudo dpkg -i mdk3_6.0-4_amd64.deb

Comment: Who is `aanarchyy`? Has anyone audited that "bully" code? Who knows what's in it. Why is the repo linked from https://tools.kali.org/wireless-attacks/bully dead? How about https://gitlab.com/kalilinux/packages/bully/ instead?
Comment: You should probably clone and build the official source that Kali is using: https://salsa.debian.org/pkg-security-team/bully
Comment: @jiroch Thanks for posting a very helpful comment. In fact this entire answer needed to be updated. bully is currently a package in the official Debian bullseye repositories, and it's also in the default repositories of Ubuntu 21.10 and later.
Comment: @DanDascalescu The owner of the bully repo linked from https://tools.kali.org/wireless-attacks/bully has deleted his GitHub and GitlLab accounts, which raises the question if that person is still a package maintainer of that project.
Answer: If you are unable to install them with apt, katoolin will also will not work. That's what happened to me.
You need add kali repository and then install it. It worked for me.
sudo apt-key adv --keyserver pgp.mit.edu --recv-keys ED444FF07D8D0BF6
sudo echo "deb http://http.kali.org/kali kali-rolling main contrib non-free" >> /etc/apt/sources.list
sudo echo "deb http://repo.kali.org/kali kali-bleeding-edge main' >> /etc/apt/sources.list"
sudo apt-get update
sudo apt-get install bully mdk3


How to prove that the product of a countable base is a countable base of the product set?

Question: It is simple but I can't find a elegant way to prove it.

$(\Omega_i)_{1\leq i \leq n}$ are metric sets and for all $i \in \{1,...,n\}$, $\mathcal{W_i}$ is a countable base of the topology of $\Omega_i$.
How to prove that $\Pi_{1\leq i \leq n}\mathcal{W_i}$ is a countable base of the topology of $\Pi_{1\leq i \leq n}\Omega_i$ ?
Comment: Two parts. That it is countable: If $a_{i,j}$ is an enumeration of $W_i$, then $a_{1,0},a_{2,0},...,a_{n,0},a_{1,1},...,a_{n,1},...$ is an enumeration of the product. That is is a base: It is enough to look at the open sets $U=\prod_{k=1}^nU_k$, where $U_k$ is open in $\Omega_k$. For each $k$ there is some $a_k\in W_k$ such that $a_k\in U_k$. Then $(a_1,...,a_k)\in U$.
Comment: The question is why it is a base, or why is it countable? Anyway, the notation $\prod_i \mathcal{W}_i$ (like a Cartesian product) is not good. One should write $$\mathcal{W} = \{U_1 \times \ldots \times U_n : (U_1,\ldots,U_n) \in \mathcal{W}_1 \times \ldots \times \mathcal{W}_n\}.$$
Comment: @owl Thank you!
Comment: @ChristopheLeuridan Is there an ambiguity with this notation?
Comment: Yes, it is the notation for Cartesian product i.e. the set of all $n$-uples $(U_1,\ldots,U_n)$ with $U_1 \in \mathcal{W}_1,\ldots,U_n \in \mathcal{W}_n$. But the basis is the set of all Cartesian products $U_1 \times \cdots \times U_n$ with $U_1 \in \mathcal{W}_1,\ldots,U_n \in \mathcal{W}_n$.
Comment: @ChristopheLeuridan Thank you
Answer:
$(\Omega_i)_{1\leq i \leq n}$ are metric sets and for all $i \in \{1,...,n\}$, $\mathcal{W_i}$ is a countable base of the topology of $\Omega_i$.
$\Pi_{1\leq i \leq n}\mathcal{W_i}$  of $\Pi_{1\leq i \leq n}\Omega_i$ ?

What we need to prove is that a set $U\subseteq \Pi_{1\leq i \leq n}\Omega_i$ that is open in the product topology can be written as a union of elements of the collection $\mathcal W:=\{A_1\times...\times A_n\mid A_i\in\mathcal W_i\}$.
Let $(x_1...,x_n)$ in  $U$.
On base of the definition of "product topology" we conclude that $\forall i $ $\exists V_i\in \mathcal T_i$ and $x_i\in \mathcal V_i $ where $\mathcal T_i$ are the respective topology of$(\Omega_i)_{1\leq i \leq n}$  : $$(x_1,...,x_n) \in V_1\times...\times V_n\subseteq U$$
Since $\mathcal W_i$ is a base of $\mathcal T_i$ so $x_i\in U_i\subseteq V_i$ for some $U_i\in\mathcal W_i$.
Then we have:$$((x_1,...,x_n) \in U_1\times...\times U_n\subseteq V_1\times...\times V_n\subseteq U$$
We can do this for every $(x_1,...x_n) \in U$ enabling us to write $U$ as a union of elements of the collection:$$U=\bigcup_{(x_1,...x_n)\in U}U_1\times...\times U_n $$ which are all elements of $\mathcal W$ and that show the result    $\square$.
Comment: Very concise, thanks!
Comment: Thanks to you, really good problem


Why is my setState updating state only once?

Question: const [invalidateCacheKey, setInvalidateCacheKey] = useState(0);

const onChangeAssignee = () => {
  setInvalidateCacheKey(invalidateCacheKey + 1);
  mutate();
};

const selectOrder = () => {
  dispatch(
    showModal('SHOOTING_OPERATIONAL_VIEW', {
      modalType: 'OPERATIONAL_VIEW',
      modalProps: {
        content: <ShootingActionsView updateOrders={mutate} onChangeAssignee={onChangeAssignee} />,
      },
    })
  );
};

I have a functional component, I'm using useState to update the state of my invalidateCacheKey counter.
Then I have a dispatch method (react-redux) that displays a modal, I pass to the modal the callback (onChangeAssignee).
The problem is that: when the callback is fired the state (invalidateCacheKey) doesn't change inside the onChangeAssignee method (it is 0 after and before run the callback logging state inside the onChangeAssignee method), while inside the functional component (logging the state after useState declaration) the state (invalidateCacheKey) is 0 before the callback and is 1 after the callback.
I think that problem is dispatch method, it "stores" my state and it doesn't update it.
How to fix that?
Comment: Ciao, just put couple of code lines to see what you have done. Please :)
Comment: could you paste your code in the question please, having image makes it hard for us to try thing on our side, also look at this help page [mcve]
Comment: @GiovanniEsposito I'm sorry, now is clear
Comment: @jonatjano you're right, check now :D
Comment: I can't help you on this one, I never used react/redux, but at least now your question doesn't get as much downvotes
Answer: Ciao, unfortunately hooks in react are async so if you try to write something like:
const onChangeAssignee = () => {
  setInvalidateCacheKey(invalidateCacheKey + 1);
  console.log(invalidateCacheKey)
  ...
};

you will log an old value of invalidateCacheKey, because setInvalidateCacheKey is async as I told you. To get updated value in react hooks you could use useEffect hook like:
useEffect(() => { // this will be triggered every time invalidateCacheKey changes
   console.log(invalidateCacheKey) // this shows the la st value of invalidateCacheKey
}, [invalidateCacheKey])

As an alternative, you could use a use-state-with-callback library. With this library you could write something like:
import useStateWithCallback from 'use-state-with-callback';
...

const [invalidateCacheKey, setInvalidateCacheKey] = useStateWithCallback(0, invalidateCacheKey => {
    console.log(invalidateCacheKey)  // here you have the last value of invalidateCacheKey
});

Note: set state reading state itself is always discouraged in react hooks. I suggest you to use this way:
const onChangeAssignee = () => {
  setInvalidateCacheKey(invalidateCacheKey => invalidateCacheKey + 1);
  ...
};

or
const onChangeAssignee = () => {
  let appo = invalidateCacheKey;
  setInvalidateCacheKey(appo + 1);
  ...
};

EDIT
Now lets say you need to use invalidateCacheKey in onChangeAssignee function. Lets suppose you worte code like this:
const onChangeAssignee = () => {
  setInvalidateCacheKey(invalidateCacheKey + 1);
  dostuff(invalidateCacheKey) // dostuff takes an old value of invalidateCacheKey so it doesn't work
};

You can solve this by moving dostuff into useEffect hook like:
useEffect(() => {
   dostuff(invalidateCacheKey) // here dostuff works because it takes last value of invalidateCacheKey
}, [invalidateCacheKey])

const onChangeAssignee = () => {
   setInvalidateCacheKey(invalidateCacheKey => invalidateCacheKey + 1);
};

Comment: Ciao Giovanni. Many thanks for your support. I work all day around this problem and I understand that the problem is about react-redux: when I pass the onChangeAssignee method as prop to ShootingActionsView component the method is "stored" and, if another component change the state, the onChangeAssignee is re-rendered but the new onChangeAssignee method is not passed to ShootingActionsView component, so is re-rendered only in my parent component and not inside  ShootingActionsView component, that "store" the old state and so set the wrong state
Comment: Thanks Giovanni! I know what is useEffect and how to use his dependency's array but I don't understand: where I need to put useEffect and how it helps me?
Comment: Ciao, my answer is just to remark that what you wrote here "when the callback is fired the state (invalidateCacheKey) doesn't change inside the onChangeAssignee method (it is 0 after and before run the callback logging state inside the onChangeAssignee method)," is incorrect because state infact changes on `onChangeAssignee` but you cannot log it because `setInvalidateCacheKey` is async. Putting `useEffect` in component you showed in code example allows you just to check that `invalidateCacheKey` is setted by `setInvalidateCacheKey`.
Comment: Ok right, but it doesn't resolve my problem, I can check using useEffect when the state changes but i can't use the new value of my state inside the onChangeAssignee
Comment: Yes you cannot use `invalidateCacheKey` directly, but in ` onChangeAssignee` you have all the data you need. Because you know that in `onChangeAssignee` function,` invalidateCacheKey` will be incremented by 1 so infact you know what will be the next value of `invalidateCacheKey`. So a possible solution could be copy `invalidateCacheKey` into a var, increment by 1 this var and use it for your scopes. Something like `let appo = invalidateCacheKey; appo = appo + 1;` and now you can use appo like it was `invalidateCacheKey`.
Comment: I just try but the problem is about when the callback has fired again: "appo" is again equal to 0, and doesn't update :(
Comment: Ok, let me see your code better. Do you have a github repo to share? A codesandbox in which I can reproduce your error?
Comment: I'm sorry I can't show you the repo. I think that the problem is about pass the callback inside the dispatch method, in the dispatch method the state is stored but can't see for changes
Comment: Ciao @Itsfilippinifra, I updated my answer with a possible solution for problem you described in comments.
Comment: I'm happy that you solved! Sorry if I was not totally useful... Ciao :)


Nouveau unknown chipset at install

Question: I'm trying to install Ubuntu version 14.10 on my new computer. It's a fresh build with nothing installed yet. You can see a list of the hardware here. At first I had difficulty with the UEFI boot, but I went into the BIOS and set everything that I could to "legacy". Now, when I try to boot, I get the following error:

[ 2.817690 nouveau E[ DEVICE][0000:01:00.0] unknown chipset, 0x124020a1
[ 2.817724 nouveau E[ DRM] failed to create 0x80000080, -22

I tried booting in nomodeset, which I thought did something to fix that, but it didn't work. I suspect it has something to do with not having any drivers yet, but I didn't get an optical drive. I was planning on just downloading them. What can I do?
Comment: I have the same issue. Have you managed to finally install Ubuntu and drivers?
Comment: http://askubuntu.com/questions/598417/nouveau-unknown-chipset-on-installer
Answer: Do a Ctrl+Alt+F1
login and do
sudo apt-get update
sudo apt-get upgrade
sudo ubuntu-drivers devices

see what is recommended
sudo apt-get install nvidia-xxx (xxx is your recommended driver)
reboot.

Nouveau unknown chipset at install


Setting a value in Frappe application isn't reflected in ERPNext GUI

Question: I have added a 'number_of_members' value to the Customer DocType via customization.
In my application I have tried several ways to update the value. However the value never updates in the webpage. I feel like I'm missing some sort of save or update or commit step.
For example I have tried:

frappe.client.set_value('Customer', '00042', 'number_of_members', 8887)
frappe.set_value('Customer', '00042', 'number_of_members', 8887)
frappe.db.set_value('Customer', '00042', 'number_of_members', 8887)
and also

customer = frappe.get_doc('Customer', '00042')
customer.number_of_members = 8887
customer.save()

In each case I can do something like frappe.get_value, or frappe.get_doc and it shows the value is set to 8887. However it never updates in the web side. This is what makes me think I'm updating some sort of cache or database transaction and I need some way to save it, but have not had any luck.
I am mostly testing this via bench console if that has any bearing on it, but I've tried a couple of the methods in my application code as well.
Relevant documentation:

Frappe Developer API - Document
Frappe Developer API - Database
Answer: Turns out the answer is to call frappe.db.commit() after making changes. If someone can point this out in the documentation so I can better understand how I'm missing stuff, I would appreciate it.
I also noticed if you try to Save something in the UI before you send frappe.db.commit() the UI will hang.
Comment: Hi @laydros. Im need to update also the GUI. calling frappe.db.commit() doest not show. can you share a piece of your code please


Will Minecraft map items automatically update with terrain changes?

Question: If I have a map item filled out and covering a particular area, will it automatically detect changes in the terrain? Or will I have to revisit the area with a map?
Comment: Umm, guys, he could be asking about http://minecraft.gamepedia.com/Map. Asking whether it shows terrain changes made after it's creation is not a duplicate of that question.
Comment: That duplicate has absolutely nothing to do with my question. I mean a literal _map_ -- not the world.
Comment: That wasn't clear before the edit, now it is. I retracted my close vote.
Answer: According to official Minecraft wiki:

To record the world on a map, that specific map item must be held in the player's hands while the player moves around the world. The world will be recorded as-is during exploration, meaning that if the world is modified, a player must revisit the area while holding the map in order to update the map's view

So no, the map will not detect changes in the terrain unless you are in the area with the map to update it.


How can I get white on black buttons working in topbar in both iOS7 and iOS6 with Trigger.io?

Question: Using black tint with light_content style:
forge.topbar.removeButtons()
forge.topbar.setStatusBarStyle("light_content")
forge.topbar.setTint([0,0,0,255])

Adding buttons. Images are black on transparent .png's:
{
   icon: 'images/info.png'
 , tint: [255,255,255,255]
 , position: 'right'
}

This works for iOS7, however in iOS6 shows black on a white background within the button. I've tried reversing the image, white on transparent, white on black - and I can't get white on black button images to work on both iOS6 and iOS7.
Is there a way to create the images or specify the forge API calls to get this to work? Or is it a bug in the forge topbar implementation?
Comment: Define "a combination that works"
Comment: Edited question to clarify. Basically I can't get white on black to work for both iOS7 AND iOS6.
Answer: This is due to changes in the underlying way iOS 7 displays both the topbar and tabbar. The API provided by Trigger tries to be as close as possible between versions, but it sometimes has to appear differently to support new platform features.
The easiest way to do what you want is to detect iOS 7 and run different code, you can do that as follows:
 if (navigator.userAgent.match(/(iPad|iPhone);.*CPU.*OS 7_\d/i) !== null) {
     // iOS 7 specific code
 } else {
     // iOS 6 and lower specific code
 }

Comment: Thanks for the work-around. Since Tigger.IO is providing abstraction to iOS v Android, I wouldn't expect to have to provide a hack for different versions of iOS.
Answer: For white on black buttons (based on white (or black) on transparent png) toggle the tint based on user agent detection provided by Connor:
var tint = (navigator.userAgent.match(/(iPad|iPhone);.*CPU.*OS 7_\d/i) !== null)
     ? [255,255,255,255]
     : [0,0,0,255];

Also, image size for topbar icons should be 44x44 pixels, not 64x64 as may be inferred from the documentation.


Getting socket hang up error while running appium scripts using windows OS

Question: I get this error intermittently while running my appium scripts in real device. every alternate execution fails for the below error. Please let me know if anybody has faced this issue earlier and how you have fixed it?
device used: Oppo A7 - VERSION 8.1.0
OS: Windows 10
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Could not proxy command to remote server. Original error: Error: socket hang up
<code>and the execption thrown is below
Session ID: 3fe1bfe2-acb2-4f2f-9dee-0d4699bbfe75
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:46)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
    at org.openqa.selenium.remote.RemoteWebDriver.getScreenshotAs(RemoteWebDriver.java:294)
    at screenshot.Screenshot.captureScreenshot(Screenshot.java:33)  -> implementation given by me
    at docscantests.DocScanTests.afterMethod(DocScanTests.java:552)  -> implementation given by me
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:786)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:207)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:178)
</code>
Comment: Please try to update to appium server on latest version
Comment: In error stack, I am not able to see any line mentioning about socket hang up
Answer: Socket hang up mostly happens because the system port (8200 by default) is under using after tearing down.
System port is something different than wd/hub port (like 4723).
Each UiAutomator clients use system port to talk with JWP.
Cases:
1- When you use several appium-based softwares together. Such as Katalon, Appium Studio and Appium itself at the same time
2- When have parallel running or fast running test iterations rapidly after each tearing down
How to resolve:
Change the systemPort desired capability of the appium. (ex. change from 8200 to 8210)
Answer: Rebooting the device helped me, not just closing it and opening again, but selecting "Cold boot Now" option in Vertual Device Manager for Android studio.
Comment: This is what worked for me.
Answer: I just relaunched the phone and the issue has disappeared.
Answer: Socket hang-up mostly happens because of the system port 8200, which is a default port. When we run our scripts/ tests every time it'll point to the system port 8200 and when we are executing multiple tests, we will get a socket hang-up issue because after each test appium will teardown or kill the system port. When the teardown is happening and if the next test starts, we will get a socket hang-up issue until the port is available for the execution.
Steps to overcome socket hang-up issue:
In your script, set the desired capability key as "appium:systemPort" and the value for this capability should be passed dynamically. Create a collection and keep some 5-10 different port numbers in the collection and for each test, it should pick a value from the collection and send it in sequential order. So this way we can avoid socket hang-up issues.
Answer: I was seeing this error intermittently, and based on the other answer I looked into what was happening with setup and teardown for the tests.
I realised I was creating a new driver for each test I was running, meaning each test created and then destroyed the full driver object. My issue actually started when I used the udid capability to specify the tablet serial number; my assumption is this made the driver creation take longer or somehow be slightly less reliable.
In addition, the actual tests themselves ran very quickly. That then meant I was running into case 2 in the other answer here.
My fix was to move the driver creation to a one-off, using the @BeforeClass jUnit annotation, so that it wouldn't be re-created in between each test.
Answer: I have run following command in terminal and It worked for me, Try it out.
adb shell am instrument -w -e debug false io.appium.espressoserver.test/androidx.test.runner.AndroidJUnitRunner
Answer: i switch on 'ed my system the next day morning and everything worked
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


SQL to bring result by month and year with multiple conditions

Question: I was trying to create a SQL into a monthly/yearly result. I'm counting the quantity of Documents with determined Statuses.
I already a SQL that brings part of what i need.
Here's a short example:
 SELECT _waiting.wt, _concluded.cc
 FROM tb_status as st
 LEFT JOIN (
    SELECT count(*) as wt
    FROM tb_status as st
    LEFT JOIN tb_document as dc ON st.iddocument = dc.iddocument
    WHERE NOT EXISTS (
        SELECT *
        FROM tb_status as stt
        WHERE stt.iddocument=st.iddocument
        AND stt.idstatus > st.idstatus)
    AND status LIKE '%Waiting%') as _waiting ON st.iddocument = st.iddocument
 LEFT JOIN (
    SELECT count(*) as cc
    FROM tb_status as st
    LEFT JOIN tb_document as dc ON st.iddocument = dc.iddocument
    WHERE NOT EXISTS (
        SELECT *
        FROM tb_status as stt
        WHERE stt.iddocument=st.iddocument
        AND stt.idstatus > st.idstatus)
    AND status LIKE '%Concluded%') as _concluded ON st.iddocument = st.iddocument
 GROUP BY _waiting.wt, _concluded.cc

This SQL brings the exactely result of how many Documents i have with these two Status (Concluded and Waiting). Like this example:
+-----------+-----------------+
|    wt     |       cc        |
+-----------+-----------------+
| 2         | 2               |
+-----------+-----------------+

Then i made a research to bring that results with Month and Year. My table has a data for each Status. I made this SQL:
SELECT to_char(datestatus,'Mon') AS month, extract(year from datestatus) as year, COUNT (*) as count,
 FROM tb_status as st
 LEFT JOIN tb_document as dc ON st.iddocument = dc.iddocument
    WHERE NOT EXISTS (
        SELECT * FROM tb_status as stt
        WHERE stt.idprocess=st.idprocess
        AND stt.idstatus > st.idstatus
        )
 GROUP BY year, month

This one bring a result like this example:
+-----------+-----------------+------------------+
|   month   |      year       |     count        |
+-----------+-----------------+------------------+
| Nov       | 2016            | 1                |
+-----------+-----------------+------------------+
| Dec       | 2016            | 1                |
+-----------+-----------------+------------------+
| Mar       | 2017            | 2                |
+-----------+-----------------+------------------+

But i when i try to increment this last SQL to bring the Status, i get errors or get multiple lines with wrong results.

P.S.: This "WHERE NOT EXISTIS ()" is a method to take into consideration the latest status from each Document (since its always begin with "Waiting"
  and pass trough others until get "Concluded")

Is there a simple way to mix these two SQL into a new one? Any tips? I need something like this example:
+-----------+-----------------+------------------+------------------+
|   month   |      year       |     wt           |        cc        |
+-----------+-----------------+------------------+------------------+
| Nov       | 2016            | 1                | 0 (or null)      |
+-----------+-----------------+------------------+------------------+
| Dec       | 2016            | 0 (or null)      | 1                |
+-----------+-----------------+------------------+------------------+
| Mar       | 2017            | 1                | 1                |
+-----------+-----------------+------------------+------------------+

Comment: Edit your question and show what your data structure looks like.  The queries look more complicated than needed for the stated purpose.
Comment: @GordonLinoff thanks. Yes, i was planning bring my tables and the full (or part of) SQL to ask if there's a better way to get the same result. Thanks for your answer btw.. i'll check it out and see how it work.
Answer: Your query is way more complicated than I think it needs to be.  The following gets the most recent status for each document:
SELECT DISTINCT ON (st.iddocument) . . .
FROM tb_status st JOIN
     tb_document dc
     ON st.iddocument = dc.iddocument
ORDER BY st.iddocument, st.idstatus DESC;

You can then aggregate the status values using a subquery:
SELECT SUM( (status LIKE '%Waiting%')::int) as waiting,
       SUM( (status LIKE '%Concluded%')::int) as Concluded
FROM (SELECT DISTINCT ON (st.iddocument) . . ..
      FROM tb_status st JOIN
           tb_document dc
           ON st.iddocument = dc.iddocument
      ORDER BY st.iddocument, st.idstatus DESC
     ) s;

And you can easily add dates:
SELECT DATE_TRUNC('month', datestatus) as yyyymm,
       SUM( (status LIKE '%Waiting%')::int) as waiting,
       SUM( (status LIKE '%Concluded%')::int) as Concluded
FROM (SELECT DISTINCT ON (st.iddocument) st.*  -- Are other columns needed?
      FROM tb_status st JOIN
           tb_document dc
           ON st.iddocument = dc.iddocument
      ORDER BY st.iddocument, st.idstatus DESC
     ) s
GROUP BY yyyymm
ORDER BY yyyymm;


How can I reach A bigger number of dwellers?

Question: I can't reach a bigger number of dwellers, I have female dwellers, which are pregnant for more than three days. Usualy it takes just a few hours. The game is showing me that I have reached the maximum count of dwellers that is 50/50. I have also free rooms without any dwellers. What should I do?
Comment: Warning: once you build enough living quarters for 200 dwellers, the game will not allow you to build any more living quarters. Be careful about allowing your dwellers to become pregnant when you start getting close to this limit.
Answer: You need to make more living quarters.  While you are at it, you may need need more power, food, and water to supply your additional dwellers.


Why does Console.Readline() have a limit on the length of text it allows?

Question:
Possible Duplicate:
Console.Readline() max length?

In my attempt to find a very simple text to speech application I decided it was faster to write my own. I noticed, however, that Console.Readline() is limited in the amount of text it allows per line to 254 characters; I can't find anything about this limit in the method documentation.
Is this a limitation in the Windows stack, or a problem with my code? How can I overcome it? I could decide to read character by character with Console.Readkey(), but won't I then risk losing characters to the MS DOS dumb text pasting behavior?
Comment: Please note I understand where 254 must come from - that's 256 bytes, minus a new line and the feed return. I don't know where that 256 came from, however.
Answer: This is a somewhat bizarre limitation on the Console API. I had this problem before and found the following solutions:
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));

From the following MSDN forum post:
http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/51ad87c5-92a3-4bb3-8385-bf66a48d6953
See also this related StackOverflow question:
Console.ReadLine() max length?
Comment: for me I needed the following: Console.SetIn(new StreamReader(Console.OpenStandardInput(8192), Console.InputEncoding, false, 8192));
Answer: A quick look at implementation with .NET Reflector gives this:
public static Stream OpenStandardInput()
{
    return OpenStandardInput(0x100);
}

public static Stream OpenStandardInput(int bufferSize)
{
  ...
}

256 is the default value of OpenStandardInput, so I guess it's by design. Note this is only for .NET as the Windows API does not have this limit.


How to pump gases? (not compress them, nor create vacuum, just pump)

Question: I have a container that is not hermetically sealed. It is filled with a certain gas/vapor: gaseous water (steam). I want to pump the gas/vapor outside, to the atmosphere. I have 2 questions:
1- What is the name for the device I need? Pump terminology seems extremely vague and confusing.

It is a pump, but it's for gases, not necessarily for liquids.
It is not necessarily a compressor, since the pumped gas is evacuated to the atmosphere, not compressed into a cylinder.
It is not necessarily a vacuum pump, since the container is not sealed, as the gas is evacuated it will be replaced by fresh air, never reaching a significant vacuum.
It must of course not be manual (not a bicycle pump!)

2- In any case, can someone recommend me a device for this?
For example, perhaps a regular water pump could work even if I'm trying to pump a gas, or perhaps a vacuum pump could work even if I'm not trying to reach a vacuum.
Comment: Fans are often used for this purpose.
Comment: I'm having trouble correlating this to a home improvement project. We're not an industrial engineering site.
Comment: It's called a fan or blower.  When the steam leaves the container, what replaces it?  How does this makeup gas enter the container, or do you aim to draw a vacuum on the container? This really, really sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Those tend to be very bad questions.  You're not the only one who's faced the root problem.
Comment: Now wait. If the container is full of steam,then it's either far below atmospheric pressure,or at or above the boiling point of water. Either case significantly limits the options. Which one is it?
Comment: You may want to specify what kind of gas you're moving, as there may be requirements about flammability and or explosions to consider. At a minimum, indicate if the gas is inert, flammable, or explosive.
Comment: @FreeMan. There I edited the question. The gas is water in the gas state.
Comment: You could set up a shop vac with a vortex chamber; but not sure if any steam would still reach the shop vac and create corrosion in the vac.
Answer: You need an axial compressor, which (despite the name) is used to move gas/vapor (but can also function as a compressor in a closed system). A common name for this is a fan.
For your purposes, it could be as simple as an in-line electric fan installed in the duct, at the duct outlet to atmosphere, or in the "container" at the duct inlet.
Example:


Can you use publish from a method called in run in background?

Question: I am using swingworker to run a method in the background and periodically update the gui with information, but from what I've found publish can't be called from another class. Here's where my Swingworker is called:
private void start() {
    worker = new SwingWorker <Void, String>() {

        @Override
        protected Void doInBackground() throws Exception {
            navigator.navigator();

            return null;
        }
        @Override
        protected void process(List<String> chunks) {
            for (String line : chunks) {
                txtrHello.append(line);
                txtrHello.append("\n");
            }
        }
        @Override
        protected void done() {

        }

    };
    worker.execute();
}

And now from the navigator method I want to call publish(String);, how would I do this? Moving all of my methods into doInBackground() would be impossible.
Comment: Oops, that statement above should read, "is not a true duplicate". And so I have re-opened the question.
Answer: Possible solution is to add an observer to your Navigator object, the key being to somehow allow the Navigator to communicate with any listener (here the SwingWorker) that its state has changed:

Give Navigator a PropertyChangeSupport object as well as an addPropertyChangeListener(PropertyChangeListener listener) method that adds the passed in listener to the support object.
Give Navigator some type of "bound" property, a field that when its state is changed, often in a setXxxx(...) type method, notifies the support object of this change.
Then in your SwingWorker constructor, add a PropertyChangeListener to your Navigator object.
In this listener, call the publish method with the new data from your Navigator object.

For example:
import java.awt.event.ActionEvent;
import java.beans.*;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class PropChangeSupportEg extends JPanel {
   private MyNavigator myNavigator = new MyNavigator();
   private JTextField textField = new JTextField(10);

   public PropChangeSupportEg() {
      textField.setFocusable(false);
      add(textField);
      add(new JButton(new StartAction("Start")));
      add(new JButton(new StopAction("Stop")));
   }

   private class StartAction extends AbstractAction {
      public StartAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (myNavigator.isUpdatingText()) {
            return; // it's already running
         }
         MyWorker worker = new MyWorker();
         worker.execute();
      }
   }

   private class StopAction extends AbstractAction {
      public StopAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         myNavigator.stop();
      }
   }

   private class MyWorker extends SwingWorker<Void, String> {
      @Override
      protected Void doInBackground() throws Exception {
         if (myNavigator.isUpdatingText()) {
            return null;
         }

         myNavigator.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
               if (MyNavigator.BOUND_PROPERTY_TEXT.equals(evt.getPropertyName())) {
                  publish(evt.getNewValue().toString());
               }
            }
         });
         myNavigator.start();
         return null;
      }

      @Override
      protected void process(List<String> chunks) {
         for (String chunk : chunks) {
            textField.setText(chunk);
         }
      }

   }

   private static void createAndShowGui() {
      PropChangeSupportEg mainPanel = new PropChangeSupportEg();

      JFrame frame = new JFrame("Prop Change Eg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MyNavigator {
   public static final String BOUND_PROPERTY_TEXT = "bound property text";
   public static final String UPDATING_TEXT = "updating text";
   private static final long SLEEP_TIME = 1000;
   private PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);
   private String boundPropertyText = "";
   private String[] textArray = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
   private int textArrayIndex = 0;
   private volatile boolean updatingText = false;

   public void start() {
      if (updatingText) {
         return;
      }
      updatingText = true;
      while (updatingText) {
         textArrayIndex++;
         textArrayIndex %= textArray.length;
         setBoundPropertyText(textArray[textArrayIndex]);
         try {
            Thread.sleep(SLEEP_TIME);
         } catch (InterruptedException e) {}
      }
   }

   public void stop() {
      setUpdatingText(false);
   }

   public String getBoundPropertyText() {
      return boundPropertyText;
   }

   public boolean isUpdatingText() {
      return updatingText;
   }

   public void setUpdatingText(boolean updatingText) {
      boolean oldValue = this.updatingText;
      boolean newValue = updatingText;
      this.updatingText = updatingText;
      pcSupport.firePropertyChange(UPDATING_TEXT, oldValue, newValue);
   }

   public void setBoundPropertyText(String boundPropertyText) {
      String oldValue = this.boundPropertyText;
      String newValue = boundPropertyText;
      this.boundPropertyText = boundPropertyText;
      pcSupport.firePropertyChange(BOUND_PROPERTY_TEXT, oldValue, newValue);
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      pcSupport.removePropertyChangeListener(listener);
   }
}

Comment: @HovercraftFullOfEels: Yes; a `String` is [effectively immutable](http://stackoverflow.com/q/16678416/230513); when invoked from `doInBackground()`, `navigator()` _could_ call `publish()` safely, but we'd need to see.
Comment: @BenOrgera: for example.
Comment: Interesting to get a down-vote for my efforts. Ah well, chit happens.
Comment: thank you, not a down vote just was gone for a few hours
Comment: @HovercraftFullOfEels: Not your down voter, but I'm concerned that `PropertyChangeSupport` doesn't provide the synchronization suggested [here](http://stackoverflow.com/a/6516351/230513); I think we need to see `navigator()`.
Comment: @trashgod: thanks for the info. Please correct me if I'm wrong, but this would only be an issue if Navigator is being used by multiple threads, correct?


Cassandra Python executing multiple statement from string using python drive?

Question: I want to execute multiple cql statements (2 or much more) using python driver.
I try such simple code but it lead to error if query contains more then one statement. I do not want to split statements or format it (to single statements). I just want to execute whole CQL.
How to do it with python driver for Cassandra - is it possible?
I use ; as statement split.
from cassandra.cluster import Cluster

def main():
    cluster = Cluster(contact_points=['cassandra-1.', 'cassandra-2.', 'cassandra-3.', 'cassandra-4.'])
    session = cluster.connect()
    session.execute('drop keyspace if exists test')
    session.execute('''
        create keyspace test
        with durable_writes = true
        and replication = {
            'class' : 'SimpleStrategy',
            'replication_factor' : 3
        };
    ''')
    session.set_keyspace('test')

    # two statements or more and there is error
    # how to execute all in one call?
    query = '''\
    create table x1 (
        name text,

        primary key ((name))
    );

    create table x2 (
        name text,

        primary key ((name))
    );
    '''

    result_set = session.execute(query)
    print(result_set)

if __name__ == '__main__':
    main()

It generates such error:
Traceback (most recent call last):
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 39, in <module>
    main()
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandbox\cassandra_scheme\04_execute_multiple_statements.py", line 34, in main
    result_set = session.execute(query)
  File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute
  File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 7:4 mismatched input 'create' expecting EOF (... ((name))    );    [create]...)">

Answer: Each statement should be separate. Just split text on ; using your Python code, and execute them separately.  Also, please take into account that programmatic schema modifications like yours are potentially dangerous - you may get so-called schema disagreement that will require to fix it by rolling restart of the cluster.
Comment: By default, driver uses round robin load balancing policy. This means that different queries may land on different nodes, and there could be a chance that the second query may land on the node that isn't received the notification about first query, and it will generate a new schema version that will conflict with version from another node. cqlsh solves that problem by using whitelist policy - it will send all queries to the same node. You also need to wait for schema agreement.
Comment: Here is code example in Java: https://github.com/alexott/cassandra-dse-playground/blob/master/driver-1.x/src/main/java/com/datastax/alexott/demos/WhiteListPolicyExample.java#L37
Comment: Consistency levels don't work for schema modifications - it's a different mechanism. Main thing - check for schema agreement
Comment: I think about this solution with split. Why programmatic schema modification can lead to errors (is other way to do it if not by queries)?

I assume that I will stop traffic for such changes for some minutes to stabilize schema. Is it not enough?
Comment: Thank you for "schema disagreement" I will study what is it.
Comment: That is greate example. So I should disable round robin for change of schema (if possible) and confirm change before and production traffic. Thank you for this good example. I often do not write in Java but code is very clear for me. I will check what Python driver do maybe the same and some policy should be modified to make clear schema change without nodes fixes.
Comment: Yes, it should be similar for Python
Comment: I found this for Python. It looks that driver is simpler and they do it little differently ... consistency_level=ConsistencyLevel.ALL. It is not same but can do same because it force all nodes to be updated - no experience (maybe not work with DC).

https://github.com/datastax/python-driver/blob/master/tests/integration/long/test_schema.py
Comment: They check rs.response_future.is_schema_agreed == True.


Java Color Histogram all Colors not RGB separate

Question: I would like to extract a color histogram out of a BufferedImage (Java). I don't want to extract a separate histogram for red, green and blue, but I would like to have one histogram including all available colors (including a binning). It would be nice if the neighboring bins  look similar to each other.
I don't have an Idea how to define the bins, since colors are not one-dimensional. Another problem is the allocation of a color to its bin.
Does somebody have an idea or a library to realize it?
Best,
Michael
Answer: You can separately calculate histograms for red, green and blue and then find the mean of them and draw result grapic. Take a look at this article.
Or you can create a cube 3d histogram (each edge responces for one color). Here's result of it (java).
Comment: A cube 3d histogram with slicing it in small sub-cubes brought a sufficient solution. Thanks :)
Answer: Just an idea:
open some image editor (e.g. Paint) and look at their color pickers to get an idea on how to arrange colors.
I think I would arrange them by HUE (enter link description here) since it would be a an unidimensional arrangement that easily matches the idea of "color bins" and it also puts similar colors near each other in a rainbow fashion.
However, using Hue-only (discarding luminance and saturation) means that you might put colors that look very differently in the picture in the same bin.
Another way would be to automatically "cluster" all the colors in the picture into a fixed number of bins (e.g. 16) by using some kind of statical cluster analysis on the full RGB info (e.g. using all 3 RGB components) and then display the graph with the 16 "mean color" of each cluster below the corresponding histogram bar.


mysql get max number from a string field

Question: I need to get maximum number from a part of the value that generally start with year followed by slash(/). So I need a maximum number after the slash(/) but year should be 2016
2016/422
2016/423
2016/469
2016/0470
2014/777
2015/123
2015/989

I tried this query
SELECT columname FROM tablename WHERE columname LIKE '2016/%'  ORDER BY id  DESC

the above query always giving '2016/469' as first record, how to get '2016/0470' as the maximum number?
any help will be much appreciated.
Thank you.
Comment: Are you saying that you want to remove `/`,  convert the result to Number and then find their `MAX`?
Comment: I need this ''2016/0470' record. as this is the max number after the slash
Comment: Are you guaranteed to have a slash in each and every record? If so, is it always in 5th position?
Comment: Just do what @PM77-1 sad:     `SELECT MAX(REPLACE(columname, '/', '')) FROM tablename`;
Comment: @PM77-1, and karacsi_maci, the leading 0 might be a problem here, if you had `2016/0422` and `2016/470`, the result is `20160422` and `2016470`
Comment: @AxelH - Since OP clarified that he is interested in *number after the slash(/)*, this issue is now irrelevant.
Comment: @PM77-1, sorry, I was mainly pointing this at **karacsi_maci**, suggesting this after the clarification.
Comment: is not good to change the terms
Comment: sorry about that. I was interested for the year 2016, that i mentioned in query, but i released you guys are looking for max number, irrespective of year
Answer: If columname follows that pattern YEAR/0000, you can use SUBSTRING function from MySQL to remove the part of the string you don't want.
SELECT value FROM (
    SELECT CAST(SUBSTRING(columname, 0, 4) AS UNSIGNED) as year, CAST(SUBSTRING(columname FROM 6) AS UNSIGNED) as value FROM tablename
) total
ORDER BY year DESC, value DESC
LIMIT 1;

Comment: You need `CAST`/`CONVERT` to a **number**, otherwise "0740" will not be the maximum.
Comment: Just was thinking on that issue. Editing.
Comment: Thanks for the response. I'm looking for the max number after '2016/'
Comment: @Developer I updated the answer to fulfill your needs.
Comment: thanks for the update, but its not giving me the result for '2016/', its giving for '2011/' record
Answer: You need to split the string into 2 parts and evaluate them as numbers, instead of strings. The following formula will return the number after the / in the fieldname. All functions used below are described in the string functions section of the MySQL documentation. This way you can get the number after the / character, even if it is not year before the /, but sg else. The + 0 converts the string to a number, eliminating any leading 0.
select right(columnname, char_length(columnname)-locate('/',columnname)) + 0
from tablename

Just take the max() of the above expression to get the expected results.
UPDATE:
If you need the original number and the result has to be restricted to a specific year, then you need to join back the results to the original table:
select columnname
from tablename t1
inner join (select max(right(t.columnname, char_length(t.columnname)-locate('/',t.columnname)) + 0) as max_num
            from tablename t
            where left(t.columnname,4)='2016'
           ) t2
           on right(t1.columnname, char_length(1t.columnname)-locate('/',t1.columnname)) + 0 = t2.max_num
where left(t1.columnname,4)='2016'

Comment: Thanks for the response. it should give me the max number for the year 2016
Comment: It will give you back the max number after the / character across the entire table. You need to provide additional filters if you have other data than 2016 in your table.
Comment: I got other years with bigger numbers in the table, that I could not figure out how to write query for.
Comment: Thanks for your time. Big thanks to everyone and community. this fixed my problem. Thank you very much @Shadow
Answer: There are lots of suggestions given as answers already. But some of those seem overkill to me.
Seems like the only change needed to the OP query is the expression in the ORDER BY clause.
Instead of:
 ORDER BY id

We just need to order by the numeric value following the slash. And there are several approaches, several expressions, that will get that from the example data.
Since the query already includes a condition  columname LIKE '2016/%'
We can get the characters after the first five characters, and then convert that string to a numeric value by adding zero.
 ORDER BY SUBSTRING(columname,6) + 0 DESC

If we only want to return one row, add
 LIMIT 1

http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring
If we only want to return the numeric value, we could use the same expression in the SELECT list, in addition columnname.
This isn't the only approach. There are lots of other approaches that will work, and don't use SUBSTRING.
Comment: Thanks for getting me right here from my query. but I'm not too sure how it works, for numbers like 2016/0001, 2016/0022, 2016/0322. where i can have multiple zeros too
Comment: As a demonstration:  `SELECT '0407' + 0` will return numeric value `407`.  Basically, to perform the `+ 0` operation, MySQL will need to convert the string value `'0407'` into a numeric value. The result of that expression is numeric value `407`.  it doesn't matter how many leading zeros you add to that string, the result is still `407`.  (The purpose of the `SUBSTRING` is to remove the leading `'2016/'` characters, leaving returning the characters following.
Comment: Note that the expression in the selected answer from Shadow is doing the same thing... removing the `'2016/'` and using a `+ 0` operation to convert to numeric.
Answer: Try like this:
SELECT
    MAX(CAST(SUBSTRING(t.name,
            LOCATE('/', t.name) + 1)
        AS UNSIGNED)) AS max_value
FROM
    tablename AS t;

Answer: You can try with this little uggly approach:
    SELECT t.id, t2.secondNumber FROM table AS t
    JOIN (SELECT id,
                 CONCAT(SUBSTRING(field,1,5),
                   if(SUBSTRING(SUBSTRING(field, 6),1,1)='0',
                      SUBSTRING(field, 6),
                      SUBSTRING(field,7)
                   )
                 ) as secondNumber FROM table ) AS t2 ON t2.id=t.id
    ORDER BY t2.secondNumber DESC

Would be valid only if the 0 (zeroes) before the second number (after the slash) are no more than 1.
Or if the year doesn`t matter you can try to order them only by the second number if it is ok:
SELECT t.id, t2.secondNumber FROM table AS t
JOIN (SELECT id,
               if(SUBSTRING(SUBSTRING(field, 6),1,1)='0',
                  SUBSTRING(field, 6),
                  SUBSTRING(field,7)
               ) as secondNumber FROM table ) AS t2 ON t2.id=t.id
ORDER BY t2.secondNumber DESC


PHP use full path from root to link to file instead of going from parent

Question: I need to be able to access a file in a folder located in the root directory on each of my pages.
Is there a piece of code I can use to type out the full directory going from the root folder to the specific folder I want and be able to copy onto each page without having to change the code?
For more clarification, it's hard to word, but I want to be able to link top my CSS file in the directory /css on each page without manually having to put ../../ etc.
Or does anyone else know the best way to link one style sheet to each page with ease?
Comment: Did you try to use $_SERVER['DOCUMENT_ROOT']?
Comment: I did, but despite working in another bit of code, it tried to load /c://users/tom/... if you get my jist. Not sure what happened, but it was perfect code. Is it true I can just do a "/" before the directory in basic HTML to get back to the root folder?
Comment: No you have to put "../"
Comment: Are you talking about _server-side_ or _client-side_ path here? Form your comment, I think it might be the latter. Then you can simply prefix your relative path with a leading slash `/` – the browser will complete that using the current protocol and domain.
Comment: [Relative and absolute paths](http://www.boogiejack.com/server_paths.html) a little guide about this
Comment: I went with the "/" starting for the link to the CSS file, which worked :)
Answer: If the root of your website has the path / (in other words, the address you type for the root of your website is something like http://mydomain.com/) then you can simply refer to your CSS files using /my.css or /css/my.css in all pages. The leading / tells the browser to look for these files relative to the root of your website.
Comment: AHA! That's the one. I never realised this was actually a thing, despite studying HTML since I was 10... Oh dear. This seems to have solved everything
Answer: You should be able to use a relative path of /folder path that will be accessible from all your pages.
You should also be able to do it the same was Cristian is recommending with:
    $folder = $_SERVER['DOCUMENT_ROOT']."/folder path";

Comment: Unfortunatley I couldn't get that to work. Although this is a different way of doing it, it will be handy in the future, so thanks for your answer :)


Displaying similar bars together in ggplot

Question: I have a Count for each Site (which corresponds with a country), and each Site belongs to a Region. The data looks like this:
> summary_data
     Site Count   Region
1    Chad     5   Africa
2  Angola     1   Africa
3  France    10   Europe
4     USA     6 Americas
5 Bolivia     3 Americas
6   Chile     4 Americas

I would like to generate a bar graph that:

Has a bar per country
The bars for a region are all next to each other in the bar graph
Per region, the bars appear in descending order
The bars are all the same width, but the heights are all on the same scale
Can be generalized (in particular: arbitrary regions, arbitrary countries per region)
I do not want to use fill color to represent the region (I want to use color to represent another characteristic eventually)
I want to have some visual representation to group the columns. For instance, having a gray background behind all the columns for the Americas region, a blue background behind all the columns for the Africa region, etc). I actually would be open to other approaches (perhaps a line at the top spanning all of Africa with "Africa" as a label or something).

Obviously each region can have a different number of country sites, and no country site spans two regions (I tried using facets but quickly realized that was not the right route). I also tried looping through all the regions to generate separate graphs per region and then put them together but that didn't quite seem the right approach either.
I have generated a graph like this (Closest I have gotten):

Using this code:
library("dplyr")
library(ggplot2)
sorted <- arrange(summary_data,Region,-Count)
sorted$Site <- factor(sorted$Site, levels = sorted$Site)
bar = ggplot(sorted,
   aes(
     x = Site,
     y = Count,
     fill = Region
   )) +
  geom_col()
print(bar)

But this does not meet the last two requirements I set above (I specifically do not want to use fill to represent region). I started down the path of geom_rect() but did not understand the coordinate system for discrete x values rather than continuous (I did find Stackoverflow questions / answers on continuous but didn't see how to translate to this). I think having shaded rectangles behind the columns is probably the best approach, but I would appreciate any input in general approach as well as how to pull it off.
Comment: You could use `ggplot(sorted, aes(x = Region, y = Count, fill = Site)) + geom_bar(position = "dodge", stat = "identity")` which would give you grouped columns by `Region`. Further, you could fill the bars by whatever scale you want and just add the country name as a `geom_text()` to the plot.
Comment: Thanks @Steven. I get columns of different widths this way. Each Region gets the same width but the columns are fit inside that standard width (so Europe with just one Site gets the full width whereas Americas gets three columns in that same width). Is there a way of forcing a consistent bar width using this approach? Thanks again.
Comment: @DavidHobbs You have indicated that the answer below is your desired solution. You could also indicate that it was "adding value" by clicking the upper arrow, leading to more credits to the person who helped you. **Up to you, I just wanted to point out this possibility**. In some cases, the difference between the two is relevant. In this case, your comment *This is perfect!* seems to indicate that you may want to grant both kind of rewards.
Answer: You could consider defining a new panel for each region to separate them using facet_grid. If you want the colors to be the same, just remove the aes(fill = Site) argument inside geom_bar.
The argument space = "free_x" assures that the width of the bars are the same and with scale = free only those axis values corresponding to the specific region are shown.
ggplot(sorted, aes(x = Site, y = Count)) +
   geom_bar(position = "dodge", stat = "identity", aes(fill = Site)) +
   facet_grid(. ~ Region,scale="free",  space="free_x")

Comment: This is perfect! That combination of space = "free_x" and scale = "free" does the trick. Thanks.
Comment: Glad it helped!


Loading form data from json

Question: I like to improve my code. I want to load the html form data from a json file by using ajax.
here is my code:

any points to improve??
file looks like:
{
  "devicename": "t",
  "mqtt_host": "z",
  "mqtt_username": "z",
  "mqtt_pass": "t",
  "mqtt_port": "7",
  "mqtt_ssl": "65"
}

Thanks
Comment: Yup you could fetch the data from JSON and use it in your code. I hope this will solve https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript
Comment: This question would probably fit better in [code review](https://codereview.stackexchange.com/).
Answer: If json data contains id's of the elements, than you can use for loop:
getFile('config.json', function(allText) {
  var configdata = JSON.parse(allText);
  for(let id in configdata)
    document.getElementById(id).value = configdata[id];
});

Answer: On modern browsers you can use fetch(), so there will be no need for your getfile() function.

const d={
  "devicename": "t",
  "mqtt_host": "z",
  "mqtt_username": "z",
  "mqtt_pass": "t",
  "mqtt_port": "7",
  "mqtt_ssl": "65"
};

// fetch("config.json").then(r=>r.json()).then(d=>
 Object.entries(d).map(([k,v])=>
  document.getElementById(k).value=v)
// )
<input type="text" id="devicename"> device

<input type="text" id="mqtt_host"> host

<input type="text" id="mqtt_username"> user

<input type="text" id="mqtt_pass"> password

<input type="text" id="mqtt_port"> port

<input type="text" id="mqtt_ssl"> ssl

Loading form data from json


Correctly plot time series in Highcharts/Highstock

Question: I have large collection of data in the format [1421065200000, 1.72], where the first parameter is time in milliseconds and the second parameter is the value at that specific time. I have data array consisting of such data in large size. Now I want scrollable graph containing plot of such time and value data. Here is my javascript implementation to do so,
var dataArray; //This contains my data array i.e. ([[t1, v1],[t2, v2],...])

var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];

var chartOption = {
        chart: {
            type: graphType,
            renderTo: 'graph-container',
            zoomType: 'x',
            useUTC: false
        },
        title: {
            text: 'Data from last 24 hours'
        },
        credits : {
            enabled: false
        },
        xAxis: {
            title: {
                text: null
            },
            type: 'datetime',
            dateTimeLabelFormats: {
                second: '%Y-%m-%d
%H:%M:%S',
                minute: '%Y-%m-%d
%H:%M',
                hour: '%Y-%m-%d
%H:%M',
                day: '%Y
%m-%d',
                week: '%Y
%m-%d',
                month: '%Y-%m',
                year: '%Y'
            },
            allowDecimals: false,
            ordinal: false,
            min: minDate,
            max: maxDate
        },
        yAxis: {
            title: {
                text: null
            }
        },
        plotOptions: {
            series: {
                pointStart: minDate,
                pointInterval: 5 * 60 *1000
            }
        },
        series: [{
            name: parameterName,
            data: dataArray
        }],
        exporting: {
            enabled: false
        }
    };

    parameterChart = new Highcharts.Chart(chartOption);
}

The chart shows incorrect data, the time value on x-axis doesn't match the value at y-axis. What is the most correct and efficient to show such time series. Should I use Highcharts or Highstock. Please guide me through this, with suggestion or maybe with solution.
Comment: Could you recreae your example as live demo, inluding hardoced data ?
Comment: @SebastianBochan I have solved my issue, I have provided the source I came up with. However, I will be adding a live demo with hardcoded data. Thank you for the concern :)
Answer: What I did was, I used HighStock instead of HighCharts (since I needed scrollbar along x-axis for large collection of data). I was passing the date in my local time zone format, whereas the chart was using UTC. So, I disabled the use of UTC (alternative: I could have provided data in UTC and drawn the graph using the same, In my case I needed my local labels). I gave the minimum and maximum range to the x-axis through x-axis min and max configuration. Here is the sample of my code,
//dataArray contains the array of data [[x1, y1], [x2, y2], ...]
//x is Date, y is temperature value (say)

var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];

//Disable use of UTC
Highcharts.setOptions({
    global: {
        useUTC: false
    }
});

//Create graph options
var chartOption = {
    chart: {
        type: graphType, //line, bar, column, etc
        renderTo: 'graph-container', //div where my graph will be drawn
        zoomType: 'x' //Making x-axis zoomable/scrollable
    },
    title: {
        text: 'Data from last 6 hours'
    },
    subtitle: {
        text: document.ontouchstart === undefined ?
            'Click and drag in the plot area to zoom in' :
            'Pinch the chart to zoom in'
    },
    xAxis: {
        title: {
            text: null
        },
        type: 'datetime', //For time series, x-axis labels will be time
        labels: {
            //You can format the label according to your need
            format: '{value:%H:%m}'
        },
        min: minDate,
        max: maxDate,
        minPadding: 0.05,
        maxPadding: 0.05
    },
    yAxis: {
        title: {
            text: null
        }
    },
    scrollbar: {
        enabled: true
    },
    series: [{
        name: "Temperature", //Name of the series
        data: dataArray
    }],
    exporting: {
        enabled: false
    },
    credits : {
        enabled: false
    }
};

//Finally create the graph
var myChart = new Highcharts.Chart(chartOption);


How is the getView() method used and where is it getting called?

Question: I am new to Android development and have been following the tutorials available on the Android website. I am currently on the section of tutorials for Views, specifically the one for Grid Views: Hello, Grid View Tutorial.
I am having trouble understanding how views are made through an adapter. I understand that you must override the getView() method in your adapter class and in this method is where you define how your Views are set up. What I don't understand is where does getView() actually get called? Perhaps I've got the wrong kind of mentality here, but in the code below (the Grid View tutorial) I don't see any calls to getView() (or any other things used in the adapter class such as getCount()).
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

Start.java
package com.examples.hellogridlayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Start extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridview = (GridView)findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new OnItemClickListener(){
        public void onItemClick(AdapterView<?> parent,View v, int position, long     id){
            Toast.makeText(Start.this, "" + position,Toast.LENGTH_SHORT).show();
        }

      });
    }
}

ImageAdapter.java
package com.examples.hellogridlayout;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
    return mThumbIds.length;
    }

    public Object getItem(int position) {
    return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
    };
}

Answer: By setting Adapter, you are telling GridView to fetch views from the Adapter to fill up all the grids. So getView is internally called by GridView to fill up the layout.
Thats why all the adapters implements Adapter interface so that any AdapterView can request the Adapter.
Answer: Adapter.getView is called inside ObtainView method, inherited from GridView parent class AbsListView, with ScrapView objects passed in when available:
child = mAdapter.getView(position, scrapView, this);

Then ObtainView is implemented in GridView.onMeasure directly but also in several more callbacks that invoke GridView.layoutChildren, including inherited onTouchEvent method which handles scroll, fling and other touch navigation.


Still getting error after set newxreg=NULL in R

Question: I am relatively new to R. I was using auto.arima and predict to predict a time series data. Here is the code I am using:
train.arima=auto.arima(train, seasonal=F, xreg=NULL)
train.pd=predict(train.arima, n.ahead=numahead, newxreg=NULL)

I am getting this error message, although I already set the xreg and newxreg as NULL
Error in predict.Arima(train.arima, n.ahead = numahead, newxreg = NULL) :
'xreg' and 'newxreg' have different numbers of columns: 1 != 0

Could anyone help please??
Comment: Do you have a small reproducible example? For example, can you paste in the output of `dput(head(train))`, `dput(head(test))`?
Comment: what is `numahead`?  Might be better to use `forecast(train.arima, h = 10)` for 10 (arbitrary) predictions.
Answer: Use forecast not predict. auto.arima sometimes selects a drift term which cannot be handled by a simple call to predict.
Comment: I would upvote this answer five times if I could. This has been driving me crazy for days.


HP 2133 Video Resolution Problem in LUbuntu Bionic Beaver (18.04 LTS)

Question: First of all: I know this is a VERY OLD Netbook. However, due to it's "compactness", it's my perfect companion while wandering thru the Datacenter patching / fixing / whatever. This Model was sold with Windows Vista, which in due time I replaced with Windows XP (and it was pretty fast). Problem is, XP is looong dead now.
I installed LUbuntu 18.04 LTS on this machine, and everything worked fine, except for Video Display, which required to install "xserver-xorg-video-openchrome" package, which I did.
Now I get Full Display support, BUT... This Netbook's Native 1024x600 Screen is detected as "1024x768" capable (by xorg), and thus, the lower 168 Lines of Desktop fall OUTSIDE the Screen, to the bottom!
I've researched the Net looking for solutions to this, and I have found some (very old) ones, that needed me to modify the "/etc/X11/xorg.conf" file, which has no longer existed for quite some time now (and I'm UNSURE of how to make xorg to revert to use an static xorg.conf).
I think this may be related to this old bug (implicating Broadcom BCM4312 802.11b/g LP-PHY Wi-Fi Card), as I first tried Lubuntu 17.10.1 (Artful Aardvark) on this machine (as a test), and then Wi-Fi Connectivity was a non-working bloody mess, but Video Display was correctly autoconfigured with 1024x600 Resolution.
Here is the output of lspci:
00:00.0 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:00.1 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:00.2 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:00.3 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:00.4 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:00.5 PIC: VIA Technologies, Inc. CN896/VN896/P4M900 I/O APIC Interrupt Controller
00:00.6 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Security Device
00:00.7 Host bridge: VIA Technologies, Inc. CN896/VN896/P4M900 Host Bridge
00:01.0 PCI bridge: VIA Technologies, Inc. VT8237/VX700 PCI Bridge
00:02.0 PCI bridge: VIA Technologies, Inc. CN896/VN896/P4M900 PCI to PCI Bridge Controller (rev 80)
00:03.0 PCI bridge: VIA Technologies, Inc. CN896/VN896/P4M900 PCI to PCI Bridge Controller (rev 80)
00:0f.0 IDE interface: VIA Technologies, Inc. VT8237/8251 Serial ATA Controller
00:10.0 USB controller: VIA Technologies, Inc. VT82xx/62xx UHCI USB 1.1 Controller (rev b0)
00:10.2 USB controller: VIA Technologies, Inc. VT82xx/62xx UHCI USB 1.1 Controller (rev b0)
00:10.3 USB controller: VIA Technologies, Inc. VT82xx/62xx UHCI USB 1.1 Controller (rev b0)
00:10.4 USB controller: VIA Technologies, Inc. USB 2.0 (rev 90)
00:11.0 ISA bridge: VIA Technologies, Inc. VT8237S PCI to ISA Bridge
00:11.7 Host bridge: VIA Technologies, Inc. VT8237/8251 Ultra VLINK Controller
00:13.0 Host bridge: VIA Technologies, Inc. VT8237A Host Bridge
00:13.1 PCI bridge: VIA Technologies, Inc. VT8237A PCI to PCI Bridge
01:00.0 VGA compatible controller: VIA Technologies, Inc. CN896/VN896/P4M900 [Chrome 9 HC] (rev 01)
02:00.0 Network controller: Broadcom Limited BCM4312 802.11b/g LP-PHY (rev 01)
07:03.0 Ethernet controller: Broadcom Limited NetXtreme BCM5788 Gigabit Ethernet (rev 03)
80:01.0 Audio device: VIA Technologies, Inc. VT8237A/VT8251 HDA Controller (rev 10)

Here is the output of lsusb:
Bus 001 Device 004: ID 04f2:b107 Chicony Electronics Co., Ltd CNF7070 Webcam
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 003: ID 03f0:171d Hewlett-Packard Bluetooth 2.0 Interface [Broadcom BCM2045]
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 002: ID 0458:003a KYE Systems Corp. (Mouse Systems) NetScroll+ Mini Traveler / Genius NetScroll 120
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

And, from my current /var/log/Xorg.0.log, line #230, it can be seen that xorg autodetects my screen as one with Native Resolution 1024x768:
(Line #230) --> [    37.775] (II) CHROME(0): Flat Panel Native Resolution: 1024x768

Here is the full Xorg.0.log file (look at Line #223 in this PasteBin).
I really hope someone could help me. By the way: could I gain something by manually downloading AND compiling the latest driver version from OpenChrome Developers, as I've read somewhere...?
Comment: Sorry, can't post my full my current "/var/log/Xorg.0.log" file, as it has over 50.000 characters... :/
Comment: For the moment, I can use my Netbook by moving the "Task Bar" to the top of the Screen, but this is just cosmetic palliative. "Full Screen" Applications are gonna be a hassle, manually resizing Windows to match physical screen edges.
Comment: I can add that, if I switch to the Text Console (CTRL-ALL-F1 to F6), the Console gets the Screen size right.
Comment: Another problem I've just run into: If I leave Netbook idle for a while, and Screen enters Power Saving Mode, Networking DIES, both Wi-Fi AND Ethernet.

have to issue a "sudo service network-manager restart" every time this happens in order to go back to normal.
Answer: I handle virtually all the OpenChrome graphics stack development, and I can say that I have got OpenChrome DDX running on HP 2133 mini-note (Xubuntu 18.04).
I did observe initial installation issues myself when I performed a fresh install recently due to two fairly new (a little over a year old) SSDs suddenly dying in a span of a week (ADATA Ultimate SU800 128 GB and 256 GB models), but I was able to install by disabling ACPI, although after installing Ubuntu, one really needs to have ACPI running (Warning: If you disable ACPI when installing Ubuntu, it will pass that setting to the installed Ubuntu installation. It is important to remove the setting that disables ACPI for standby to work properly.)
If you wanted to, you could file a bug report with launchpad.net or bugs.freedesktop.org.

Update:
I researched the matter further and it appears that some models shipped with a 1024x600 screen resolution panel.
The model I have comes with a 1280x768 panel that has EDID support.
You should open a bug case with launchpad.net or bugs.freedesktop.org.
Answer: The Lubuntu 17.10 WLAN not working was due to OpenChrome DDX shipping with Version 0.5.
Unfortunately, I broke VN896 chipset FP / PCIe interface in that version, so the only realistic way to fix it is to compile upstream DDX.
Version 0.6 fixed this bug since someone brought it to my attention.
Sorry for the mistake.
Kevin Brace
Brace Computer Laboratory blog
Comment: I take then, I no longer need to file a Bug Report myself?

Either, compile it from Sources myself, or just sit and wait for an updated Ubuntu Driver Package to become available...?
Comment: Guess what...? Finally had spare time to compile & install OpenChrome DDX Driver from GIT Sources, and... **Same problem persists...!**

@kevin-brace - Is there some place in the Source Code I may hack, in order to force the Driver to come up with a Resolution of 1024x600 instead of 1024x768...?
Comment: A quick look at the Sources, shows many lines with "1024x768", but none with "1024x600". Really, I wouldn't know what to modify by myself.


Viewing cumulative electricity usage

Question: The TED 5000C monitors real-time electricity usage. This, however, isn't so useful if plugged into, say, a fridge, where, presumably, the bulk of the electricity usage is going to come from when the compressor is on.
As such it seems like it'd be more useful to monitor the cumulative electricity usage. ie. from the moment you plug it in to the moment you unplug it or something.
Is there such a device?
Comment: I would bet that the TED does have a cumulative usage display mode. But do you really need that device or would the less costly although more limited _Kill a Watt_ meter work for you.
Answer: Most of the multitude of kill-a-watt type plug-in energy monitors will give cumulative kWh since the monitor was powered-on.
The device you link to looks like a whole-household energy monitor. There is a current-sense clamp for each phase of electricity supply into the building. I've used two different models of  these types of device and they both gave cumulative use (though obviously you can't directly track usage by individual appliances). They typically give a history of usage by day for the last week, usage by week for several weeks and usage by month for several months.

The Gateway is the heart of the TED 5000 series. It stores 60 minutes of Second-data, 2 days of Minute-data, 90 days of Hourly-data, 24 months of Daily-data, and 10 years of Monthly-data and provides the communications interface to your computer. Your real-time and historical data can be viewed on your computer by the Gateway's Ethernet connection and its embedded Footprints Firmware

Viewing cumulative electricity usage


Different Image Slider

Question: I know there are lot of sliders out there that i can download and use,but i cant find one that i need.I need simple slider that will move back and forward but it needs to display 6 images per slider in formation 3*2 :
3*2 slider
This is my html code:

So is out there any slider like this one ?
If tags are wrong please change them,Ty and sorry for my bad English.
Answer: Use slick js
Then you just need to use the grid mode.

Different Image Slider


out-of-core/external-memory combinatorics in python

Question: I am iterating the search space of valid Python3 ASTs. With max recursion depth = 3, my laptop runs out of memory. My implementation makes heavy use of generators, specifically 'yield' and itertools.product().
Ideally, I'd replace product() and the max recursion depth with some sort of iterative deepening, but first things first:
Are there any libraries or useful SO posts for out-of-core/external-memory combinatorics?
If not... I am considering the feasibility of using either dask or joblib's delayed()... or perhaps wendelin-core's ZBigArray, though I don't like the looks of its interface:
root = dbopen('test.fs')
root['A'] = A = ZBigArray((10,), np.int)
transaction.commit()

Based on this example, I think that my solution would involve an annotation/wrapper function that eagerly converts the generators to ZBigArrays, replacing root['A'] with something like root[get_key(function_name, *function_args)] It's not pretty, since my generators are not entirely pure--the output is shuffled. In my current version, this shouldn't be a big deal, but the previous and next versions involve using various NNs and RL rather mere shuffling.
Comment: Is this an open-source project (with say a github/gitlab repo)? As someone who has spent a lot of time poking around Python's AST module and parsing logic, this project has my interest
Comment: I have literally >100 projects that need to be released. Thanks for the push I needed:
[link](https://github.com/InnovAnon-Inc/ProgramSynthesis)
Answer: First things first- the reason you're getting the out of memory error is because itertools.product() caches intermediate values. It has no idea if the function that gave you your generator is idempotent, and even if it did, it couldn't be able to infer how to call it again given just the generator. This means itertools.product must cache values of each iterable its passed.
The solution here is to bite the small performance bullet and either write explicit for loops, or write your own cartesian product function, which takes functions that would produce each generator. For instance:
def product(*funcs, repeat=None):
    if not funcs:
        yield ()
        return

    if repeat is not None:
        funcs *= repeat

    func, *rest = funcs

    for val in func():
        for res in product(*rest):
            yield (val, ) + res

from functools import partial
values = product(partial(gen1, arg1, arg2), partial(gen2, arg1))

The bonus from rolling your own here is that you can also change how it goes about traversing the A by B by C ... dimensional search space, so that you could do maybe a breadth-first search instead of an iteratively deepening DFS. Or, maybe pick some random space-filling curve, such as the Hilbert Curve which would iterate all indices/depths of each dimension in your product() in a local-centric fashion.
Apart from that, I have one more thing to point out- you can also implement BFS lazily (using generators) to avoid building a queue that could bloat memory usage as well. See this SO answer, copied below for convenience:
def breadth_first(self):
    yield self
    for c in self.breadth_first():
        if not c.children:
            return  # stop the recursion as soon as we hit a leaf
        yield from c.children

Overall, you will take a performance hit from using semi-coroutines, with zero caching, all in python-land (in comparison to the baked in and heavily optimized C of CPython). However, it should still be doable- algorithmic optimizations (avoiding generating semantically nonsensical ASTs, prioritizing ASTs that suit your goal, etc.) will have a larger impact than the constant-factor performance hit.
Comment: I was falsely assuming that product's "actual implementation does not build up intermediate results in memory," but replacing it with your implementation seems to have fixed it. Good thing, too, because my attempts at implementing an @out_of_core decorator with e.g., dask, wendelin, joblib, weren't panning out as I expected. I'm now trying to wrap my head around the idea of using a space-filling curve for this. I hypothesize that somehow including "locality of data points" should improve NN performance.


zip directory using java

Question: I am trying to create a java program that will take in a directory path and then zip its contents. What is the best way of achieving this? Are there any packages which have this functionality already implemented?
Comment: Also a nice option is this little open source library: http://www.fuin.org/utils4j/examples/zipdir.html
Answer: The package java.util.zip is available in the runtime.
Answer: In case the interface of java.util.zip is too complicated, you might want to have a look at http://commons.apache.org/compress/.

zip directory using java


Do datalakes offered from amazon and azure support rosbag files?

Question: I have a lot of camera, radar and lidar data stored with me in a hard-disk in rosbag formats. I would now like to shift this to a cloud service, preferably trying to preserve the rosbag format.
From what I understand in data lakes you can store data in their natural format. Is there a also limit the formats supported by datalakes.
Any help is much appreciated.
Answer: Both Azure Storage as well as AWS S3 are object stores. You can put in files in whatever native format in there. I am not aware of any limit in terms of file formats in either of those.
Answer: Data Lake gives the freedom to store data in natural format. So far there is no limit, in whatever format you can store data in data lake.
Aws Datalake documents
https://aws.amazon.com/lake-formation/
Azure Datalake
https://azure.microsoft.com/en-us/solutions/data-lake/


Edge browser refresh after closing the element - Angular 5

Question: I have two buttons on form
<button *ngIf="!loader" type="submit" class="custom-button blue left">Update</button>
<button (click)="close()" class="custom-button red left">Close</button>

Everything is working fine in Chrome but in Edge after I click on Close button my whole page is refreshed.
It my .ts file I have
export class InventoryDetailsComponent implements OnInit {
  @Input() inventoryDetails: boolean;
  **@Output() inventoryDetailsChange = new EventEmitter<boolean>();**
  @Output() update = new EventEmitter();

  close () {
    this.inventoryDetailsChange.emit(false);
  }

Any error I get in Edge is

Unable to get property 'handleEvent' of undefined or null reference
  polyfills.bundle.js (4262,17)

I can not figure out why is Edge crashing on this event
The problem with this was with bad type on buttons, my both buttons were type='button' and that was confusing for EDGE, I added type='submit' for my submit button and that prevented my browser to crash
Comment: @gregwhitworth You were right!  I solved this bug by adding type to every button, type='submit' and type='button'

Without your help I would not change my focus to html, thank you
Comment: Do you have a working page to repro against. Because the error page and the experience don't add up. The entire page refreshing seems like EdgeHTML is completely crashing and probably has nothing to do with that error as the above error doesn't look like an EdgeHTML crash stack. If you can provide me with a repro at bugs.microsoftedge.com we can get a trace and identify the root issue.
Comment: mind filing a bug with a reduction of the crasher here: bugs.microsoftedge.com so we can get it fixed and other webdevs don't have to work around it?
Comment: I had an issue in my Angular 6 app where pages where refreshing when clicking on the buttons. type='button' has fixed the issues. Thank you.
Answer: Generally the problem is that MS Edge submits the form whenever a button of type "submit" is clicked inside of any form. Which acually is understandable, but doesn't work very well in SPA applications, because it means refreshing a page.
The first possible answer was mentioned in comments and author added it inside of his question: change button type from "submit" to "button".
The second answer is to use event.preventDefault() in button's handler.
So in this case:
<button (click)="close($event)" class="custom-button red left">Close</button>

close (event) {
    event.peventDefault();
    this.inventoryDetailsChange.emit(false);
  }

Changing a button type is not always a good idea. E.g. if you would like your users to be able to submit a form only by using keyboard (clicking enter), you would need to have a submit button inside of your form.


Replace column values according to values of consecutive rows in pandas

Question: I have a dataframe df_in defined as so:
import pandas as pd
dic_in = {'A':['aa','bb','cc','dd','ee','ff','gg','uu','xx','yy','zz'],
       'B':['200','200','200','400','400','500','700','700','900','900','200'],
       'C':['da','cs','fr','fs','se','at','yu','j5','31','ds','sz']}
df_in = pd.DataFrame(dic_in)

I want to investigate column B in such a way that all the rows having the same consecutive value are assigned a new value (according to a specific rule which i am about to describe). I will give an example to be more clear: the first three rows['B'] are equal to 200. Therefore all of them will have assigned the number 1; the fourth and fifth row['B'] are equal to 400 so they will be assigned number 2. The procedure repeats until the end.
The final result (df_out) should look like this:
# BEFORE #                # AFTER #
In[121]:df_in             In[125]df_out
Out[121]:                 Out[125]:
     A    B   C                A  B   C
0   aa  200  da           0   aa  1  da
1   bb  200  cs           1   bb  1  cs
2   cc  200  fr           2   cc  1  fr
3   dd  400  fs           3   dd  2  fs
4   ee  400  se           4   ee  2  se
5   ff  500  at           5   ff  3  at
6   gg  700  yu           6   gg  4  yu
7   uu  700  j5           7   uu  4  j5
8   xx  900  31           8   xx  5  31
9   yy  900  ds           9   yy  5  ds
10  zz  200  sz           10  zz  6  sz

Notice:

The last row['B'] is equal to 200 but the new value assigned to it is 6 and not 1! Therefore there must be no repeated values.
Values must start always from 1 and therefore are in an increasing order.

Can you suggest me a smart way to achieve such result using pandas?
PS: mapping values manually is not helpful since this is a test case, and eventually I will have thousands of rows to map. It should be something automatic.
Answer: You can compare by ne shifted column and then use cumsum:
print (df_in.B.ne(df_in.B.shift()))
0      True
1     False
2     False
3      True
4     False
5      True
6      True
7     False
8      True
9     False
10     True
Name: B, dtype: bool

df_in.B = df_in.B.ne(df_in.B.shift()).cumsum()
#same as !=, but 'ne' is faster
#df_in.B = (df_in.B != df_in.B.shift()).cumsum()
print (df_in)
     A  B   C
0   aa  1  da
1   bb  1  cs
2   cc  1  fr
3   dd  2  fs
4   ee  2  se
5   ff  3  at
6   gg  4  yu
7   uu  4  j5
8   xx  5  31
9   yy  5  ds
10  zz  6  sz

Comment: I think you can substract `1` by `df_in.B.ne(df_in.B.shift()).cumsum().sub(1)`
Comment: That is a very good answer! Thanks!! could you also tell me what I should do if I wanted to start the counting from 0?
Comment: I have a question: let's say I would like to to the same operation with two columns instead of one, can I still use .ne ? if not what other function do you racomend ?
Comment: I think you can use .ne, eq and similar functions.But need same column names and same index.


Insufficient system storage. The server response was: 4.5.3 Too many recipients (AS780090)

Question: Insufficient system storage. The server response was: 4.5.3 Too many recipients (AS780090)
Line 121:        Dim mSmtpClient As New SmtpClient()
Line 122:
Line 123:        mSmtpClient.Send(mMailMessage)

<code>   Public Function SendMail(ByVal emailto As String, ByVal strtitle As String, ByVal strmsg As String) As String
        ' Try

        Dim mMailMessage As New MailMessage()
        Dim from1 As String = "*******@*****.com"
        ' Set the sender address of the mail message
        mMailMessage.From = New MailAddress(from1, strtitle)
        ' Set the recepient address of the mail message
        mMailMessage.To.Add(New MailAddress(emailto, strtitle))
        mMailMessage.Subject = strtitle

        mMailMessage.Subject = strtitle

        'mMailMessage.To.Add(New MailAddress(email).ToString)
        mMailMessage.To.Add(New MailAddress(emailto).ToString)

        ' Set the format of the mail message body as HTML
        mMailMessage.IsBodyHtml = True
        'mMailMessage.Body = strmsg
        mMailMessage.Body = strmsg

        ' Set the priority of the mail message to normal
        mMailMessage.Priority = MailPriority.High
        mMailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("windows-1256")
        mMailMessage.SubjectEncoding = System.Text.Encoding.GetEncoding("windows-1256")

        ' Instantiate a new instance of SmtpClient
        Dim mSmtpClient As New SmtpClient()

        mSmtpClient.Send(mMailMessage)

    End Function</code>

What is solution for this error ??or where is my code wrong ??
I have added the code too ,please review my code !
Answer: There is some limit to how many recipients can be added in one single email. Recipients include:

To
CC
BCC

In gmail its set to 100 for different mail provider its diff value.
If you are sending more than that no of ID in single email then it will give this error


Why thumbnail shows just another pic?

Question:
Download this picture and see it as a thumbnail, like in whatsapp or your phone gallery and you'll find that it shows another picture in the thumbnail.
If you can't see the thumbnail:
You can simply do some changes in color, or do some filters on it using PicsArt and you'll notice the difference.  I've searched the whole internet, but haven't got the answer yet.
Please explain how is this happening.
Note: I know about the trick with PNG files, but this is a JPEG file and the trick works with this too.
I added video a to elaborate.
Comment: Probably this feature got lost when imgur reapplied compression. Some formats embed a separate thumbnail, if they do then nothing stops the thumbnail from being a different picture.
Comment: It doesn't show a different thumbnail for me when downloaded.
Comment: also possibly its same as http://thume.ca/projects/2012/11/14/magic-png-files/
Answer: You can't see it in the image you uploaded because it's a JPEG, but PNG files which have a full alpha channel can do the trick you mentioned. It works with websites or apps where the "thumbnail" image is displayed on a white background and the "full" image is displayed on a black background. In the thumbnail display, white pixels and completely transparent pixels look the same, because of the white background; in the full image, black pixels and completely transparent pixels look the same.
Thus, you can have a white-on-black picture and a black-on-white picture in the same image, and the background hides one of the two images. You can easily see what's going on if you look at the image against a background of some other colour.
Comment: @AdeshTamrakar Transparency is supported in [JPEG 2000 format](https://en.wikipedia.org/wiki/JPEG_2000).
Comment: Actually I read that it is possible with PNG files, but the thing which amused me and brought me here is that, how this trick is applied to JPEG format.

Why thumbnail shows just another pic?