text: Q: How can i plot the variable stepsize ODE solver chooses in matlab? im trying to plot the stepsize for ODE45 and ODE15s against x but I have no clue how to find the values for each step size. any ideas?


text:
Q: basic question about joint probability Are these two joint probabilities always equal: P(a,b) = P(b,a) ? Or does it matter the order a,b vs b,a?

A: If $a$ and $b$ are events, yes, they're equal. But, in general events are denoted with uppercase letters, so I'm assuming they are specific real values. If that's the case, it is an abuse of notation. Normally, it should be $P(A=a,B=b)$, which is equal to $P(B=b,A=a)$. Here, $\{A=a\}$ and $\{B=b\}$ are events, and we can change their ordering because the comma sign basically mean $\cap$.
If you're asking for PDFs and PMFs, they're commonly denoted with lowercase $p$ or $f$, and commonly with a subscript to denote the ordering of RVs. For example, $p_{A,B}(a,b)$, and surely $p_{A,B}(a,b)\neq p_{A,B}(b,a)$.

A: They are the same. Taking the simpler example of discrete random variables $A$ and $B$, $P(a,b)$ is just a short notation for $P(A=a \wedge B=b)$, which is obviously the same as $P(B=b \wedge A=a)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reflexivity of the preference relation Advanced Microeconomic Theory by Jhele and Reny states the axioms of consumer choice: completeness, transitivity, continuity, local-non satiation, strict monotonicity, convexity and strict convexity.
It is clear that the preference relation is also reflexive. I thought I could derive it from completeness, but the book states completeness is the comparison between two distinct consumption plans.
That is,
$$\forall\vec{x},\vec{y}\in X,\text{ }\vec{x}\succsim\vec{y}\vee\vec{y}\succsim\vec{x}.$$
Shouldn't it be stated as
$$\forall\vec{x},\vec{y}\in X,\text{ }\vec{x}\succsim\vec{y}\vee\vec{y}\succsim\vec{x}\vee\vec{x}=\vec{y}?$$
Or is reflexivity implied by some of the axioms? What am I missing?

A: We have $\forall\vec{x},\vec{y}\in X,\text{ }\vec{x}\succsim\vec{y}\vee\vec{y}\succsim\vec{x}.$ Take some arbitrary $\vec{z}$. It follows by plugging in $\vec{x} = \vec{y} = \vec{z}$ that $\vec{z} \succsim \vec{z} \lor \vec{z} \succsim \vec{z}$, which is equivalent to saying $\vec{z} \succsim \vec{z}$. So we have proved $\forall \vec{z} (\vec{z} \succsim \vec{z})$, which is the definition of reflexivity.


text:
Q: handle zooming in lightweight chart i want when my chart is created, chart automaticly zoom to 20 or 10 last candles.

its default zoom when chart creating.

this picture describes what i want.
is there a solution for this question?
thanks.

A: You can achieve that in several different ways:

*

*you can specify different default bar spacing value

*you can use setVisibleLogicalRange method to change visible range

*you can use setVisibleRange method to change visible range


text:
Q: Подскажите, как можно оптимизировать загрузку сайта? Я сделал сайт, залил на демо-хостинг, вот его адрес:
win2020.000webhostapp.com
В чем же его проблема? Дело в том, что когда сайт загружается, лоадер очень тормозит. Также при появлении основного контента происходят пролагивания. Подскажите, как можно оптимизировать код?
P. S  Ещё одна проблема: после загрузки сайта, замечаю что браузер занимает намного больше оперативной памяти(!400 мб!), чем обычно(50-100мб)

A: Может-быть дело не в сайте, а в каких-то плагинах/браузере который вы используете?
Потыкал сейчас с компа, всё плавно и ест страничка не больше остальных в Windows Chrome

A: Может и в сайте есть проблемы, но не только. Хостинг который вы используйте бесплатный и было ожидаемо что владельцы хостинга будут ограничивать скорость. Я когда-то тоже использовал этот хостинг и с ним всегда проблемы были - низкая скорость, частые вылеты, иногда вообще остановка.


text:
Q: Referencing cookies set in VB.NET with javascript In the beginning, I set a cookie value like this:
Response.Cookies("UserInfo")("UserName") = "Bob"

And it was good.
In the end, I need to read that cookie in javascript. But I have no idea how to do that. The documentation for javascript and cookies (especially those set like I have above) is poor at best. Most cookie-reading functions out there seem to only accept 1 argument (cookie name). But as we clearly see here, I have to pass two arguments to get the value for "Bob".
Any help is greatly appreciated!
Thanks,
Jason

A: alert(document.cookie); will show you everything available to JavaScript.
Inserting Bob from the VB side gives something like UserInfo=Username=Bob.
Let's add something else, like Bob's favorite color:
Response.Cookies("UserInfo")("FavoriteColor") = "Chartreuse"

Now the cookie is UserInfo=Username=Bob&FavoriteColor=Chartreuse
One way to get at the cookie values is to take the whole collection and split it on the semi-colon:
var cookieArray = document.cookie.split(";")

In your case, you'll also need to split UserInfo cookie using the ampersand, and then you'll have access to each of your UserInfo key/value pairs.
There are plenty of examples here on StackOverflow about handling cookies in Javascript; here's one that I've found useful


text:
Q: How is the value object constructed in case key is not present while using [] operator for an unordered_map? In an unordered_map, when we use the [] operator to get the value for a key, then if the key is not present, it performs an insertion. I want to understand how it is implemented.
std::unordered_map<int, int> x;
x[1] = 10;

In the above statement, how is the rvalue 10 accessed and used to perform an insertion ?

A: Very straightforward.
Operator [] for std::map and std::unordered_map looks for an element with a given key. If the element is present, it returns the reference to the second member of it's pair. If it is not present, it creates a new pair, with a key (first) equal to given key and value-initialized second, inserts this element and returns reference to the second.
Then operator= works normally.


text:
Q: How to indicate a search directory different than the current one in grep How do I run a grep on the "c:\Test" directory from "c:\Users\myName?
I tried with grep c:\Test text -r but it doesn't work.
Thank you

A: You need to include the string that you would like to grep in your command then the file, the syntax for grep is grep <string> <file path>
lets say I'm in the home directory that contains a sub-directory called test with a couple text files inside it:
file1.txt: hello world
file2.txt: the quick brown fox had entered the world

etc...

if I was grepping the word "world" from the home directory I would type this
grep world test/*

the "*" character just means search all files.


text:
Q: 'DefaultAppPool' is being automatically disabled in IIS I turned on IIS on my PC with default configuration but when I tried to access "localhost" in my browser it returned 'HTTP Error 503. The service is unavailable'.
I found that the DefaultAppPool under Application Pools automatically stops when it receives a request. The corresponding error under Win logs was 'Application pool DefaultAppPool is being automatically disabled due to a series of failures in the process(es) serving that application pool'.
I found a solution to this issue. However, I don't know how to use Process Monitor (which has replaced Sysinternals Regmon) to tell for which registry keys I need to provide access rights to NT AUTHORITY\NETWORK SERVICE.
Could you please tell me how to use Process Monitor to identify the concerned registry keys?


text:
Q: How can I do an if conditional for a failure of a bash command? I'd like to have a very simple condition that will only execute if the command fails.
In this example it's a conditional based on the SUCCESS of the command.
if command ; then
    echo "Command succeeded"
fi

I'd like the opposite - how can I do this? Is there a elagant way besides doing a comparison on $?
I do not want to use the || or operator - it does semantically convey (in my opinion) the desired functionality. In the case of command || echo "command failed".

A: An alternative to @StephenKitt's correct answer: use the : "no-op" command in the "then" block and the else block:
if command; then :; else
    echo "command failed"
fi

Full disclosure: I would not use this method myself.

A: Negate the command's exit status:
if ! command ; then
    echo "Command failed"
fi


text:
Q: docker - Error: Cannot find module 'winston' Background
I am using EC2 instance to create docker container.
Problem
When I run docker-compose up -d --build, all containers are up successfully.
But when I run docker logs <container id> for test-web container, error shows.
Error: Cannot find module 'winston'

What I've done
I've already tried same command on local environment but it runs successfully, so I wonder it's a docker problem.
I also tried to sh to the images, but the winston module exists in node_modules.
Dockerfile
FROM node:lts-alpine

RUN npm install --global sequelize-cli nodemon

WORKDIR /server

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3030

CMD ["npm", "run", "dev"]

docker-compose.yml
version: '2.1'

services:
  test-db:
    image: mysql:5.7
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=true
      - MYSQL_USER=admin
      - MYSQL_PASSWORD=12345
      - MYSQL_DATABASE=test
    volumes:
      - ./db-data:/var/lib/mysql
    ports:
      - 3306:3306
  test-web:
    environment:
      - NODE_ENV=local
      #- DEBUG=*
      - PORT=3030
    build: .
    command: >
      ./wait-for-db-redis.sh test-db npm run dev
    volumes:
      - ./:/server
    ports:
      - "3030:3030"
    depends_on:
      - test-db

.dockerignore
node_modules
npm-debug.log

package.json
{
  "name": "docker-server",
  "description": "",
  "version": "0.0.0",
  "homepage": "",
  "private": true,
  "main": "src",
  "keywords": [
    "feathers"
  ],
  "author": {
    "name": "hello",
    "email": "hello@example.com"
  },
  "contributors": [],
  "bugs": {},
  "directories": {
    "lib": "src",
    "test": "test/",
    "config": "config/"
  },
  "engines": {
    "node": "^13.0.0",
    "npm": ">= 3.0.0"
  },
  "scripts": {
    "test": "npm run lint && npm run mocha",
    "lint": "eslint src/. test/. --config .eslintrc.json --fix",
    "dev": "nodemon --legacy-watch src/",
    "start": "node src/",
  },
  "standard": {
    "env": [
      "mocha"
    ],
    "ignore": []
  },
  "dependencies": {
    "@feathersjs/authentication": "^4.5.11",
    "@feathersjs/authentication-local": "^4.5.11",
    "@feathersjs/authentication-oauth": "^4.5.11",
    "@feathersjs/configuration": "^4.5.11",
    "@feathersjs/errors": "^4.5.11",
    "@feathersjs/express": "^4.5.11",
    "@feathersjs/feathers": "^4.5.11",
    "@feathersjs/socketio": "^4.5.11",
    "@feathersjs/transport-commons": "^4.5.11",
    "aws-sdk": "^2.868.0",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "express-winston": "^4.1.0",
    "feathers-hooks-common": "^5.0.5",
    "feathers-logger": "^0.3.2",
    "feathers-permissions": "^2.1.4",
    "feathers-sequelize": "^6.2.0",
    "helmet": "^4.4.1",
    "sequelize": "^6.5.1",
    "serve-favicon": "^2.5.0",
    "uuid": "^3.4.0",
    "winston": "^3.3.3",
    "winston-dynamodb": "^0.3.1"
  },
  "devDependencies": {
    "axios": "^0.21.1",
    "eslint": "^7.22.0",
    "mocha": "^8.3.2",
    "nodemon": "^2.0.7"
  }
}


text:
Q: SELECT something JOIN ON something IN columns of multiple tables I'm trying to integrate a bunch of SELECTs all into one.
I have multiple tables that look similar to the following:
Table: A1
+---+----+----+----+----+
|id | I1 | I2 | I3 | I4 |
+---+----+----+----+----+
| 1 |  5 |  6 |  1 |  3 |
+---+----+----+----+----+

Table: A2
+---+----+----+----+
|id | I1 | I2 | I3 |
+---+----+----+----+
| 1 |  3 | 10 |  5 |
+---+----+----+----+

And 1 table that looks like this:
Table: Standards
+---+---------+
|id |   Name  |
+---+---------+
| 1 | 'one'   |
| 2 | 'two'   |
| 3 | 'three' |
| 4 | 'four'  |
| 5 | 'five'  |
| 6 | 'six'   |
| 7 | 'seven' |
| 8 | 'eight' |
| 9 | 'nine'  |
|10 | 'ten'   |
+---+---------+

PHP Code
<?php
    while(/*"A" tables*/){
        $noi = // number of columns in this A table
        $id = // id of this A table
        $columns = "";
        for ($i=1; $i<=$noi; $i++){
            $columns = $columns . "A" . $id . ".I" . $i . ", ";
        }
        $columns = rtrim($columns, ", ");

        $sql = "SELECT s.* FROM A" . $id . "
            INNER JOIN Standards AS s
            ON s.id IN (" . $columns . ")
            WHERE A" . $id . ".id=1
            ORDER BY s.id ASC";

        $result = mysql_query($sql);
    }
?>

I'd like to combine all of these SELECTS into 1.  I was thinking I could run a for loop to generate all the names of the tables, but I wasn't sure exactly how to join them with the other JOIN ON ... IN (...) that's in there.
The results I want to generate are:
+---+---------+
|id |   Name  |
+---+---------+
| 1 | 'one'   |
| 3 | 'three' |
| 5 | 'five'  |
| 6 | 'six'   |
|10 | 'ten'   |
+---+---------+

A: Take a look at this solution, it should give you a foundation of how to do this:
select-mysql-rows-but-rows-into-columns-and-column-into-rows
In short, you might want to try to select the values from each row's columns as rows from the 2 tables and UNION those datasets, then JOIN them onto the lookup table. The result should be what you described. (I am assuming that all of the I1, I2, I3, etc. columns represent IDs in your lookup table)


text:
Q: AMD 700, 800 series chipset. I'm lost I've been an Intel / NVidia user ever since I started using computers.
Intel really gone up with the prices, and they won't get cheaper.
So I decided to get an AMD.
But WHICH one?
I mean.. not shopping question but.. what are the differences?
Like: 880GMA comes only with a single PCI ex and it looks like a chinese replica (no offense).
While 890FX comes with 5PCI-ex for QuadCrossfire.
Also.. what's the deal with 7xx series? I mean.. its the same price. Yet its older? Or why is it 7xx?
Isn't there a single chipset between? Not chinese YET it's durable/fine for long-term usage?
What it should know (desktop stuff):

*

*NVidia GPU (Zalman AMP2 GTX 260^2
(one card))

*Phenom 1090T cpu

*A somewhat good audio.

Any ideas which is the chipset I'm searching for?
If this sounds too much of a shopping question, feel free to edit. I just want some clarification on these chipsets.

A: There is some info in these articles:
Intel vs AMD Processor Comparison 2010
AMD Versus INTEL Chips Comparison
PassMark Intel vs AMD CPU Benchmarks - High End
Comparison of AMD chipsets
The latest link can show that Intel prices may be justified.
Here is a somewhat too general comparison from the first link:

A: Okay. In the end the picture became clear.
Check whether you need more than one PCI EX (890fx), or an integrated card (880).
If yo are fine with your own VGA, no crossfire and stuff, then 870 series.
(Forget about the 7xx series. Also, don't try to find a premium/platinum MB, there IS NO SUCH THING. It's a budget setup .. that's all. !)
(But the end I ended up buying an Intel i7 950 + Gigabyte X58A-UD3R :} I'm very happy with it.. best decision in this situation. Just as @moab and @harrymc said, worth EVERY single penny. !!!)

A: Only difference I could read is 770 more SATA 3gig (2 / II), ACHI ver1.1 and the 870 counterpart is SATA 6gig (3 / III), ACHI ver1.2 .
AMD Chipsets for Desktop PCs (helps a little)
Shiki, any reason exact why "I/anyone" should forget about the 700 series? When you say budget and say you've purchased a (@current$$$) a $250+ mobo, along with a $275+ cpu (that aren't AMD ;P)...umm, in my opinion that's not budget. X

AMD 8 Series Chipset Features Comparison
Can anyone link a Q&A here, regarding AMD/ATI on-board video "integrated" and nVidia graphics card. Would it be better to get a discrete mobo?


text:
Q: jquery event bubbling Can someone explain to me why
var divdbl = $("div:first");
var i = 0;

divdbl.change(function(){
    alert('change');
}).click();

divdbl.click(function(){
    i++;
    alert('click '+i);
}).change();

behaves like they are calling themselves, even if I do it like this
divdbl.click(function(){
    i++;
    alert('click '+i);
}).change();

divdbl.change(function(){
    alert('change');
}).click();

its as if they are calling themselves instead of the other.
EDIT
var divdbl = $("div:first");
var i = 0;

divdbl.change(function(){
    alert('change');
});

divdbl.click(function(){
    i++;
    alert('click '+i);
}).change().click();

i just realized that what i wanted to accomplish was to force them to run once on load
Would the above code make sense?

A: Well, first of all, there's an issue because you are calling triggering change() handler before it is defined. What are you trying to accomplish? Calling .change() and .click() runs the functions for those events.
EDIT:
Based on your recent update to your question: Yes, that will work as intended. Both .click and .change will be invoked upon load.


text:
Q: Norm of the Linear (Integral) Operator on $C[0,1]$ There may be some similar questions being asked but I didn't see anything that was quite what I was looking for so I'll ask the question here.
Let $X = (C[0,1],||.||_{\max})$ and $T:X \to X = \int^{t}_{0}x(\tau)d\tau$.
The norm is defined in the following way: for $x(t) \in C[0,1]$, $||x(t)||_{max}= \textrm{max}\{|x(t)|:t \in [0,1]\}$.
I want to show that $T$ is a bounded linear operator and find $||T||= \textrm{sup}\left\{\frac{||T(x(t))||}{||x(t)||}:x(t) \in C[0,1], x(t) \neq 0\right\}$.
Showing that $T$ is a bounded linear operator is simple but I'm not sure about finding the norm of $T$. By the Extreme Value Theorem, we know that a maximum exists for $x(t)$ and $T(x(t))$ on $[0,1]$. But the supremum of the quotient of all such values may be infinite. How do we show this is not the case?

A: When we use the bound
$$\tag{*}\int_0^t|x(\tau)|\mathrm{d}\tau\leqslant \lVert x\rVert_\infty,$$
there is no loss if and only if $x$ is constant so the norm is greater than $1$.
Inequality (*) for general $x$ shows that the norm is actually $1$.


text:
Q: How to convert a string containing newline characters to multiline yaml I have a string similar to the following:
test_string = "This is a multiple line string \n
containing new line characters. \n
Another new line."

I'm trying to use the to_yaml function to convert it to a multi-line yaml string but it automatically escapes the new line characters.
test_string.to_yaml

outputs:
=> "--- ! This is a multiple line string \\ncontaining new line characters.
 \\nAnother new line."

How do you create a string that contains "\n" and parse it into yaml?
EDIT:
As it turns out if you place a space before the "\n" the to_yaml function will escape the new line. The following string solved the problem:
test_string = "This is a multiple line string\n
containing new line characters.\n
Another new line."

A: YAML treats an empty line (two consecutive line breaks) as being equivalent to \n.
from http://yaml.org/spec/history/2001-08-01.html
Had the same problem and finally found out solution:
s.replaceAll("\n", "\n\n");

A: Where is this string coming from? If that was real Ruby code then the string would contain pairs of linefeed characters, not the two characters \n.
Inside double quotes \n is converted to a single linefeed character, so together with the linefeed at the end of the lines you would have two of them after each line. But to_yaml is seeing a backslash (which it escapes with a second backslash) followed by an n which is passed through verbatim.
There isn't a unique way of representing a string in YAML. String#to_yaml (or YAML.dump) generates the single-quoted flow style of string data unless the data contains characters that must be represented with double-quotes. Newlines are represented by a blank line in the YAML data.
This short program demonstrates.
require 'yaml'

puts "aa\nbb\n".to_yaml

output
--- ! 'aa

  bb

'


text:
Q: Add javascript confirmation popup on "Move to Trash" link I want to open javascript error message when some one clicks on "Move to Trash" link in Publish box in wp-admin

A: Put the following in your functions.php:
if (! empty($GLOBALS['pagenow']) && 'post.php' === $GLOBALS['pagenow'])
    add_action('admin_footer', 'trash_click_error');
function trash_click_error() {
    echo <<<JQUERY
<script>
    jQuery(function($) {
        $('#delete-action a').unbind();
        $('#delete-action a').click(function(event) {
            event.preventDefault();
            alert('Error!');
            setTimeout(
                function() {
                    $('#save-action .spinner').hide();
                    $('#publish').removeClass('button-primary-disabled');
                },
                1
            );
        });
    });
</script>
JQUERY;
}


text:
Q: Jenkins GitHub Organization jobs triggered by schedule I've setup an Octopus organization with multiple repositories inside.
One of those repositories has automated tests. I'm trying to setup the Jenkinsfile in that repo to make the job trigger periodically instead of only on SCM change.
I haven't found documentation that shows this is possible. Even the job, after is automatically created shows the BUILD TRIGGER option but of course it can't be saved.
Jenkins Organization Job Configuration Screenshot

A: I found the way of doing this by using the "properties" option. In this example, the job will trigger by changes pushed to GitHub and also on a periodic basis (every 60 minutes):
properties([pipelineTriggers([cron('H/60 * * * *'), [$class: 'GitHubPushTrigger']])])


text:
Q: How to suppress lombok warnings I have an Entity
@Builder
class MyEntity {
   private Set<OtherEntitiy> children = new HashSet<>()
}

And i get a lombok warning.

warning: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.
      Set = new HashSet<>();

The question is: how can i suppress lombok's warning?
Also. I need to initialize children because i want to avoid NullPointerException. Also i can't mark this filed as final because it is not final really. I cant mark filed @Builder.Default because i wanna create this entity not only with builder and i wanna to save default value for other constructors.

A:
Use @Builder.Defaultto add default behavior for your Builder

@Builder
class MyEntity {
   @Builder.Default
   private Set<String> children = new HashSet<>();
}

You use it on the field that has a default value defined an Lombok will then pick up the value during object creation
@Builder.Default functionality was added in lombok v1.16.16.
So if you're using lower version of Lombok  you will not be able to use it.


text:
Q: How to subscribe to execution of a task using RxJava and Android I am just dipping my toes into RxJava so please be gentle :) I was ok with AsyncTasks up to today but it gets more and more complicated and I think I have finally stumbled upon a requirement that I am actually struggling to fulfil with simple AsyncTasks. This is my use case:
1) I have a method (lets call it checkNetwork()) that needs to run once in a session. If it has run previously it returns with cached response. Otherwise it executes a network call and then, depending on the result, executes another one. Both those network tasks are run with OkHttp and are synchronous. The method itself is run from an AsyncTask. For example:
public class MyApis{

  private boolean mCachedResult;
  private boolean mNetworkChecked;

  ....

  public boolean checkNetwork() {
    if (mNetworkChecked) {
      return mCachedResult;
    }
    doFirstCall();
    // check response, set flags and potentially return
    doSecondCall();
    // check response, set flags, i.e.

    mCachedResult = response.blah
    mNetworkChecked = true;
  }

  public boolean isNetworkChecked(){
    return mNetworkChecked;
}

2) I have multiple parts of my code that will run isNetworkChecked() and if not, then call checkNetwork(). There can be situations with poor network conditions that checkNetwork() will be taking its sweet time and isNetworkChecked() will be returning false. This will generate and queue up quite a few of AsyncTasks. Yes those tasks will be resolved very quickly but I'm hitting problems with the default queue size on the Executor.
As far as I understand RxJava can help me with this. What I would like to do is to run checkNetwork() only once, and if it is running already, instead of queueing AsyncTasks, simply subscribe, wait for it to finish and execute my code based on the response (i.e. mCachedResult in my example).

A: you could use fromCallable with replay(1) in RxJava 1.0.15:
Observable<Blah> blahs = Observable.fromCallable(() -> {
    doFirstCall();
    doSecondCall();
    return response.blah;
})
.subscribeOn(Schedulers.io())
.replay(1).autoConnect(0);

blahs.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)


text:
Q: convert ipv4 netmask to cidr format I have the ip and netmask
192.168.1.0 255.255.255.0

I need to convert the netmask into cidr format
192.168.1.0/24

How do I convert ipv4 address and netmask into cidr format?
I am using PHP5.6

A: The complicated way would be to convert the netmask to binary and count the number of leading 1 bits. But since there are only 33 possible values, a simpler way is just an associative array:
$netmask_to_cidr = array(
    '255.255.255.255' => 32,
    '255.255.255.254' => 31,
    '255.255.255.252' => 30,
    ...
    '128.0.0.0' => 1,
    '0.0.0.0' => 0);

A: A bit hold the topic, but may help someone else and you have here the solution:
function mask2cidr($mask)
{
  $long = ip2long($mask);
  $base = ip2long('255.255.255.255');
  return 32-log(($long ^ $base)+1,2);

  /* xor-ing will give you the inverse mask,
      log base 2 of that +1 will return the number
      of bits that are off in the mask and subtracting
      from 32 gets you the cidr notation */
}

PHP ip2long help

A: The following code transfers the mask to binary to convert the binary to CIDR
    public function mask2cdr($mask) {
          $dq = explode(".",$mask);
          for ($i=0; $i<4 ; $i++) {
             $bin[$i]=str_pad(decbin($dq[$i]), 8, "0", STR_PAD_LEFT);
          }
          $bin = implode("",$bin);

          return strlen(rtrim($bin,"0"));
    }

A: I fixed the code from php ip2long help for 0.0.0.0 mask and simplified it a little (no need to always compute $base = ip2long('255.255.255.255');):
function mask2cidr($mask)
{
    if($mask[0]=='0')
        return 0;

    return 32 - log(~ip2long($mask) + 1, 2);
}

@Barmar's answer is good too, as it will always do the job without any surprises on any PC architecture.

A: function convert($ip,$mask){
  return $ip."/".strlen(str_replace("0","",decbin(ip2long($mask))))
}


text:
Q: Numexpr not found in pandas I install numexpr package via pip on my Windows 7 machine:
pip list | grep numexpr
numexpr (2.4.6)

but when I open ipython and trying to use df.query it shows an error:
ImportError: 'numexpr' not found. Cannot use engine='numexpr' for query/eval if 'numexpr' is not installed

Than I checked whether it installed or not with pd.show_versions:
In [97]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.4.3.final.0
python-bits: 32
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 37 Stepping 5, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None

pandas: 0.17.1
nose: None
pip: 7.1.2
setuptools: 18.5
Cython: None
numpy: 1.10.1
scipy: 0.16.1
statsmodels: 0.6.1
IPython: 4.0.0
sphinx: None
patsy: 0.4.1
dateutil: 2.4.2
pytz: 2015.7
blosc: None
bottleneck: 1.0.0
tables: None
numexpr: None
matplotlib: 1.5.0
openpyxl: 2.3.1
xlrd: 0.9.4
xlwt: 1.0.0
xlsxwriter: None
lxml: 3.5.0
bs4: 4.4.1
html5lib: 1.0b8
httplib2: None
apiclient: None
sqlalchemy: None
pymysql: None
psycopg2: None
Jinja2: 2.8

From the docs:

numexpr: for accelerating certain numerical operations. numexpr uses multiple cores as well as smart chunking and caching to achieve large speedups. If installed, must be Version 2.1 or higher.

A: Regarding your last comment about compatibility of numpy 1.10.1 and numexpr: I am not sure what numexpr version I used, but used it yesterday at home with numpy 1.10.1 under python 3.4 and it worked.
I am not an expert in using pip so maybe my hint is wrong but when I used pip to upgrade numpy under Ubuntu lately it updated only numpy for python 2.7 which is installed in parallel on my machine.
As I use python 3.4 for coding I had to install pip3 to get it also upgraded for python3. Try if the installation works when using pip3 install numexpr.

A: Since the 'numexpr' engine can not be found use the 'python' engine instead.
Open the eval.py file in pandas package and replace the
def eval(expr, parser='pandas', engine='numexpr'

with
def eval(expr, parser='pandas', engine='python'


text:
Q: JPA EclipseLink oneToMany Derived Ids Fail Hello I'm trying to make an example of persistence of a OneToMany relationship in which I get the following error:
Exception Description: Invalid composite primary key specification. The names of the primary key fields or properties in the primary key class [entitys.OrderItemPK] and those of the entity bean class [class entitys.OrderItem] must correspond and their types must be the same. Also, ensure that you have specified ID elements for the corresponding attributes in XML and/or an @Id on the corresponding fields or properties of the entity class.

Note: I'm using EclipseLink and MySQL DB

The entities:
@Entity
public class CustomerOrder implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idOrder")
    private Integer idOrder;

    @Basic(optional = false)
    @Column(name = "orderText")
    private String orderText;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customerOrder")
    private Collection<OrderItem> orderItemCollection;

    public CustomerOrder() {
    }
}

@Entity
@IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected OrderItemPK orderItemPK;

    @Basic(optional = false)
    @Column(name = "itemDesc")
    private String itemDesc;

@Id
@ManyToOne(optional = false)
@JoinColumns({
    @JoinColumn(name="idOrder", referencedColumnName="idOrder"),
    @JoinColumn(name="ItemNumber", referencedColumnName="ItemNumber")
})
//@JoinColumn(name = "idOrder", referencedColumnName = "idOrder", insertable = false, updatable = false)
private CustomerOrder customerOrder;
    private CustomerOrder customerOrder;

    public OrderItem() {
        this.orderItemPK = new OrderItemPK();
   }
}

@Embeddable
public class OrderItemPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "idOrder")
    private int idOrder;

    @Basic(optional = false)
    @Column(name = "itemNumber")
    private int itemNumber;

    public OrderItemPK() {
    }
}

The test Source:
public static void main(String[] args) {
    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();

    // Fill the items fileds
    OrderItem item = new OrderItem();
    item.setItemDesc("Item Text");

    // Fill the orders fields
    CustomerOrder order = new CustomerOrder();
    order.setOrderText("Order text");

    // Fill the relationship fields
    order.getOrderItemCollection().add(item);
    item.setCustomerOrder(order);

    em.persist(order);
    em.getTransaction().commit();
}

I have no idea what I'm doing wrong, any suggestions are welcome.

A: Well i managed to solve the problem by removing idClass annotation and adding the @MapId
heres the final code:
@Entity
@Table(name = "Orders")
public class CustomerOrder implements Serializable {
  private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "idOrder")
  private Integer idOrder;
  @Basic(optional = false)
  @Column(name = "orderText")
  private String orderText;

 @OneToMany(mappedBy = "customerOrder", cascade = CascadeType.ALL)
 private Collection<OrderItem> orderItemCollection;

 public CustomerOrder() {
 }

@Entity
@Table(name = "OrdersItems")
public class OrderItem implements Serializable {

  private static final long serialVersionUID = 1L;
  @EmbeddedId
  protected OrderItemPK orderItemPK;
  @Basic(optional = false)

  @Column(name = "itemDesc")
  private String itemDesc;

  @MapsId("idOrder")
  @ManyToOne(optional = false)
  @JoinColumn(name = "idOrder", referencedColumnName = "idOrder", nullable = false)
  private CustomerOrder customerOrder;

  public OrderItem() {
    this.orderItemPK = new OrderItemPK();
  }

@Embeddable
public class OrderItemPK implements Serializable {
  @Basic(optional = false)
  @Column(name = "idOrder")
  private int idOrder;
  @Basic(optional = false)
  @Column(name = "itemNumber")
  private int itemNumber;

  public OrderItemPK() {
  }

public static void main(String[] args) {

    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();

    // Fill the order item
    OrderItem item = new OrderItem();
    item.getOrderItemPK().setItemNumber(1);
    item.setItemDesc("Product Name");

    // Fill the order
    CustomerOrder order = new CustomerOrder();
    order.setOrderText("Testing");

    // Create relationship
    order.getOrderItemCollection().add(item);
    item.setCustomerOrder(order);

    // Persist
    em.persist(order);
    em.getTransaction().commit();
}

But i can't get it work with IdClass, here's the source
@Embeddable
public class OrderItemPK implements Serializable {

  @Basic(optional = false)
  @Column(name = "idOrder")
  private Integer idOrder;

  @Basic(optional = false)
  @Column(name = "ItemNumber")
  private Integer itemNumber;

  public OrderItemPK() {
  }

@Entity
@IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
   private static final long serialVersionUID = 1L;

   @Id
   @Column(name = "itemNumber")
   private Integer itemNumber;

   @Basic(optional = false)
   @Column(name = "itemDesc")
   private String itemDesc;

   @MapsId("idOrder")
   @ManyToOne(optional = false)
   @JoinColumn(name = "idOrder", referencedColumnName = "idOrder", nullable = false)
   private CustomerOrder customerOrder;

   public OrderItem() {
   }

  @Entity
  public class CustomerOrder implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idOrder")
    private Integer idOrder;

    @Basic(optional = false)
    @Column(name = "OrderText")
    private String orderText;

    @OneToMany(mappedBy = "customerOrder", cascade = CascadeType.ALL)
    private Collection<OrderItem> orderItemCollection;

    public CustomerOrder() {
        this.orderItemCollection = new ArrayList();
    }

A: Use MapsId in OrderItem:
@Entity
public class OrderItem implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected OrderItemPK orderItemPK;

    @Basic(optional = false)
    @Column(name = "itemDesc")
    private String itemDesc;

    @MapsId("idOrder")
    @ManyToOne(optional = false)
    @JoinColumn(name = "idOrder", referencedColumnName = "idOrder")
    private CustomerOrder customerOrder;
}

An alternative is to remove the embedded id and use an ID class:
@Entity
@IdClass(OrderItemPK.class)
public class OrderItem implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "itemNumber")
    private int itemNumber;

    @Basic(optional = false)
    @Column(name = "itemDesc")
    private String itemDesc;

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "idOrder", referencedColumnName = "idOrder")
    private CustomerOrder customerOrder;
}

public class OrderItemPK implements Serializable {
    //name of the relation in the entity, but same type as the CustomerOrder PK.
    int customerOrder;

    int itemNumber;

    public OrderItemPK() {
    }
}


text:
Q: Trouble with PhoneGap demo: "nothing to be done for..." I'm trying to do the PhoneGap demo for IOS at:
http://mobile.tutsplus.com/tutorials/phonegap/phonegap-development/
It says to open a terminal in the folder that has "PhoneGapLibInstaller.pkg". I did that. If I do "ls", I can see the file listed. Then it says to run "make". I'm not a terminal person very much, but it first said "make: * No targets specified and no makefile found.  Stop." I assumed the tutorial left out the file name so I tried "make PhoneGapLibInstaller.pkg". Now I get "make: Nothing to be done for `PhoneGapLibInstaller.pkg'."
What should I be typing?? I wish tutorials would be more clear sometimes :)

A: Have you tried following the install instructions on the PhoneGap Wiki for iOS?
Getting Started with PhoneGap (iOS)


text:
Q: Is `dpkg --contents` unable to handle SIGPIPE? I noticed a weird antipattern in some CI scripts I've taken over, which basically boils down to this code checking whether a particular file is present in a package:
dpkg --contents some.deb > contents.txt
grep --quiet foo contents.txt

I tried the obvious refactor of dpkg --contents some.deb | grep --quiet foo, but I keep getting this error:

dpkg-deb: error: tar subprocess was killed by signal (Broken pipe)

From some more investigation, this is definitely a timing issue. If I use a regex which matches early in the input stream I get the error, but if I use a regex which specifically matches a late line it succeeds.
The most obvious conclusion is that dpkg (or possibly tar) does something wrong with SIGPIPE. Is this a known issue?
Platform:
# lsb_release --all
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.6 LTS
Release:    18.04
Codename:   bionic
# dpkg --version
Debian 'dpkg' package management program version 1.19.0.5 (amd64).
This is free software; see the GNU General Public License version 2 or
later for copying conditions. There is NO warranty.
# tar --version
tar (GNU tar) 1.29
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by John Gilmore and Jay Fenlason.

A: dpkg uses tar to list the package contents. When tar can't process an archive in full, it indicates an error, and that's what dpkg is reporting. Both commands expect that an inability to complete their task is an error, and act accordingly.
You can avoid this by ensuring that grep reads all its input before exiting:
| grep foo > /dev/null

(instead of -q, which exits as soon as it matches).

A: You could also use a command which will soak up the output of dpkg before
passing it all to grep, without generating an error on SIGPIPE. perl is such a command:
dpkg --contents some.deb | perl -0777 -pe1 | grep --quiet foo

The perl options mean:

*

*-0777 slurp the entire input into one "line"

*-p read each "line" from stdin and print it to stdout

*-e1 evaluate the given expression (1) for every input "line".


text:
Q: XML Schema define custom named nodes down to specific level I've got an XML file which consists of a root node with a defined name "IDTree". This node shall contain exactly three levels of descendents with undefined names, because I need to use XPath in an application to beautifully address specific values in this XML file.
Example:
<IDTree>
  <Foofoo id="0x00">
    <Foobar id="0x00">
      <Boofar id="0x00" />
      <Fasfoo id="0x01" />
      <Farfoo id="0x02" />
    </Foobar>
    <Foobas id="0x01">
      <Bas id="0x00" />
      <Bar id="0x01" />
      <Foo id="0x02" />
    </Foobas>
  </Foofoo>
</IDTree>

I need to address these nodes by using XPath like "/IDTree/Foofoo/Foobas/Bar" to convert them into three values like 0x00 0x01 0x01.
The data stored in this XML file is somehow "dynamic". That is it will probably get extended, edited or otherwise altered by adding, moving, deleting nodes with unspecified names within these three levels.
Below the third level however nodes shall have defined names. Every node on the third level below the root node shall have zero or one child node with the name "Description" which in turn shall have subnode with the names "ShortDesc" and "Field". "Field" on the other hand shall have zero to many fields named "Value".
All child nodes of the root node shall have attributes with defined names. All nodes on levels 1 - 3 below the root node with unspecified names must have an 'id' attribute. The nodes with defined names below level 3 all shall have defined attributes depending on their type.
Question is, how do I specify all these requirements and options in a XML Scheme?


text:
Q: How to make sure the function turns what I write into a string Here's the code:
abc = ['abcdefghijklmnopqrstuvwxyz', 'secondstring', 'thirdstring']

def findletter(letter, l1st, idx):

    if letter in l1st[idx]:
        print("found")
    else:
        print("not found")

findletter("i", abc, 0)

This works, however I have a few questions:

*

*Why writing the letter the 'i' without quotation marks gives an error?

*How do I make so it'd take letters without quotation marks?

Thanks.

A: A "letters without quotation marks" would be a variable.
If you set that variable to a string first, it will work without errors.
i = "something"
findletter(i, abc, 0)

Otherwise it's un undeclared variable, which is an error.

A: Writing i without quotations considers it as a variable which i has not been assigned to
For the second, str(abc) would work as str() converts what you have to a string

A: If you write "i" without the quotation marks, it will take it as a variable instead of a string.
If you do not want to hard-code what you to search, try this:
abc = ['abcdefghijklmnopqrstuvwxyz', 'secondstring', 'thirdstring']

def findletter(letter, l1st, idx):

    if letter in l1st[idx]:
        print("found")
    else:
        print("not found")

i = input("Enter the string to be searched: ")
findletter(i, abc, 0)

This will ask you what to search in the shell, every time you run the code and input() function always returns the value as a string.


text:
Q: Is there any way to encrypt User Name in WSO2 Identity Server? I am using WSO2 Identity Server v5.6.0.
I want to encrypt usernames and emails saved in the database.
The documentation says that as a part of Personal Data Protection WSO2 IS is hashing the user credentials:

But, in the tables such as IDN_OAUTH2_ACCESS_TOKEN
IDN_IDENTITY_USER_DATA the UserName column contains data in plain text.
My Question is:
How to encode or encrypt the UserName column to make the personal data more secure?
Or Broadly, How can I have WSO2 encrypt some information before storing it in the database?

A: I am unfamiliar with WSO2 but:
1) Hashing is not the same as encryption. Hashing is (ideally) not reversable, and that's the point. Encryption is a reversable hash where the source (plaintext) can be recovered.
2) The username might be the reference needed by WSO2 to decrypt or cross reference the data given in any hash (or encryption). I hope not, but....
3) The encryption/hashing may well take place when the data is in transit rather than when the data is at rest. If you are looking in your data storage depository and seeing plaintext usernames this may well be simply because in storage on your server (or elsewhere) the data is not covered by the WSO2 encryption/hashing mechanism.
 - Are other fields in your database table hashed?
 - Can you see any [other] non-hashed output to your endpoint browser (ie end user)?

4)

[I want to] make the personal data more secure

How will encrypting usernames help with that? What sort of data theft will that prevent? There are different ways of protecting different data from different threats; exampled by hashing (as outlined in the linked document) being completely different from encryption (as you request you want to achieve).
If you can answer the above that would help a lot. Thank you.

A:
The documentation says that as a part of Personal Data Protection WSO2 IS is hashing the user credentials

The user's password is hashed by default using the default userstore, you may see
http://xacmlinfo.org/2015/06/10/user-password-hashing-with-wso2-identity-server-wso2is/ For other userstore types it all depends on underlaying implementation (e. g. LDAP)
As well it is possible to encrypt an access token, see https://docs.wso2.com/m/mobile.action#page/85392668

How to encode or encrypt the UserName column to make the personal data more secure?
Or Broadly, How can I have WSO2 encrypt some information before storing it in the database?

You can have it easy or hard way.
Easy - using the JDBC userstore you may configure "advanced" properties and define your own SQL commands to update or query data (including encryption of data). https://docs.wso2.com/m/mobile.action#page/87705730
More complex - you may create your own userstore implementation https://docs.wso2.com/m/view-rendered-page.action?abstractPageId=92523884


text:
Q: Hot-Module-Replacement (HMR) suddenly stopped working in vue-cli 3 project in my vue project, created with vue-cli 3 i had hot reload working fine and than suddenly stopped.
in my console, when i save a *.vue file` i see:
[WDS] App updated. Recompiling...
[WDS] App hot update...

but that is it, it stops there, no reload in the browser.
i allready tried to reinstall my entire node modules, my webpack-dev-server,
tried adding
watchOptions: {
      poll: true
}

to my  vue.config.js file but nothing works. my configration file is very simple and straight forward:
module.exports = {
  devServer: {
    port: 8080,
    clientLogLevel: 'info'
  },
  pages: {
    app: {
      entry: 'src/main.js',
      template: 'public/index.html',
      filename: 'index.html'
    }
  },
  css: {
    loaderOptions: {
      sass: {
        data: `
            @import "@/assets/styles/variables.scss";
          `
      }
    }
  }
}

any idea what might cause that?


text:
Q: SHOWPLAN permission denied when including execution plan in Data Explorer If I select the "Include execution plan" checkbox in the Data Explorer, the query fails:

SHOWPLAN permission denied in database 'StackOverflow'.

I see that this has happened before following maintenance. I don't know whether there was any recent maintenance. It's been several days since the data was updated and longer since an update was deployed, if that's related.

A: It is annoying but at least the showplan permission has been fixed somewhat by not using the checkbox on the UI but leveraging the SHOWPLAN_TEXT setting yourself as part of the command batch:
SQL
set showplan_text  on
go
select top 10 *
from posts
inner join votes v on v.postid = posts.id
go

Result
StmtText
--------------------------------------------------------------------
select top 10 *
from posts inner join
votes v on v.postid = posts.id

(1 row(s) returned)

StmtText
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  |--Top(TOP EXPRESSION:((10)))
       |--Nested Loops(Inner Join, OUTER REFERENCES:([v].[PostId], [Expr1003]) OPTIMIZED WITH UNORDERED PREFETCH)
            |--Clustered Index Scan(OBJECT:([StackOverflow].[dbo].[Votes].[UIX_Votes_Id] AS [v]))
            |--Clustered Index Seek(OBJECT:([StackOverflow].[dbo].[Posts].[UIX_Posts_Id]), SEEK:([StackOverflow].[dbo].[Posts].[Id]=[StackOverflow].[dbo].[Votes].[PostId] as [v].[PostId]) ORDERED FORWARD)

(4 row(s) returned)

I tried this same script earlier (when I left the comment) and at that time this failed as well.
So consider this now as a temporary workaround.


text:
Q: PM2: ignore watch folder glob pattern I want pm2 to stop watching folders which have a name like cache or tmp.
I tried a lot of manners in my app.json config file :
{"apps": [{
    "name": "BSTAT",
    "script": "./server/app.js",
    "watch": true,
    "ignore_watch": [
        "HERE IS WHAT I HAVE TRIED ==>",
        "*cache*",
        "*/cache",
        "cache/",
        "*cache/*"
    ],
}]}

and also saw this question who doesn't seem to have an exemple of that case.
The only way that I find to resolve the problem was to put the exact path like server/my-module/cache
I can not bring myself to think this is not possible...that's why I request your help :)

A: you need a regex for this, e.g.:
ignore_watch : ['./**/*tests.js', ]

this pattern will ignore all files with name "tests.js" in all project folders


text:
Q: showing value of enum in jsp using spring mvc I have an enum
public enum Number
 {
 ONE("one"), TWO("two"), THREE("three"), FOUR("four");
 }

i put this enum into model
model.addAttribute("myEnum", Number.values());

Now, in jsp page I want to show a value of one of these enums.
<c:out value="${myEnum.ONE}"/>

but it doesnt seem to work. What am I doindg wrong?

A: myEnum is a list of values returned, you could either create one attribute equal to the value of one enum instance :
model.addAttribute("one", Number.ONE);

<c:out value="${one}"/>

or loop through myEnum :
<c:forEach items="${myEnum}" var="value">
    ${value}
</c:forEach>


text:
Q: Linear Search on Vector I have tests to pass online using my created methods. I have a feeling there is an issue with one of the tests. The final one i cannot pass.
Here is the test-
TEST_CASE ("Linear Search With Self-Organization 3") {
  int searchKey = 191;

  vector<int> searchArray(500);
  for (int i = 0; i < 500; i++) {
    searchArray[i] = i + 1;
  }
  random_shuffle(searchArray.begin(), searchArray.end());

  bool result, result2;
  result = linearSearchSO(searchArray, searchKey);
  int searchKey2 = 243;
  result2 = linearSearchSO(searchArray, searchKey2);

  REQUIRE (result == true);
  REQUIRE (result2 == true);
  REQUIRE (verifySearchArray(searchArray) == true);
  REQUIRE (searchArray[0] == searchKey2);
  REQUIRE (searchArray[1] == searchKey);
  REQUIRE (searchArray.size() == 500);
}

The method in question here is linearSearchSO.
bool linearSearchSO(vector<int> & inputArr, int searchKey) {
   printArray(inputArr);
   for(int i=0; i < inputArr.size(); i++) {
      int temp = inputArr[0];
      if (inputArr[i] == searchKey) {
         inputArr[0] = inputArr[i];
         inputArr[i] = temp;
         printArray(inputArr);
         return true;
      }
   }
   return false;
}

Worth noting that this method has passed all 3 of the other tests required. As you can see in the test, my tutor has called this method twice passing two different values.The idea is that there is a vector of 500 numbers.. In this instance he randomises the numbers. The best way for me to explain what is happening is that if he didn't randomise and the numbers were simply listed 1-500. The method gets called and I begin with the requested number 191, I move this to front of the vector.
Now it reads 191, 2, 3, 4 etc. 190, 1, 192 etc.
So he then calls the method again, and wants 243 to be moved to the front. His test wants the result to be 243, 191, 2, 3, 4. However what my code does is swap 191 to 243's position.
My result now reads 243, 2, 3, 4 etc. 242, 191, 244, 245 etc.
Every other test is simply taking one number and moving it to the front, the test then checks that each number is in the correct position. My question is, is there a way for me to achieve 243, 191, 2, 3.. without messing up every other test I've passed only using this one linearSearch function? or is there a problem with the test, and hes simply made a mistake.
EDIT- The actual question asked for this test.
Question 4
A self-organising search algorithm is one that rearranges items in a collection such that those items that are searched frequently are likely to be found sooner in the search. Modify the learning algorithm for linear search such that every time an item is found in the array, that item is exchanged with the item at the beginning of the array.

A: If I have understood correctly you need something like the following
#include <iostream>
#include <vector>

bool linearSearchSO( std::vector<int> & inputArr, int searchKey )
{
    bool success = false;

    auto it = inputArr.begin();

    while  (  it != inputArr.end() && *it != searchKey ) ++it;

    if ( ( success = it != inputArr.end() ) )
    {
        int value = *it;
        inputArr.erase( it );
        inputArr.insert( inputArr.begin(), value );
    }

    return success;
}

int main()
{
    std::vector<int> inputArr = { 1, 2, 3, 4, 5 };

    for ( const auto &item : inputArr )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    linearSearchSO( inputArr, 3 );

    for ( const auto &item : inputArr )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
}

The program output is
1 2 3 4 5
3 1 2 4 5

Pay attention to that instead of writing manually a loop in the function you could use the standard algorithm std::find.


text:
Q: How many one in a million people exist? So if there are 7,632,819,325 people currently alive (According to google), then how many of those people are "One in a million"?
My math behind it was to divide the number by a million, but I just wanted to double check. I got the number 7,632; as expected- but this felt a little too easy. (Math has never been my strong suit, lol.) Thanks!

A: For a single trait for a human to possess such that the odds of a single person possessing that trait are "one in a million", then the expected number of people globally to possess that trait would be around 7,632 as you state. But, that is just the expected number. Since this would be a binomial distribution, you are likely to come close to that number, but if you wanted a 95% confidence interval, it would be more like you can be 95% confident that between 7,463 and 7,809 people are "one in a million".


text:
Q: How to bring a menu to front of a navigation frame in silverlight? I Have a Silverlight page with a header menu, a navigation frame, and a footer. In my header menu I want to put a drop down menu, but when I open the menu, it goes behind the frame.
Is there a way to put it forward? Canvas.ZIndex makes no difference at all.

A: For me to get this to work, the navigation frame had to be in a grid that was a child of the grid my menu was in.
Like so:

Grid "FullPageGrid"
     Grid
        Menu Stuff
        Grid
           Navigation Frame

Not sure why that works, but it does.

A: You can use this free opensource menu for this purpose:
www.sl4popupmenu.codeplex.com
It brings the content on top by placing in a Popup control.

A: If you can place the drop down menu later in the XAML, it will appear above.
So you want to have this hierarchy:
Grid
    Grid
       Your navigation frame
    Grid
       The menu


text:
Q: How to apply a function to a data.table subset by multiple columns in R? I have a data table with counts for changes for multiple groups. For example:
input <- data.table(from = c("A", "A", "A", "B", "B", "B", "A", "A", "A", "B", "B", "B"),
                 to = c(letters[1:6], letters[1:6]),
                 from_N = c(100, 100, 100, 50, 50, 50, 60, 60 ,60, 80, 80, 80),
                 to_N = c(10, 20, 40, 5, 5, 15, 10, 5, 10, 20, 5, 10),
                 group = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2))

How can I calculate the total for each change across groups? I can do this using a for loop, for example:
out <- list()
for (i in 1:length(unique(input$from))){
  sub <- input[from == unique(input$from)[i]]
  out2 <- list()
  for (j in 1:length(unique(sub$to))){
    sub2 <- sub[to == unique(sub$to)[j]]
    out2[[j]] <- data.table(from = sub2$from[1],
                  to = sub2$to[1],
                  from_N = sum(sub2$from_N),
                  to_N = sum(sub2$to_N))
    print(unique(sub$to)[j])
  }
  out[[i]] <- do.call("rbind", out2)
  print(unique(input$from)[i])
}
output <- do.call("rbind", out)

However, the data table I need to apply this to is very large, and I therefore need to maximise performance. Is there a data.table method? Any help will be greatly appreciated!

A: Perhaps I've overlooked something, but it seems you're just after:
library(data.table)

setDT(input)[, .(from_N = sum(from_N), to_N = sum(to_N)), by = .(from, to)]

Output:
   from to from_N to_N
1:    A  a    160   20
2:    A  b    160   25
3:    A  c    160   50
4:    B  d    130   25
5:    B  e    130   10
6:    B  f    130   25

A: An option with dplyr
library(dplyr)
input %>%
 group_by(from, to) %>%
 summarise_at(vars(ends_with('_N')), sum)

Or in data.table
library(data.table)
setDT(input)[, lapply(.SD, sum),  by = .(from, to), .SDcols = patterns('_N$')]


text:
Q: Used RVM to get latest, ruby -v still out of date Very odd, I had a ruby app working in 1.9.3 for a few weeks, one machine reboot and it fails. I hit ruby -v and am told "1.8.7", well thats the reason its failing. No idea how that happened though...
Tried:
#rvm get stable
#rvm get 1.9.3-head

but still,
#ruby -v
ruby 1.8.7 (2010-08-16 patchlevel 302) [x86_64-linux]

Why is it not getting updated?
#rvm list rubies
rvm rubies

   ruby-1.9.3-head [ x86_64 ]
=* ruby-1.9.3-p194 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

Note: none of the answers/comments have fixed the problem...yet it was down voted? Anyway i cannot even type "rvm" on some of the user accounts!

A: This command will set the the ruby 1.9.3-head as default for whole system.
rvm use 1.9.3-head --default

or use the ruby version you want to set as default instead of 1.9.3-head  in above command
if you want to use it for project only specific , create .rvmrc file and speccify the details as below
go in app directory
echo rvm use ruby-1.9.3-head@projectname --create > .rvmrc

This will create a gemset named projectname and will be used everytime you go to this direcory.
Also have a look at the cheatsheet .It explains rvm usage in simple way.

A: You can type
rvm use 1.9.3 --default

So it make ruby 1.9.3 as default ruby, you can also switch between multiple versions of ruby use
rvm use version

You can create a .rvmrc file in your project folder and write
rvm use 1.9.3

So, everytime you cd to your project folder, the specified ruby version in your .rvmrc file is used. Adding to this create a gemset say project_name and then update the .rvmrc file with
rvm use 1.9.3@project_name

Which will make things more clear ruby version with the proper gems are loaded when you enter the project folder.


text:
Q: Binding Command inside DataTemplate in WPF C# I have a button tag inside my data template. I want to trigger the command once I click on the button. If the button is outside of the data template my button is able to work. I tried few solutions such as :
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right" Click="btnUpdate_Click"
                                    Command="{Binding Path=DataContext.updateProductionLineConfigCommand,
                                RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>

This is my ViewModel:
public UpdateProductionLineConfigCommand updateProductionLineConfigCommand { get; set; }

    public ProductionLineConfigViewModel()
    {
        ProductionLineConfig = new ProductionLineConfig();
        newProductionLineConfigCommand = new NewProductionLineConfigCommand(this);
        updateProductionLineConfigCommand = new UpdateProductionLineConfigCommand(this);
    }

This is my Command class:
 public ProductionLineConfigViewModel VM { get; set; }

    public event EventHandler CanExecuteChanged;

    public UpdateProductionLineConfigCommand(ProductionLineConfigViewModel vm)
    {
        VM = vm;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        VM.updateProductionLineConfig();

    }

Can someone please help me on this. Why i am not able to bind my commands to my button?

A: This is the solution which fixed my problem.
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right"
Click="btnUpdate_Click" Command="{Binding DataContext.updateProductionLineConfigCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:production_line_config_home}}}"/>


text:
Q: OpenLayers SelectFeature control ignores graphicZIndex I am having trouble with SelectFeature control with hover = true and highlightOnly = true.
There are two adjacent polygons on the same layer, one on top of the other. There's also a SelectFeature control that highlights a polygon on hover. Layer has styleMap with 'default' and 'select' intents. Select intent has a higher graphicZIndex. But it's ignored - whenever I hover upper polygon its lower border (the one that's common with the lower polygon) is rendered under the lower polygon.
If you go to http://jsfiddle.net/vLpt6/12/ you'll see two adjacent polygons - hover the upper polygon and its lower border will be rendered under the lower polygon as if graphicZIndex had no effect.
Here's the HTML code:

And javascript code:
var map = new OpenLayers.Map({
    div: 'map',
    allOverlays: true,
    controls: [],
    fractionalZoom: true
});

var layer = new OpenLayers.Layer.Vector('Layer');
map.addLayer(layer);

layer.rendererOptions = { zIndexing: true };
layer.styleMap = new OpenLayers.StyleMap({
    'default': {
        fillColor: '#a9a8a7',
        strokeColor: '#ffffff',
        strokeWidth: 1,
        graphicZIndex: 10
    },
    'select': {
        fillColor: '#a9a8a7',
        strokeColor: '#5d7cc4',
        strokeWidth: 5,
        cursor: 'pointer',
        graphicZIndex: 100
    }
});

var format = new OpenLayers.Format.WKT();
var features = [
    format.read('POLYGON((0 0, 100 0, 100 50, 0 50, 0 0))'),
    format.read('POLYGON((0 0, 0 -50, 100 -50, 100 0, 0 0))')
];
layer.addFeatures(features);

map.zoomToExtent(layer.getDataExtent());

var hoverControl = new OpenLayers.Control.SelectFeature(
    [layer],
    {
        hover: true,
        highlightOnly: true
    }
);
map.addControl(hoverControl);
hoverControl.activate();

What should I correct so that graphicsZIndex would have effect?map

A: This seems to work: Your modified DEMO
All i did was move your options in to the layer's constructor like this:
var layer = new OpenLayers.Layer.Vector('Layer', {
    rendererOptions: { zIndexing: true },
    styleMap: new OpenLayers.StyleMap({
        'default': {
            fillColor: '#a9a8a7',
            strokeColor: '#ffffff',
            strokeWidth: 1,
            graphicZIndex: 10
        },
        'select': {
            fillColor: '#a9a8a7',
            strokeColor: '#5d7cc4',
            strokeWidth: 5,
            cursor: 'pointer',
            graphicZIndex: 100
        }
    })
});


text:
Q: Highcharts - xAxis date I'm trying to set my xAxis to display a month for every bit of data I input..
so 1, 2, 3, 4 will display as Jan on xAxis and 1 in the yAxis. Feb xAxis and 2 yAxis etc.
*For every bit of data, + a certain amount of time to xAxis and plot.
// I'm doing this from a csv file but if I can get it done from manual input first thats fine.
Any ideas or documentation/examples you could point me to?
Thanks

A: Yes, this is doable. See the API for the xAxis.type then look at the demo link for "datetime" with regular intervals. This provides the basic framework. You tell it the start time (pointStart) and what the increments (pointInterval) are going to be for each point.


text:
Q: How to read data from nested JSON structure in protractor Below is my code and I want to extract data under "specs" part like description, status etc. however I'm getting undefined when I capture the data and print it in the console. I have tried
let web = JSON.parse(jsondata);
let TestSuite = web["suite1"]["description"]

and this is providing data in console however, when I use this,
let id = web["suite1"]["specs"]["id"]

its gives undefined. Please help!

{
"suite1": {
    "id": "suite1",
    "description": "Login",
    "fullName": "Login",
    "failedExpectations": [],
    "status": "finished",
    "specs": [
        {
            "id": "spec0",
            "description": "Should able to login into the Distribution management Webpage",
            "fullName": "Login Should able to login into the Distribution management Webpage",
            "failedExpectations": [
                {
                    "matcherName": "",
                    "message": "",
                    "stack": "",
                    "passed": false,
                    "expected": "",
                    "actual": ""
                }
            ],
            "passedExpectations": [],
            "pendingReason": "",
            "started": "2018-09-06T06:57:42.740Z",
            "status": "failed",
            "duration": "7 secs",
            "stopped": "2018-09-06T06:57:49.255Z",
            "browserLogs": []
        }
    ]
} }

A: JSON.parse(JSON.stringify(json)).suite1.specs[0].id

A: specs contains an array of objects. First, you need to get the object from the array and then get a value of the object.
Try this:
let id = web["suite1"]["specs"][0]["id"]

OR
let id = web.suite1.specs[0].id

Hope this will work.

A: When you do ["suite1"]["specs"], you select array. You need an index, which is the 0-th one in this case.
You can check that by typing Object.prototype.toString.call( data["suite1"]["specs"]).
You can try with:
data["suite1"]["specs"][0]["id"]

Or use the object property notation
data["suite1"]["specs"][0].id


text:
Q: xpath not accepting this expression hello everyone i have on question for xpath
/abcd/nsanity/component_details[@component="ucs"]/command_details[<*configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" */>]/collected_data
i want to retrieve the string for above the xpath statement but when i am giving this xpath to  xpath expression for evaulate it is throwing an exception like
Caused by: javax.xml.transform.TransformerException: A location path was expected, but the following token was encountered:  <configScope

A: The bold part in your XPath expression is not a valid predicate expression. I can only guess, what do you want to achieve. If you want only the <command_details/> elements, which have a <configScope/> child element with attributes set to inHierarchical="true", cookie="{COOKIE}" and dn="org-root" then the XPath expression should be:
/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data

Here is an example XML:
<abcd>
  <nsanity>
    <component_details component="ucs">
      <command_details>
        <configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" />
        <collected_data>Yes</collected_data>
      </command_details>
      <command_details>
        <configScope inHierarchical="true" cookie="{COOKIE}" dn="XXX"/>
        <collected_data>No</collected_data>
      </command_details>
    </component_details>
  </nsanity>
</abcd>

The following Java program reads the XML file test.xml and evaluates the XPath expression (and prints the text node of element <collected_data/>.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Test {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document = dbf.newDocumentBuilder().parse("test.xml");

    XPath xpath = XPathFactory.newInstance().newXPath() ;

    NodeList nl = (NodeList) xpath.evaluate("/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data", document, XPathConstants.NODESET);
    for(int i = 0; i < nl.getLength(); i++) {
      Element el = (Element) nl.item(i);
      System.out.println(el.getTextContent());
    }
  }
}


text:
Q: Sorting model instances with Globalize3 The problem seems trivial, but I can't find any reasonable solution. I have list of countries with translations stored in Globalize3 translation tables. How can I fetch the list of countries sorted by name?
Country name isn't stored directly in the model, but in separate table. Is there any reasonable way to sort the result other than manual sql query, or manualy sorting result table after AR query is complete?

A: Country.with_translations(I18n.locale).order('name') for current locale.
Edit:
You can also use fallbacks:
Country.with_translations(I18n.fallbacks[I18n.locale]).order('name')

A: Country.with_translations.order('name')


text:
Q: Python text adventure woes if schoice == 1:
    print "You walk right up to the rat and proceed to BEAT THE SHIT OUT OF IT AHHHHHH. Ahem. Anyway, you look at your blood-covered fists and feel good about yourself. You know that you just leveled up your Unarmed to 11. BOOYA!"
    skills("Unarmed") = 11
else:
    "You proceed to be a little bitch and sneak past the rat. Even though you know that you are being a total coward, you feel good, and you know that you leveled up your sneak to 11. Oh Yeah!"
    skills("Sneak") = 11

First off, I would like to say that I have the raw_input stuff with everything else set up, but I was just wondering if I HAVE to split off from here, and then have to write the same thing a gazillion times, or I could make both of these choices, no matter which is picked, to proceed to a shared new choice?

A: You don't have to split everything every time there is a choice, no.
Consider this:
print('This happens first')
choice = raw_input('Make a choice (1 or 2)')
if choice == 1:
    print('Conditional event no1')
else:
    print('Conditional event no2')
print('This happens after the choice, no matter what happened')

The story can go on from there. You can visualize this as a flowchart resembling this:
                /------ Choice 1 -------\
Starting point /                         \____ Happens in either case
               \                         /
                \------ Choice 2 -------/


text:
Q: How can I input a 0 or empty value on the prompt and don't let the action returned by this value be the same as the one returned by the cancel button? I was making a simple calculator with JavaScript and, after I finished it, I started to look for some parts of my code which it could be improved. I had been trying to make an alert show up if the number 0 or empty was inputted in the prompt and it was working, but then I clicked the CANCEL button in the prompt and the same output happened. My question is how can I change the code below to be able to have one output for the 0 or empty value and another one for the CANCEL button?
const operacao = Number(
  prompt(
    `Qual a sua operação hoje?
    1 - Soma (+)
    2 - Subtração (-)
    3 - Multiplicação (*)
    4 - Divisão (/)
    5 - Potenciação (^)
    6 - Raiz (*/)
    7 - Logaritmo natural (log)
    8 - Divisão inteira (resto)
    `,
    ["Digite aqui!"]
  )
);

if (operacao == false) {
  if (confirm("Quer mesmo sair?") == true) {
    Window.close();
  } else {
    calculadora();
  }
} else if (operacao < 1 || operacao > 8) {
  alert("Por favor, escolha um número que retorne uma operação!");
  calculadora();
} else if (!operacao) {
  alert("Por Favor, digite um número válido!");
  calculadora();
}

A: Per the prompt docs, "If the user clicks the Cancel button, this function returns null." The first thing you do with the result of prompt is coerce it into a Number. Number(null) === 0, so when the user presses Cancel, all of the conditions are evaluated against 0.
However, immediately coercing to Number is the wrong thing to do, because you are losing information. Once you've done so, there's no way to tell the difference between Cancel and typing 0. Instead, we're going to remove the coersion as follows:
const promptResult = prompt(
  `Qual a sua operação hoje?
    1 - Soma (+)
    2 - Subtração (-)
    3 - Multiplicação (*)
    4 - Divisão (/)
    5 - Potenciação (^)
    6 - Raiz (*/)
    7 - Logaritmo natural (log)
    8 - Divisão inteira (resto)
    `,
  ["Digite aqui!"]
);

Then, we're going to add an outer check to your conditionals:
if (promptResult === null) {
  // do whatever should happen when the user presses cancel
} else {
  const operacao = Number(promptResult);
  // the rest of your code goes here
...

Also, note per the docs that Number("invalid number") === NaN, so where you say else if (!operacao), it's clearer (though no less correct) if you check explictly for NaN, i.e. else if (operacao === NaN).


text:
Q: Instantiate a Class - With or Without Parens? scala> class A { ... }
defined class A

A can be instantiated with or without parentheses:
scala> val a = new A
a: A = A@4a27b5cd

scala> val aaa = new A()
aaa: A = A@68aa419e

Which form is (more) idiomatic?
Should the parentheses be included since, as I understand, creating an object is a side effect, similarly to a 0-arity argument's style?

A: I wrote a similar answer here:
https://stackoverflow.com/a/20664517/1296806
It's especially relevant that constructors are not like methods with respect to parens.
A constructor always has a non-implicit parameter list.  If you omit it in the definition, then it is supplied.
new A is idiomatic. (If there's a need to rationalize it, consider the instance as a result.  If instantiation is a side effect, nothing non-primitive could be pure.)
new A().a requires the parens, so they are useful syntactically.
You must supply parens if an implicit follows; see the link.


text:
Q: How to calculate this PV complex integral? $$P.V. \int_{-\infty}^{\infty}\frac{xe^{ix}}{x^2-\pi^2}.dx$$
I find this a challenging integral to solve. I tried solving by extending to the complex plane and integrating over a semicircle contour (real axis, but infinitesimally small hoops (radii $\rho$) around points $x=-\pi$ and $x=\pi$,  plus the arc $Re^{i\phi}$, $\phi \in [0,\pi]$), but this leads me nowhere as i find that the integral on all of the three arcs vanishes, in the limit $R->\infty$, $\rho ->0$ .

A: You may define a contour that looks like $\mathcal{C}=[-R,-\varepsilon]\cup\varepsilon e^{i[-\pi-\varepsilon,-\pi+\varepsilon]}\cup \varepsilon e^{i[-\varepsilon,\varepsilon]}\cup\varepsilon e^{i[\pi-\varepsilon,\pi+\varepsilon]}\cup [\varepsilon,R]\cup Re^{i[-R,R]}$.
$$\oint_\mathcal{C}=\int_{-R}^{\varepsilon}+\int_{-\varepsilon}^{\varepsilon}+\int_{-\varepsilon}^{R}+\int_{-R}^{R}+\int_{-\pi-\varepsilon}^{-\pi+\varepsilon}+\int_{\pi-\varepsilon}^{\pi+\varepsilon}.$$
Note that the sum of the first and the third path intergals correspond your integral, wheras he second and the fourth one go to zero, if you let $R\to\infty$ and $\varepsilon\to0$. This can be easily proven by the ML-inequality and Jordans Lemma. Now you just have to find the other two semicircles that will give you $\pm i\pi$ if you parametrize them correctly:
with
$$x=\pm\pi+\varepsilon e^{i\varphi}.$$
Also not that the integral over $\mathcal{C}$ equals zero.

A: Problem resolved. As @Svyatoslav mentioned (thank you kindly), the integrals over the two hoops do not vanish.
These integrals can be evaluated by rewriting $f(z)$ (after coordinate transformation of $z'= z \pm \pi$)  as $\frac{1}{z} g(z)$, where $g(z)$ is analytic in the relevant domain and can therefore be written as a power series:
$$\int f(z) dz = \int \frac{1}{z}(a_0 + a_1z + a_2z^2 ... ) dz = \int \frac{a_0}{z}dz +\int (a_1 + a_2z + a_3z^2 ... ) dz  $$
In the limit of radius $\rho$ approaching $0$, the latter integral vanishes (as the begining point and end point of the path of integration overlap). The integral that remains can be easily evaluated:
$$\int \frac{a_0}{z} dz = i\int_{\pi}^{0} a_0 dt.$$


text:
Q: Java-Read Text Files And Store Them As Arrays I have the following piece of code. I do not understand why its not working.
I'd really appreciate help on this.
import java.util.Scanner;
import java.io.*;

class ReadFiles {
    String [] codes = new String[99];
    int i = 0;

    private Scanner readCodes;

    public void openCodesFile() {
        try {
            readCodes = new Scanner(new File("C:/Users/Carlo/Desktop/Files/codes.txt"));
        } catch (Exception e) {
            System.out.println("Could not locate the data file!");
        }
    }

    public void readCodesFile() {

        while(readCodes.hasNext()) {
            codes[i] = readCodes.nextLine();
            i++;
            System.out.println(codes[i]);
        }
    }

    public void closeCodesFile() {
        readCodes.close();
    }
}

class NewHardware {
    public static void main(String[] args) {
        ReadFiles codesRead = new ReadFiles();
        codesRead.openCodesFile();
        codesRead.readCodesFile();
        codesRead.closeCodesFile();
    }
}

The output prints out "null" a bunch of times.
Also, I want to be able to not only print out the codes but use the codes array in the class NewHardware and manipulate it (print it out, truncate it, etc).
I was thinking of doing the following with readCodesFile():
public String readCodesFile() {

        while(readCodes.hasNext()) {
            codes[i] = readCodes.nextLine();
            i++;
            System.out.println(codes[i]);
        }
                    return (codes[i]);
    }

Or something but it hasn't worked just yet. Am I on the right track?
Oh, just wanted to add that the text contains the following:
G22
K13
S21
I30
H15
N23
L33
E19
U49

EDIT:
Thanks to Tony and Churk below to help me with my idiocy. I am accepting Tony's answer basically because he challenged me to think but Churk's answer is just as valuable.
For the second part of my question (where I asked about being able to use it in class NewHardware), I did the following:
class NewHardware {
    public static void main(String[] args) {
        ReadFiles codesRead = new ReadFiles();

        codesRead.openCodesFile();

        codesRead.readCodesFile();

        for (int i = 0; i < 9; i++) {
            System.out.println("\n\n" + codesRead.codes[i]);
        }

        codesRead.closeCodesFile();
    }
}

This is of course not the final program code but this has helped me get the basic idea. Hope this helps others too.

A: codes[i] = readCodes.nextLine();
            i++;
            System.out.println(codes[i]);

You are printing codes[i++]

A: Look carefully at your readCodesFile() method.  Look at every line.  What is it doing?  Can you explain it to us?


text:
Q: Trying to get AirPods working in Ubuntu 21.10 on my 2012 MacBook Air, but little seems to work I've already done a ton of searching trying to find solutions to this issue, and the most common fix seems to be changing the controller mode in /etc/bluetooth/main.conf to either bredr or dual, and then restarting the Bluetooth service. However, this did nothing for me. The result is always the same: I open the Bluetooth setup in settings (I'll use KDE's as an example), I attempt to connect, it tells me that it failed to connect, and although the device appears in my paired Bluetooth devices, trying to connect to it instantly lands me the message "protocol not available".
I did also manage to connect it (only once), and the earbud controls let me send a play or pause command, but it wouldn't appear on my actual audio device output list, so I couldn't output audio to the earbuds.
Does anyone possibly know why this could be happening, and does anyone perhaps even have a fix for it?
Thanks.
Error message


text:
Q: How do you connect to BusinessObjects? I have the rights to log into a BOXI server and build queries and reports, but can only export 100,000 rows at a time.
I have tools on my desktop that can connect to databases via things like ODBC.
Is there a way to use ODBC or some other connection type to connect to BusinessObjects?
---Edit---
In response to the first two answers:
Thank you for your insight.
In a perfect world, I would be glad to connect directly to the database servers that BOXI is pulling data from, but I can not. The only access I have to the data is through BOXI.
I understand the row limitation is set by the BOXI admins, but they will not adjust it.
---Edit 2---
Answers to two more questions:

*

*"And you should think of it, what will you do with a query with more than 100k row ?"

I would like to analyze the data with tools on my desktop that are designed to connect directly to data sources.

*"Is there any valuable information in a 100k row answer ?"

I am not look for 100k rows to be my final answer, I am hoping to analyze millions of rows.
A better way to describe my issue:
I have access to data in BOXI, but it is limited in the amount of analysis I can preform, so I want to connect to the data in BOXI and analyze it with tools on my desktop.

A: You want to look at the question a different way: what you want to do is capture the query that BusinessObjects is executing on the database server, and then run that same query yourself on the database server.
For example, if it's accessing data stored in Microsoft SQL Server, you can ask the database administrator to run Profiler to capture your queries while you're executing the report in BO.  He can then give you the queries you ran, and you can execute those same queries in your own tools to get the results directly.
Update: I saw your edits, and what you're asking for just isn't possible.  BOXI isn't a middleware tier for accessing millions of rows of data via ODBC.  You either need to get the admins to allow you to export more data, or you need to connect to the underlying database.

A: If I remember right the limitation of how many rows are allowed to be exported is a configuration value. Look up in the connection properties what the limitations are and set them accordingly.

A: This 100k row is a limitation set by admin of BO XI.
And you should think of it, what will you do with a query with more than 100k row ?
Is there any valuable information in a 100k row answer ?
BOXI will give you report, graph, filtering, and plenty of option, to do the same query directly on the DB will :

*

*give you a huge blurb of more than 100 (could be 1M rows)

*problems with the DBA who will not like you run your query at peak time.

You should think of your query and reduce the amount of data if you want that real time, or schedule the report, to have the full answer during off-peak.


text:
Q: How to share connection_id between 2 queries? I need to execute two SQL statements together because connection_id() in the first statement will be used in the Mysql view wp_statistics_benchmarks.
Without the connection_id(), the wp_statistics_benchmarks is an empty view. The following SQL works fine and get results:
replace into wp_params (`view_name` , `param1_val`, `connection_id`)
                values ('benchmarks', 484         , connection_id())
;

select * from wp_statistic_benchmarks;

But, to work with wordpress, the following code doesn't work:
$mysqli  = new mysqli(.....);

$results = $this->_wpdb->query("
     replace into wp_params (`view_name`, `param1_val`, `connection_id`)
                values ('benchmarks', $connected_from, $mysqli->thread_id);

     select * FROM `wp_statistic_benchmarks`;"
);

How can I convert these two mysql codes into Wordpress wpdb queries?

A: Use the wpdb object twice.
$this->_wpdb->query('replace into ...');
$rows = $this->_wpdb->get_results('select ...')

Let me put it another way, select * from wp_stat ... and replace into wp_params ... from your original "mysql codes" are separate statements without any relation to each other.
You think that you need to run them in sequence, whereas in fact you can have a cup of coffee or even travel around the earth in between those replace into and select statements and they would still do the same thing. If that is not the case, then your question lacks information necessary to provide a good answer because wp_params is not a standard table in wordpress and neither is the view. I don't think you understand your problem.
Besides, running them as I suggest is equivalent with your "mysql codes". Moreover, $wpdb->query returns the number of affected rows or false, so you will never be able to run a select statement with $wpdb->query() to retrieve a set of tuples.

A:
How can I convert these two mysql codes into Wordpress wpdb queries?

You can't. That's because you're using wpdb and it only supports one query per ->query() call. However, if you're using Mysqli with wpdb, you can use the multi_query() method of it with wpdb. Here is how:
To use multiple queries, you need to ensure that wpdb uses Mysqli (e.g. define the USE_EXT_MYSQL constant as  FALSE in your Wordpress config).
Then you can obtain the mysqli instance from the wpdb object, either with reflection or a helper class/module:
abstract class wpdb_dbh extends wpdb
{
    static function from(wpdb $wpdb) {
        return $wpdb->dbh;
    }
}

Mysqli is then available without creating a new instance:
$mysqli = wpdb_dbh::from($this->_wpdb);

As this is a valid Mysqli instance you can run multi query.
But just obtaining the same Mysqli instance as wpdb uses it probably the most important thing here as otherwise your open an additional connection with new mysqli(...) which you need to prevent.
Additionally take care that $mysqli->thread_id is a fitting replacement to connection_id() following the same formatting/encoding. You should be able to use connection_id() directly anyway, so I actually see not much reason to access the thread_id member, but it's perhaps only because you tried some alternatives and I'm just over-cautious.

A: The ';' query delimiter is purely an SQL shell convenience and is not a part of the MySQL dialect so you're correct that your code doesn't work.
Here's the actual replacement code:
$mysqli = new mysqli(.....);
$this->_wpdb->query(
     "replace into wp_params
    (`view_name`, `param1_val`, `connection_id`)
    values ('benchmarks', $connected_from, $mysqli->thread_id)");
$results = $this->_wpdb->query("select * FROM `wp_statistic_benchmarks`");

This is the same as Ярослав's answer above.
Update:
If your code is still not working you might have to enable persistent connections in Wordpress.
Update 2:
There was a missing space between in the second query's select statement and the * shorthand all columns selector.  Interestingly this may or may not cause an issue for you, it doesn't seem to bother my MySQL 5.5 command line shell.

A: If I understand your requirements (and I do not know wordpress), you are inserting a row to wp_params with a column called connection_id. I would assume that this value will be unique on the table. I would be tempted to add an integer autoincrement id field to the table and then get the value of that (last insert id). Then use this id in a WHERE clause when selecting from the view.


text:
Q: Sounds still play when mute/silent mode is ON I'm playing system sounds using AudioServicesPlaySystemSoundWithCompletion and custom sounds using AVAudioPlayer.
Why are sounds played if the silent switch is on? I've tried all the categories for the "AVAudioSession".
I tried the following code:
 try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
 try AVAudioSession.sharedInstance().setActive(true)

Also tried this:
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)

I tried all the categories defined in this link, but the sounds are always playing when the phone is muted (silent switch ON).
https://developer.apple.com/reference/avfoundation/avaudiosession/audio_session_categories
I'm playing the sounds like this:
System sounds:
AudioServicesPlaySystemSoundWithCompletion(1304, nil)

Custom sounds:
        let url = Bundle.main.url(forResource: "sound01", withExtension: ".wav")
        do {
            if audioPlayer != nil {
                audioPlayer!.stop()
                audioPlayer = nil
            }
            if let soundURL = soundURL {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
                try AVAudioSession.sharedInstance().setActive(true)
                audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            }
            guard let audioPlayer = audioPlayer else {
                return
            }
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch let error {
            print(error.localizedDescription)
        }

Am I doing something wrong?

A: The fix was to use the AudioServicesPlayAlertSound function instead of the AudioServicesPlaySystemSoundWithCompletion function.
We also can't use AVAudioPlayer. We need to use the AudioServicesPlayAlertSound function by creating a sound ID for each custom sound.
let soundURL = Bundle.main.url(forResource: "test01", withExtension: ".wav")

if let soundURL = soundURL {
      var soundID : SystemSoundID = 0
      AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
      AudioServicesPlayAlertSound(soundID)
}


text:
Q: Default value for ForeignKey field in django admin panel I have two django Models: PageModel and RecordModel. They are registered in django admin panel. I want automatically create RecordModel object and assign it to (object of PageModel).record field if record is not selected in process of Page creation. (Django Admin - Add Page form) I tried to create form and used clean_record() method, but that not work. (debugger is not stopped there) How can i solve the problem?
Models (Sortable and SortableAdmin classes are part of adminsortable (https://github.com/iambrandontaylor/django-admin-sortable), but I think it does not really matter):
class Record(Sortable):
    """
    Запись в книге почетных гостей
    """
    class Meta(Sortable.Meta):
        verbose_name = u'Запись'
        verbose_name_plural = u'Записи'

    author = models.CharField(verbose_name=u'Автор', max_length=255, unique=False, blank=False,
                              default=author_default)

    def __unicode__(self):
        return u'Запись {} ({})'.format(self.id, self.author)

class Page(Sortable):
    """
    Страница книги почетных гостей
    """

    class Meta(Sortable.Meta):
        verbose_name = u'Страница'
        verbose_name_plural = u'Страницы'

    record = SortableForeignKey(Record, verbose_name=u'Запись', related_name='pages', blank=False, default=None)
    image = models.ImageField(verbose_name=u'Картинка',
                              upload_to='pages',
                              default='',
                              help_text=u'Размер файла - до 10 MB. Формат PNG.',
                              validators=[ImageValidator(formats=['PNG'], max_size=10000000)])
    updated = models.DateTimeField(verbose_name=u'Обновление', auto_now=True, null=True,
                                   help_text=u'Время последнего изменения страницы на сервере')

    def __unicode__(self):
        return u'Страница {} ({})'.format(self.id, self.image)

Admin:
class PageInline(SortableTabularInline):
    model = Page

@admin.register(Record)
class RecordAdmin(SortableAdmin):
    list_display = ['author', 'pages_count']

    inlines = [PageInline]

    fields = ['author']

    def pages_count(self, object):
        return object.pages.count()
    pages_count.short_description = u'Количество страниц'
    pages_count.allow_tags = False

class PageAdminForm(forms.ModelForm):
    def clean_record(self):
        return self.cleaned_data["record"]

@admin.register(Page)
class PageAdmin(SortableAdmin):
    list_display = ['__unicode__', 'image', 'author', 'updated']

    form = PageAdminForm

    readonly_fields = ['updated']

    def get_fields(self, request, obj=None):
        if obj:
            return super(PageAdmin, self).get_fields(request, obj)
        else:
            return ['record', 'image']

    def author(self, page):
        return page.record.author
    author.allow_tags = False
    author.short_description = u'Автор записи'

A: I solved the problem as follows:

*

*Change record field in Page model
record = SortableForeignKey(Record, verbose_name=u'Запись', related_name='pages', null=True, blank=True, default=None)

*Add save_model() method to PageAdmin
def save_model(self, request, obj, form, change):
        if obj.record is None:
            record = Record.objects.create(author=BookConfiguration.get_solo().record_author_default + ' (' + timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S') + ')')
            record.save()


text:
Q: Utility method that allows passing a different comparison function in java for using in contains I have a class that represents each row in my database table. So it has some data members that represent the primary keys in the table while others are non key columns. Say I have a list of rows (listA) that I fetched at some point of time, then after some duration I fetch some more rows (listB) which can contain ones that were fetched earlier but having some updated data in the non key columns. I want to merge listA and listB retaining updated values (i.e stuff in listB). This comparison requires only checking the key columns. So are there any utility (maybe in guava or apache commons etc) contains / removeAll methods that take in a custom comparison function?
For all other purposes I want to check all the data members in the class for equality.
Please note the usual removeAll will use the equals and hashcode that which has been overridden to compare every data member in the class, I want to use a different comparator that compares only the data members that are part of the primary key for the contains.

A: You can use standard-Java Set operations. If your "row" class does not implement equals and hashCode using only the primary key information, you can use some wrapper or utility class that does, for example:
class Row {

  Object pk, a, b;

  public boolean equals(Object other) {
    // Checks for other's type, etc.
    Row otherRow = (Row) other;
    return pk.equals(otherRow.pk) && a.equals(otherRow.a) && b.equals(otherRow.b);
  }
}

class PkInfo {

  final Row row;

  PkInfo(Row row) {
    this.row = row;
  }

  Row getRow() {
    return row;
  }

  public boolean equals(Object other) {
    // Checks for other's type, etc.
    PkInfo otherPkInfo = (PkInfo) other;
    return row.pk.equals(otherPkInfo.row.pk);
  }

  public int hashCode() {
    return row.pk.hashCode();
  }
}

So, whenever you want to merge result sets, you can do something like:
// Your result sets
Collection<Row> listA, listB;

// Your primary-key-based sets
Set<PkInfo> pkiA = new HashSet<PkInfo>();
for (Row r : listA)
  pkiA.add(new PkInfo(r));
Set<PkInfo> pkiB = new HashSet<PkInfo>();
for (Row r : listB)
  pkiB.add(new PkInfo(r));

// Remove from A the rows present in B
pkiA.removeAll(pkiB);

// Modify listA
listA = new ...();
for (PkInfo pki : pkiA)
  listA.add(pki.getRow());

// Add all from listB
listA.addAll(listB);

You can place the code above in a utility method that you call whenever you want to update a list with fresh data from another.

A: In your class you just need to @Override the public boolean equals(Object obj). That is the method used by List when you are testing the contains(Object).


text:
Q: Loading font to Pango I am trying to load a non system font to my GTK application. I have tried using pango to achieve that. Here's my code:
string fontPath = "res/fonts/FreeSans.ttf";
const FcChar8 *fontFile = (const FcChar8*) fontPath.c_str();
FcBool fontAddStatus = FcConfigAppFontAddFile(FcConfigGetCurrent(), fontFile);
if(fontAddStatus)
{
    FcFontSet *fontSet = FcConfigGetFonts (FcConfigGetCurrent(), FcSetApplication);
    PangoFontDescription *desc = pango_fc_font_description_from_pattern(fontSet->fonts[0], false);
    pango_font_description_set_family(desc, "FreeSans");
    PangoAttribute *attr = pango_attr_font_desc_new(desc);
    PangoAttrList *attrs = gtk_label_get_attributes(GTK_LABEL(lbl_0));
    pango_attr_list_change(attrs, attr);
    pango_layout_set_attributes (gtk_label_get_layout(GTK_LABEL(lbl_0)), attrs);
}

When I run that code it gives me:
Pango-WARNING **: couldn't load font "FreeSans Not-Rotated 10", falling back to "Sans Not-Rotated 10", expect ugly output.
How can I do that successfully?
Many thanks


text:
Q: What are the odds of getting a trade token in clan war? After each participation in clan war with the war battle played, you get some rewards.
What are the odds of getting any trade token?

A: According to this article and this datamine reddit post, there is a 10% chance to receive a token. The rates are broken down as follows:

*

*Legendary token: 4%

*Epic token: 3%

*Rare token: 2%

*Common token: 1%

Note: This could change at any time.

A: After a recent update, your average chance is 25%. Basically, there now exists a cycle of 8 War loots, of which 2 have Trade Tokens, 1 has Gems and 5 have Gold.
If I'm not wrong, the chances for each rarity remain the same (e.g. if you get a token, there's a 40% chance to be Legendary, 30% chance to be Epic, 20% to be Rare and 10% to be Common).