text:
Q: Java Spring: RestTemplate with bounded generics Similar to this question, I want to exchange information between two microservices. However the difference is, that my generics is an abstract class and by this I'm having trouble.
My class looks like that:
public <T extends Account> Page<T> getAllAccounts() {   // not working
    ParameterizedTypeReference<Page<T>> responseType = new ParameterizedTypeReference<Page<T>>() { };
    ResponseEntity<Page<T>> result = restTemplate.exchange("http://localhost:8080/api/v1/accounts/", HttpMethod.GET, null, responseType);

    Page<T> accounts = result.getBody();

    return accounts;
}

The function behind the API-call has the return type public <T extends Account> Page<T> getAccounts...) {..}. T can be everything that extends Account, because there are several "Accounts" possible.
The given method also works for non-abstract classes (e.g. Page<CustomerAccount>), however with abstract classes it doesn't.
If I try to call the function, I get the following error message:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Dec 18 14:55:33 CET 2020
There was an unexpected error (type=Internal Server Error, status=500).
Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information at [Source: (PushbackInputStream); line: 1, column: 1]
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (PushbackInputStream); line: 1, column: 1]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:282)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:243)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:105)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1034)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1017)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:710)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:630)
    at de.rwth.swc.lab.ws2021.daifu.businesslogic.services.AccountService.getAllAccounts(AccountService.java:50)
    at de.rwth.swc.lab.ws2021.daifu.businesslogic.api.AccountController.getAllAccounts(AccountController.java:47)
... (rest shortend for better readability)

Question
How can I communicate from Port 8081 with the MS running on port 8080 with "abstract generics" (I think you call them different, but idk atm :D)


text: Q: why jquery time picker selects minutes by default I am using jQuery time picker .When I select hour be default it add minutes  to it then I have to select my desire minutes always to change it.But my question is when I select hour it should not select minutes by default.How it is possible or is anything is possible that when I select hour from time picker by default minutes should be 00.Next I can change minutes on my choice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: codeigniter won't show anything from my producten table could anyone take a look and help me please.
Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_product extends CI_Model
{
    public function getALL()
    {
        $results = $this->db->get('producten');

        return $results->result_array();
    }
}

Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller
{
    public function index()
    {
        $this->load->model('Model_product');

        $data['products'] = $this->Model_product->getALL();
        $this->load->view('header');
        $this->load->view('welcome_message', $data);
        $this->load->view('footer');
    }
}

View:

    Naam
    Beschrijving
    Prijs
    Vooraad
    Categorie

    <?php foreach ($products as $product) { ?>

            <?php echo $product['naam']; ?>
            <?php echo $product['beschrijving']; ?>
            <?php echo $product['prijs']; ?>
            <?php echo $product['producten_op_voorraad']; ?>
            <?php echo $product['categorie_naam']; ?>

    <?php } ?>

There is 1 row in the correct table "producten" the database is loaded. I just don't know what to do. can anyone help me solve this?

A: Afaik you have to call the model product_model.php, call it in the controller "product_model" and call the class "Product_model" (with a capital P).
Also, CI doesn't connect automatically to the database, so while loading you have to specify it with the third parameter.
So:
class Product_model extends CI_Model

And:
$this->load->model('product_model', '', TRUE);

...
$data['products'] = $this->product_model->getALL();

A: try like this
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_product extends CI_Model
{

    function __construct()
    {
         // Initialization of class
        parent::__construct();
    }
    public function getALL()
    {
        $results = $this->db->get('producten');

        return $results->result_array();
    }
}

Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller
{

        function __construct()
        {
             // Initialization of class
            parent::__construct();
        $this->load->model('model_product');
        }
    public function index()
    {

        $data['products'] = $this->model_product->getALL();
        $this->load->view('header');
        $this->load->view('welcome_message', $data);
        $this->load->view('footer');
    }
}

and in autoload.php
$autoload['libraries'] = array('database');

A: Please at the very least locate where the problem is. The fact that you posted the M+C+V shows that you haven't made any effort. Come up with a more specific question.
Check that the right files and lines are executed (e.g.: echo), that the data is loaded from the database (var_dump/print_r/echo), etc (mostly echo... really. debugging 101.)...


text:
Q: dynamic id and special characters for serialization with flat buffers I have Json data like below
{
  "!type": "alarm",
  "$": {
    "12279": {
      "!type": "alarm",
      "title": "Default",
      "$": {
        "5955": {
          "!type": "alarm",
          "name": "Wake",
          "day": "SUN",
          "startTime": "06:00"
        },
        "29323": {
          "!type": "alarm",
          "name": "Away",
          "day": "SUN",
          "startTime": "08:00"
        },
        "2238": {
          "!type": "alarm",
          "name": "Home",
          "day": "SUN",
          "startTime": "18:00"
        }
      }
    }
  }
}

My fbs looks like this

namespace space.alarm;

table Atom{
    !type:string;
    name:string;
    startDay:string;
    startTime:string; }

table AtomShell{
    key:string (required, key);
    value: Atom; }

table Alarm{
    !type:string;
    title:string;
    $:[AtomShell]; }

table AlarmShell{
    key:string (required, key);
    value:Alarm;  }

table Weeklyalarm{
    !type:string;
    $:[AlarmShell]; } root_type Weeklyalarm;

Im trying to implement google flat buffers but I'm getting errors like

*

*alarm.fbs:4:0: error: illegal character: !

*alarm.fbs:23:0: error: illegal character: $  (i have removed ! from
!type and changed $ to dollar to test the working of flat buffers
but i can't change the dynamic ids )

*Sample.json:25:0: error: unknown field: 12279

Now my question,

*

*Is it possible to use dynamic ids in flat buffers, if possible how
shall i proceed?

*Can is use special characters in ids, if possible how to do it?

Thanks in advance.

A: You can't have characters like ! and $ in field names. Just use type instead of !type, etc.
Not sure what you mean by dynamic ids. All field names (keys) have to be declared in the schema, so they can't be dynamic. You can still achieve similar results though, if you make your JSON look something like this:
{
  "type": "alarm",
  "data": [
    {
      id: "12279",
      "type": "alarm",
      "title": "Default",
      "data": [
        {
          "id": "5955",
          "type": "alarm",
          "name": "Wake",
          "day": "SUN",
          "startTime": "06:00"
        },
        {
          "id": "29323",
          "type": "alarm",
          "name": "Away",
          "day": "SUN",
          "startTime": "08:00"
        },
        {
          "id": "2238",
          "type": "alarm",
          "name": "Home",
          "day": "SUN",
          "startTime": "18:00"
        }
      ]
    }
  ]
}

And then make the corresponding schema.
Note that I made the "dynamic" list into a vector, and moved the id into the object itself.
Other tip: string values that are not dynamic (like "alarm") will take up way less space if you make them into an enum instead.


text:
Q: restore postgresql on pythonanywhere from sql-format dump I upgraded PythonAnywhere to the $99 startup plan and created a PostgreSQL database. The PythonAnywhere database page shows:
Address: magula6-1249.postgres.pythonanywhere-services.com
Port: 11249
Superuser role name: super

I want to populate my new database from a pg-dump file created on my macbook.
I've tried several variations of:
$ psql -H magula6-1249.postgres.pythonanywhere-services.com -U super -p
11249 -f 2019_7_30_pgdump.sql
psql: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.11249"?

I also tried:
postgres=# \i /home/magula6/cogswatch/2019_7_30_pgdump.sql
tpsql:/home/magula6/cogswatch/2019_7_30_pgdump.sql:149: ERROR:  function "function_correctiveaction" already exists with s
ame argument types

Oddly the Pythonanywhere database page says:
Postgres disk usage:
100% full (1.0 GB of your 1.0 GB quota)

but the database appears empty:
postgres=# \d
No relations found.

A: The answer:
postgres=# grant usage on schema public to public;
postgres=# grant create on schema public to public;
postgres=# \d

(all my tables appear - amazing)


text:
Q: Playing with z-index Please enter to this website. (I can't recreate same problem on jsFiddle. Sorry) The problem is, when you press recommend's dropdown button, it changes parent div's height. How can I set dropdown menus position over the parent divs border? And why dropdown menu shows fonts white?

A: Your "Recomend" button is not actually a dropdown menu, it's two buttons and an unordered list made to look like a dropdown menu. Therefore it won't function and display like a regular dropdown menu would i.e. overlay on top of the UI when you click it.
You will have to position: absolute the list underneath your buttons to achieve this affect.

UPDATE:
The problem is that the container your buttons are in is positioned relative, which changes the behavior of the child element positioning.

*

*Remove position: relative from .btn-group and #main

*Remove left: 0 and top: 100% from .dropdown-menu

A: change css for class dropdown-menu to position: relative
the color of class dropdown-menu a is getting overwritten by #topContainer a
you can inspect elements using developer tools of the browser.


text:
Q: Trouble installing Kivy on pyCharm I can't install Kivy on pycharm, it doesn't seem to recognize it
I followed the instructions on the kivy website for the installation, which was completed.
I tried to get Kivy to work on pyCharm: I followed these instructions: https://github.com/kivy/kivy/wiki/Setting-Up-Kivy-with-various-popular-IDE's
I only have the basic python interpreter to choose from, but I also tried to install the Kivy package, which didn't seem to make a difference (File > Settings > Project > Project Interpreter > +(Available packages) and selected Kivy)
I tried following different online tutorials, which all seemed pretty similar one to the other, but my problem persists.
This is the shown message:
Traceback (most recent call last):
  File "C:/Users/ivost/PycharmProjects/Kivy/Kivy try.py", line 1, in <module>
    import kivy
ModuleNotFoundError: No module named 'kivy'

A: There shouldn't be anything special to install in Pycharm as far as modules are concerned. Pycharm scans your Python installation. So when you install a new package with pip, it will automatically be available in Pycharm. Assuming you don't have several python installation and are confused as to which one gets the installation though...
The tutorial page you mention will help you with other things, like code coloring/completion with kv language for instance but is not necessary if you just need to write kivy apps in Pycharm.

A: I had trouble installing Kivy too.
It only worked when I uninstalled and reinstalled Kivy from Terminal.
To uninstall:
    $ pip uninstall kivy

To install:
    $ python -m pip install kivy==2.0.0rc1

I hope this helps !

A: This message is shown because you haven't installed the dependancies foe kivy,for that, you should install these three modules in the projects interpreter settings as well after installing kivy:
kivy-deps.sdl2
kivy-deps.glew
kivy-deps.gstreamer

it should solve the problem


text:
Q: How to redirect to callback url using POST I am a newbie to ASP.NET NVC and I'm currently (self) learning how to consume Web APIs. I want to integrate an OAuth Web API into my ASP.NET MVC application to have the following flow.

*

*User clicks Login Button

*redirect to API-login website

*User logs in

*User accepts T&C

*The redirected page URL has the access token

*Access token is retrieved by the main MVC app

*Using HTTP Post, the necessary data is displayed on the page.

Currently I am able to redirect to the login website using the Redirect(Uri url) method and carry out steps 1-4. However, I am stuck at step 5 where the T&C page redirects to a page with the access token as part of the URL, which produces a server error (because I haven't implemented the https://localhost:5241/redirect in my application yet)
The URL with the token is in the form https://localhost:5241/redirect?token="abcde..."
Please advise me as to how I should implement the /redirect portion to redirect to my main page (in step 1), and how I can parse the token from the redirected URL.
My current approach is to create a redirect controller which redirects to the main page (home controller) and creates the POST request in step 7.
Any help/advice would be appreciated.
Thank you.


text:
Q: invalid label json label vs javascript label I get invalid label error for "firstname": "John2",.
I put my json data in parenthesis, so why am I still getting this error?
Am I still lacking something so that the code is confusing it with a java script label?
    <script type="text/javascript">
        var data = "(" + {
  "firstname": "John1",
  "lastname": "Doe",
  "location": {
    "latitude": "48.4048403957642",
    "longitude": "2.68452644348145"
  }
}
{
  "firstname": "John2",
  "lastname": "Doe",
  "location": {
    "latitude": "48.4050236871384",
    "longitude": "2.68512690051361"
  }
}
{
  "firstname": "John3",
  "lastname": "Doe",
  "location": {
    "latitude": "48.4048403957642",
    "longitude": "2.68452644348145"
  }
}
+ ")" ;

      function initialize() {
        var center = new google.maps.LatLng(48.404840395764175, 2.6845264434814453);

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var markers = [];
        for (var i = 0; i < data.length; i++) {
          var location = data[i];
          var latLng = new google.maps.LatLng(location.latitude,
              location.longitude);
          var marker = new google.maps.Marker({
            position: latLng
          });
          markers.push(marker);
        }
        var markerCluster = new MarkerClusterer(map, markers);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>

A: You have two problems (that I can spot).
First, you are working in JavaScript, not JSON. You have an object literal.
Get rid of the "(" and ")" entirely. Those are used if you are trying to parse JSON using eval. You don't have JSON and if you did you should use the JSON object (and its parse method), not eval. Currently, you are trying to stringify the object (which would give you something like "([Object object])", which wouldn't be any use at all).
Second, you appear to be trying to work with an array of objects, but you have just placed them one after the other.
Wrap your objects with an array literal [ and ].
Separate the items in the array with commas (,).
The reason for the error message is that you have created such a weird parse state that the JS engine things you are trying to label a loop.

A: Isn't it easier to use a JSON generating function? For example:
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

for (var key in arr) {
    var value = arr[key];
    if(typeof value == "object") { //Custom handling for arrays
        if(is_list) parts.push(array2json(value)); /* :RECURSION: */
        else parts[key] = array2json(value); /* :RECURSION: */
    } else {
        var str = "";
        if(!is_list) str = '"' + key + '":';

        //Custom handling for multiple data types
        if(typeof value == "number") str += value; //Numbers
        else if(value === false) str += 'false'; //The booleans
        else if(value === true) str += 'true';
        else str += '"' + value + '"'; //All other things
        // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

        parts.push(str);
    }
}
var json = parts.join(",");

if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}

(Sidenote: I did not make this code myself, but it's very useful!)
You can make JSON data using:
myJSON = array2json(['any data', {'even objects': 'can go in here'});

And you can get the array back using:
var myArray = eval('(' + myJSON + ')');


text:
Q: Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff) I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:
The resource from "https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js" was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js" was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

A: It might be a wrong path.
Ensure in your main app file you have:
app.use(express.static(path.join(__dirname,"public")));

Example link to your css as:
<link href="/css/clean-blog.min.css" rel="stylesheet">

similar for link to js files:
<script src="/js/clean-blog.min.js"></script>

A: For Wordpress
In my case i just missed the slash "/" after get_template_directory_uri() so resulted / generated path was wrong:

My Wrong code :
wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' );

My Corrected Code :
wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );

A: This can be fixed by changing your URL to use a mirror/proxy.  Instead of using GitHub:
https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Use a third-party cache:
https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com was a caching proxy service for GitHub that has shut down since 2018. See its FAQ

A: We started facing this error in production after our devops team changed the webserver configuration by adding X-Content-Type-Options: nosniff. Now, due to this, browser was forced to interpret the resources as it was mentioned in content-type parameter of response headers.
Now, from the beginning, our application server was explicitly setting content-type of the js files as text/plain. Since, X-Content-Type-Options: nosniff was not set in webserver, browser was automatically interpreting the js files as JavaScript files although the content-type was mentioned as text/plain. This is called as MIME-sniffing. Now, after setting X-Content-Type-Options: nosniff, browser was forced to not do the MIME-sniffing and take the content-type as mentioned in response headers. Due to this, it did interpret js files as plain text files and denied to execute them or blocked them. The same is shown in your errors.
Solution: is to make your server set the content-type of JS files as
application/javascript;charset=utf-8

This way, it will load all JS files normally and issue will get resolved.

A: This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.

A: I've solved this problem by changing charset in js-files from UTF-8 without BOM to simple UTF-8 in Notepad++

A: check your path ,this error will come if file was not exist into given path.

A: Are you using express?
Check your path(note the "/" after /public/):
app.use(express.static(__dirname + "/public/"));

//note: you do not need the "/" before "css" because its already included above:
rel="stylesheet" href="css/style.css

Hope this helps

A: Check if the file path is correct and the file exists - in my case that was the issue - as I fixed it, the error disappeared

A: I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8 and i changed the content type to application/javascript
It started working.

A: It happened to me for wrong tag. By mistake I add the js file in link tag.
Example: (The Wrong One)
<link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.js">

It solved by using the correct tag for javascript. Example:
<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>

A: See for the protocols HTTPS and HTTP
Sometimes if you are using mixed protocols [this happens mostly with JSONP callbacks ] you can end up in this ERROR.
Make sure both the web-page and the resource page have the same HTTP protocols.

A: I got this problem, when having a function name in the url parameters (firefox 68).
E.g. https://.../test.html?concat() where test.html is
<!DOCTYPE html>
<html>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
</html>

concat is a function in math.js.
I have no idea, why it happens at all. And it occurs least for this function, while some other functions have no effect.
A space between concat and the parenthesis https://.../test.html?concat () solves the problem.

A: app.static() does not preserve the file directory. For example: If you use app.static('static/') and link to the file as <script src="/static/code.js"></script> then the file will not be found as it is looking in the long place. Changing the code to <script src="code.js"></script> solved the problem for me

A: i also facing this same problem in django server.So i changed DEBUG = True in settings.py file its working


text:
Q: Auto scroll to Bottom I am working on application with chat screen. But as normal screen it starts scrolling from top to bottom. But its should be from bottom to top. The application is in Telerik Nativescript platform.
View.xml
<ScrollView row="0" col="0">
    <StackLayout class="history-content-area">
        <Repeater items="{{messageHistory}}">
            <Repeater.itemTemplate>
                <StackLayout>
                    <!-- ITEMS GO HERE -->
                </StackLayout>
            </Repeater.itemTemplate>
        </Repeater>
    </StackLayout>
</ScrollView>

I need help in above code how can i scroll to bottom automatically on page load ? Let me know if you need javascript code.
Thanks in advance.

A: On your ScrollView you can use scrollToVerticalOffset where you can pass the offset to scroll to.
For example:
view.xml
<ScrollView row="0" col="0" id="myScroller">
    <StackLayout class="history-content-area">
        <Repeater items="{{messageHistory}}">
            <Repeater.itemTemplate>
                <StackLayout>
                    <!-- ITEMS GO HERE -->
                </StackLayout>
            </Repeater.itemTemplate>
        </Repeater>
    </StackLayout>
</ScrollView>

view.js
mScroller = page.getViewById("myScroller");

var offset = mScroller.scrollableHeight; // get the current scroll height
mScroller.scrollToVerticalOffset(offset, false); // scroll to the bottom

A: Let's say your ScrollView has its id to 'id-scroller'. Then in your View.js you do:
let scroller = page.getViewById('id-scroller');

setTimeout(function() {
  scroller.scrollToVerticalOffset(scroller.scrollableHeight, true);
}, 1);


text:
Q: Received SIGHUP or SIGTERM: nano cannot edit empty file I have a empty file in home directory, when I run nano temp4 it gives me error Received SIGHUP or SIGTERM and does not open the file
@archlinux ➜  ~  ᐅ  nano temp4
    Received SIGHUP or SIGTERM
@archlinux ➜  ~  ᐅ  l temp4
    -rw-r--r-- 1 edward edward 0 May 17 16:04 temp4
@archlinux ➜  ~  ᐅ  file temp4
    temp4: empty

what could be the reason? This has been happening too often lately with many other files.
However, I can solve the problem by running echo > temp4 and then opening it with nano
(I am running Arch Linux. nano 2.5.3)


text:
Q: CSS selector for child of EITHER parent A or B (best practice)? In short, I'd like to select a child element that has either Parent A or Parent B.
I'm wondering if there's a way to simplify my selectors in this scenario, or if what I have here is the only way to do it.  Also, is there a best practice in this scenario?  Below are some simplified examples:
/* long example (probably not best practice) */
    #parent-a .common-child {
        color: #000;
    }
    #parent-b .common-child {
        color: #000;
    }

/* shortest example I know of */
    #parent-a .common-child, #parent-b .common-child {
        color: #000;
    }

Is there any way to do something like:
#parent-a||#parent-b .common-child {
    color: #000;
}

It might not look like a big deal in these simple examples, but in my actual CSS I have several dozen selectors that chain down through the DOM a bit, and I want to optimize the file size / readability.
Thanks!

A: /* shortest example I know of */
#parent-a .common-child, #parent-b .common-child {
    color: #000;
}

This would be the most simplified solution. They have to be separated. All you can do is combine similar styles into one line like in the above.
However, I would say that you're almost leaving the realm of use for an ID selector. An ID is meant to be unique, and the styles that apply to it should be unique as well. If you ever add a parent-c or further, you should definitely consider adding a single class to those elements rather than selecting each one by its ID.
color: #000 is a very broad style. If that were the only style being applied to both of these elements, it would make sense to set the style on a parent higher up so that it gets inherited by all its children, grandchildren, and so on.
Without seeing more of your structure, we can't really advise you on best practices. CSS and its optimization is very highly based on what else is around it and being specific.

A: Unfortunately there is no shorter way to do it than your last example.

A: In Sass this can be done with the Sass Ampersand:
parent1, parent2 {
    & .common-child {
        color: #000;
    }
}


text:
Q: Having issues with uitable I have created a uitable. In addition to that, I have a function, f(handles, some parameters), that its goal is to produce a 9-by-2 matrix. Then I want to pass the matrix to the uitable. I don't want to edit it manually it just has to be edited by the function. The problem is that I can't figure out how I should pass the data to the uitable. Using tableA_CellEditCallback(hObject, eventdata, handles) is prohibited because it doesn't accept handles. I don't know how to do that. Any suggestion is highly appreciated.

A: Using set on the Data property should do the trick:
result = f(handles, parameters);
set(handles.uitable, 'Data', result);


text:
Q: How to use "SQL SELECT DISTINCT Statement" on multiple columns specifically in MySQL database management system? I know how to use "SQL SELECT DISTINCT Statement" on a single column as below :
SELECT DISTINCT City FROM Customers;

But what about using "SQL SELECT DISTINCT Statement" on multiple columns(PostalCode and Country are the two other desired columns) where I want different(i.e. DISTINCT) data elements from to each of the desired columns?
I want the answer specific to MySQL database.
I checked on stackoverflow. The questions like these have been already asked but the have been answered bt keeping in mind the MS SQL Server database. So, I've asked this question specifically oriented to MySQL database system.
Please provide me in detail solution with appropriate explanation.
Thanks.

A: You can use
select distinct PostalCode ,Country
from
yourtable

Note the Above distinct implies unique combination of postalcode,country not unique combination of  postalcode and unique combination of country

A: You can use something like:
SELECT DISTINCT(CONCAT(col1, col2, ...)) FROM Table;
Or SELECT col1, col2, ... FROM Table 1 group by 1, 2, ...
Not sure which is performing better though.

A: When you use distinct make sure the fields are selected only and has a redundant value like this:
Select  distinct fieldshas_duplicate_one,fieldshas_duplicate_two from table;


text:
Q: Access notification within webview I just started using cordova for a web app I built, I am currently building the cordova app with the following
<script>window.location.assign('http://192.168.1.11/projects/1/backbone/app/')</script>

Can some one tell me if it is possible for me to call the following within my web app so that it affects the phones state?
navigator.notification.vibrate(2500);

If so what am I doing wrong or can you point me in the right direction.


text:
Q: How to overload operator<< to output a vector, defined inside a template? The example below is a distilled version of a problem with templates I'm having - please see compilation errors below.
#include <iostream>
#include <vector>

template <class T> struct S
{
  typedef std::vector<T> SVec;
};

template <class T> std::ostream& operator<<(std::ostream& OS, const S<T>::SVec& X)
{
  for (const auto& e: X) OS << e << ' ';
  return OS;
}

int main()
{
  S<int>::SVec v;
  std::cout << v << std::endl;
}

Compiler output:
g++ -g -Wall -O4 -std=c++11 -c tc041.cpp
tc041.cpp:22:69: error: need 'typename' before 'S<T>::SVec' because 'S<T>' is a dependent scope
 template <class T> std::ostream& operator<<(std::ostream& OS, const S<T>::SVec& X)

And so on - hundreds of lines.
My compiler - g++ 5.2.1, OS - Xubuntu 4.2.0.
How to make this operator to be compiled correctly?

A: There are two problems:

*

*Missing typename keyword at the operator declaration.

*Template type deduction fails in main.

template <class T>
std::ostream& operator<<(std::ostream& OS, const typename S<T>::SVec& X)

A typename keyword should be placed before S<T>::SVec. Due to language rules, the compiler does not know whether SVec is a member type or something else. The typename keyword is to tell the compiler it is a type.
For details of the language rules, you may refer to: http://en.cppreference.com/w/cpp/language/dependent_name

(Note: I am actually less sure about it because this scenario is new to me too.)
Let's do an experiment. Instead of invoking operator<< with operator syntax, let's invoke it with function syntax.
operator<< (std::cout, v);

Well, it still fails.
What if we invoke it with explicit template argument?
operator<< <int> (std::cout, v);

It works! Well, actually, may work. I find that some standard library header may contain something that interferes it. But let's put it aside.
The problem this experiment demonstrates is that the template argument deduction fails. Argument type of the form class-template-name<T>::member-type cannot be deduced.
Details: http://en.cppreference.com/w/cpp/language/template_argument_deduction


text:
Q: Advice on how I can decrease Kafka Lag I'm relatively new to working with Kafka, below is a sample of what my current set up is.
Kafka Setup
Multiple topics that all have one partition each. 2 Consumer Groups with each group containing one consumer.
The issue I am seeing is that the Lag is enormous, sometimes upwards of 8-10 hours waiting for consuming, the load is about 100-200 million messages a day
What steps should I look at in order to address this? Is it as simple as reassigning partitions or creating new partitions for the 3 topics that are being consumed by the two consumers? - I've also looked at compressing the contents of the producer with gzip but it doesn't really help in terms of the lag. I've looked at network connections and don't feel that it is anything got to do with this. If anyone could point me in the direction of Kafka and Low Latency documents that would be good also.

A: Generally the flow is to parallelize your consumption through the increase on the number of partitions and consumers in consumer groups that subscribe to those topics with increased partitions (Nconsumers <= Npartitions).
And distribute your topics with increase on the number of brokers in your cluster.
So from topic considerations:
Less partition per topic result:

*

*in producer and/or consumer lag

*starved or overloaded brokers and consumers.

(But take into account) More partition per topic result in:

*

*More broker resources – file handlers and memory.

*There is an overhead with each additional partition and a number of partitions a broker can handle is limited.

*Overhead of replication load

Then increase the number of consumers in that consumer groups.

Try increasing partition per topic, but by itself it should not help! You also will need to increase the number of consumers in your consumer group. Is that single consumers or consumer groups on your diagram? How many consumers in your consumer group vs partitions on the topic that they are subscibed to.

From this in your message:

I've also looked at compressing the contents of the producer with gzip but it doesn't really help in terms of the lag.

I get an idead that your messages may be huge! Is it so? In case yes, try to keep messages small (for example by excluding BLOBs and keep external links to them)
Still the issue may be somewhere else like bad configs, consumer commit messages (acknowledgment handling), etc.
So, I highly advice you to read article Fine-tune Kafka performance with the Kafka optimization theorem

I also advise you to go through Apache Kafka courses on Confluent web-page
This should be added as a comment, but I haven't had permissions to do so. The provided info is very limited with incorrect diagram, which limits the ability to provide an adequate helpfull answer. If possible please correct your diagram and add more details about your set-up like:

*

*broker configuration, file attached;

*consumer set-up (Consumer commit messages);

*producer set-up;

*topic set-up;

*kafka version (the defaults differ with major/minor versions)
The provided diagram is not correct in the notion of topic - partition relationship, so I assume it is a mistype and Partition 0 must be substituded with Broker 0, right?

Kafka's topics are divided into several partitions. While the topic is a logical concept in Kafka, a partition is the smallest storage unit that holds a subset of records owned by a topic...

Then there is an open question on the number of partiotions in each topic and the number of topics in each broker, as well as the number of brokers in your cluster!


text:
Q: Nonzero [error] code on gpg: keyserver receive failed: Cannot assign requested address I am getting this message on building a Debian:stretch-slim Docker image with Python 3.7.7:
gpg: keyserver receive failed: Cannot assign requested address
The command '/bin/sh -c set -ex [...]'
[...] returned a non-zero code: 2

I think it's a GPG or a networking issue.
Any tips? Your assistance is highly appreciated.

A: Following the recommendation from Laurent Sittler, the solution was on adding options to the gpg servers.
Find this line in the Dockerfile:
&& gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$GPG_KEY" \

and replace it with this block:
&& ( \
  gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$GPG_KEY" \
    || gpg --batch --keyserver pgp.mit.edu --recv-keys "$GPG_KEY" \
    || gpg --batch --keyserver keyserver.pgp.com --recv-keys "$GPG_KEY" \
) \

A: UPDATE: Any change in the code has no effect. You need to run your code again until it works (or you add more download locations to go through in an if-statement so that the chance is less that you do not catch a download); see the other answer of this thread.
I just leave the following old part here as a proof that any placebo code changes did not help me, it was random and it strangely appeared at every first run, while at the second, it usually worked.

Run
sudo apt-get update

before you run
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0F164EEB

And if you have an "echo" line before that, run another sudo apt-get update even before that:
RUN apt-get update
RUN sh -c 'echo "..." > /etc/...'
RUN apt-get update
RUN apt-key adv ...

By this, I got rid of the similar error "Cannot assign requested address":
Executing: /tmp/apt-key-gpghome.Up2U8vHXpt/gpg.1.sh --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key C1CF6E31E6
gpg: keyserver receive failed: Cannot assign requested address
ERROR: Service 'listener' failed to build: The command '/bin/sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key C1CF6E31E6' returned a non-zero code: 2

Most likely: server is just busy, try again
This could be a placebo, though, since this answer to the same error, but in another context says that this can appear when the address is just busy. Which would mean: if you have this error, just try again, and sudo apt-get update might not change anything, then. That sounds most likely.


text:
Q: How to stop return undefined for json_encode I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.
If it not found any newly added data in mysql, it's return a undefined value. So as per my script, It's append a undefined one after one at a time interval.
How to stop this undefined value?
my javascript:
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});

function addrep(type, msg){
CID.forEach(function(id){
    $("#newreply"+id).append("

"+ msg.detail +"

");
});
}

function waitForRep(){
    $.ajax({
        type: "GET",
        url: "server.php",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: {
        // this way array containing all ID's can be sent:
        CID : CID
    },
        timeout:15000,
        success: function(data){
            addrep("postreply", data);
            setTimeout(
                waitForRep,
                15000
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            setTimeout(
                waitForRep,
                15000);
        }
    });
}

$(document).ready(function(){
    waitForRep();
});

server.php
while (true) {
    if($_REQUEST['CID']){  //cid got all dynamic post id as: 1,2,3,4 etc.
      foreach($_REQUEST['CID'] as $key => $value){

        $datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
        $res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']."  AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
    $data = array();
        while($rows =  mysqli_fetch_assoc($res)){

          $data[]=$rows;

          $data['id'] = $rows['id'];
          $data['qazi_id'] = $rows['qazi_id'];
          $data['username'] = $rows['username'];
          $data['description'] = $rows['description'];
          $data['date'] = $rows['date'];
          //etc. all
             $id = $rows['id'];
             $qazi_id = $rows['qazi_id'];
             $username = $rows['username'];
             $description = $rows['description'];
             //etc. all
          } //foreach close
      } //foreach close

          if ($description=="") {$detail .= '';}
            else {$detail .=''.$description.'';}
          $data['detail'] = $detail;
          // do somethig

           if (!empty($data)) {
              echo json_encode($data);
              flush();
              exit(0);
           }

    } //request close
    sleep(5);
} //while close

A: Edit your addrep function to not insert if it's undefined:
function addrep(type, msg){
CID.forEach(function(id){
    if(msg.detail != "undefined") {
       $("#newreply"+id).append("+ msg.detail +");
    }
});
}

Or just break it if undefined:
function addrep(type, msg){
    CID.forEach(function(id){
        if(msg.detail == "undefined")
           break;
        $("#newreply"+id).append("+ msg.detail +");
    });
}


text:
Q: Function calls within a loop when its not necessary PHP This might be a very dumb question but it still bugs me. I tend to use this:
$variable = $someObject->getSomeValue();

for ($i = 0; $i < $x; $i++) {
   performSomeFunction($variable);
}

I have seen people do the following & some of my co-workers are arguing with me that there is no difference in performance if I use function calls within a loop & that it will save 1 line of code.
for ($i = 0; $i < $x; $i++) {
    performSomeFunction($someObject->getSomeValue());
}

Now for $x = 10 this might not have impact on performance but what if $x = 10000 ? Which one is the preferred way or best practice in PHP and in Programming general?
Example of function getSomeValue
// just a getter method for the class
function getSomeValue() {
   return $this->userFirstName;
}

A: Highly depends on your function. For example this
function() {
  return 2;
}

It won't matter.
For this:
function() {
  $pdo->query('SELECT ....');
  // more db stuff
  return $someDbStuff;
}

It will matter extremely!

A: Depends on what you do on $someObject->getSomeValue();. If just returns a variable, it doesn't have any impact on performance, if, on the other hand, you are retrieving the data from a database, its very important to avoid it.
However, its always a good policy to avoid unnecessary iterations and do like this
$variable = $someObject->getSomeValue();

for ($i = 0; $i < $x; $i++) {
   performSomeFunction($variable);
}

A: Yeah, sure there's an impact in the performance.
If you are about to use the same value over iterated loops, why would you go get it every time?
It's better getting it before the loop (if there's no chance of changing this value while in the loop) and then reusing it.
Imagine this getSomeValue() needs to access a database or a webservice, would you rather do it 1 time or $x times for the same effect?


text:
Q: JTA(Bitronix)/JPA/Hibernate - How I can get XAResource from an Entitymanager? Do you know how I can get XAResource that is automaticaly enlist to my transaction when I use my entity manager ?
I use Bitronix, JPA, hibernate, my code works fine, but I don't want to rollback all my XAResources if one specific failed. I just want to delist it from the current transaction and others will be commited.
But for delist it of the current transaction, I need the object XaResource and I don't know how i get it with JPA/Bitronix. example of code :
transactionManager.begin();
try {
    (...)
    EntityManager em = emf.createEntityManager();
    (...)
    em.close();
} catch (Exception e) {
    // old version - rollback every XaResource in the current transaction
    //transactionManager.rollback();
    //new version wanted - rollbackonly this XaResource
    transactionManager.getTransaction().delistResource(XaResource ...);
    throw e;
}
transactionManager.commit();

Thanks for your help.

A: The A(tomicity) property of ACID doesn't allow such scenario. The transaction can only be successful if all data sources were able to commit.
I think the Command Pattern can help you with your problem. Let's say you want to update two data sources, and if one fails you still have control whether to undo the already executed commands.
If you never want to undo, then you don't need XA transactions. You just have to use Resource Local transactions, and if one data source fails, the rest could proceed.


text:
Q: Why does sbt try to publish packages anonymous We are running an artifactory server that we use for our artifacts. When I tail the access log I notice that everytime an sbt project publishes, it will first try to do this anonymous (which is disallowed in our configuration).
In the access log there will always show up two lines with denied deploys. The curious thing here is that the ip adress is also different. It turns out that the ip address that succeeds is the ip adrress of the slave (which I expect to publish) and that the other ip address is from the controller of the build server (Jenkins in our case).
I am not very familiar with sbt, but in our sbt configurations there is a part that appends the correct credentials from a file
credentials += Credentials("path" / "to" / ".credentials")

Is it possible that the credentials sequence contains an anonymous entry and that it will try that one first?
And does anyone know why it tries to publish from the build server ip, where the job is not running?
BTW the publish does work, but it annoys me that it is trying to publish anonymous


text:
Q: Is changing a block device's ownership/permissions equivalent to changing a filesystem's ownrshp/perms? Is this something one would want to do? I was trying to answer this question: Cannot fsck a disk due to no r/w access. To which I replied:

The answer is implied in fsck's output.
Change ownsership with:
# chown username /dev/sdb5
$ fsck /dev/sdb5

Or don't change it and become root instead (probably better):
# fsck /dev/sdb5

If device is mounted, unmount it before.

The alluded fsck output being:

You must have r/w access to the filesystem or be root.

Then another user commented in my answer the following:

Never change the ownership of a blockdevice. It opens security holes
  and it normally also prevents a normal user from doing something
  stupid. So the sudo option you describe would be the way to go. Maybe
  you want to adopt your answer.

And this confuses me, because normally, I would create a filesystem by running mkfs on a block device, e.g. sudo mkfs.ext4 /dev/block_device. So I assumed that to interact with that filesystem I must do it through the block device file. Now, if the file system resides in /dev/block_device, when I change the block device's ownership or permissions, does that mean I'm changing the filesystem's ownership or permissions?
If I made the wrong assumption and these things aren't equivalent, then how does one change the ownership or permissions of a file system?
Or is this something one just shouldn't do? Why?

A: When you change the owner or ownership of the block device, you do not change anything in the filesystem. What happens if you chown the block device to a normal user is, that you completely bypass the filesystem access rights.
A block device is just container that holds unstructured data. The filesystem makes this structured and usable. Normally all users access the block device indirectly through the filesystem, asking to read/open/write files or folders. All based on the access rights that are maintained by the filesystem, granting or denying access to a file or folder.
Now when a normal user has read/write access on a block device, one can bypass those access rights of the filesystem as you can "scratch" files directly form the block device.
Let's walk through.
First we create a folder and file that is only accessible by root, starting with a block device as it should be.
root@host:~# ll /dev/vda1
brw-rw---- 1 root disk 253, 1 Jul 26 18:52 /dev/vda1

root@host:~# mkdir /secure-folder
root@host:~# chmod 700 /secure-folder/
root@host:~# ll -d /secure-folder
drwx------ 2 root root 4096 Jul 27 20:06 /secure-folder/

root@host:~# echo "MySuperSecretText" > /secure-folder/my-secure-file
root@host:~# chmod 400 /secure-folder/my-secure-file
root@host:~# ll /secure-folder/my-secure-file
-r-------- 1 root root 9 Jul 27 19:19 /secure-folder/my-secure-file

This folder and file can only be accessed by the root user and even after changing the owner of the block device, it is still as you would expect.
user@host:~$ ll /secure-folder/
ls: cannot open directory /secure-folder/: Permission denied
user@host:~$ ll /secure-folder/my-secure-file
ls: cannot access /secure-folder/my-secure-file: Permission denied

root@host:~# chown user /dev/vda1
root@host:~# ll /dev/vda1
brw-rw---- 1 user disk 253, 1 Jul 27 20:16 /dev/vda1

user@host:~$ ll /secure-folder/
ls: cannot open directory /secure-folder/: Permission denied
user@host:~$ ll /secure-folder/my-secure-file
ls: cannot access /secure-folder/my-secure-file: Permission denied

In this case your filesystem is preventing the user from access files that it does not have access rights to.
But since the user has read/write access to the block device, we can bypass the filesystem. vda1 here is the partition that is mounted on / and debugfs comes with e2fsprogs, so is pretty sure preinstalled.
user@host:~$ debugfs /dev/vda1 -R "ls -l /secure-folder"
  67344   40700 (2)      0      0    4096 27-Jul-2017 19:33 .
      2   40755 (2)      0      0    4096 27-Jul-2017 19:16 ..
  45137  100400 (1)      0      0      18 27-Jul-2017 19:43 my-secure-file

Alright, I can list the directory entries in a folder I do not have access rights. Let's see what else can be done on a file that I do not have access rights on.
user@host:~$ debugfs /dev/vda1 -R "cat /secure-folder/my-secure-file"
debugfs 1.42.9 (4-Feb-2014)
MySuperSecretText

Alright, I can read contents of files this way. Cool. What else could I do? Let's create a folder in a place I normally couldn't.
user@host:~$ debugfs -w /dev/vda1 -R "mkdir /secure-folder/attack"
debugfs 1.42.9 (4-Feb-2014)

root@host:~# ll /secure-folder/
total 16
drwx------  2 root root 4096 Jul 27 19:33 ./
drwxr-xr-x 25 root root 4096 Jul 27 19:16 ../
drwxr-xr-x  2 root root 4096 Jul 27 20:29 attack/
-r--------  1 root root   18 Jul 27 19:43 my-secure-file

Ooops. It even belongs to root although I have created it as user. Hm, what else would be possible? Let's try.
First we need the block number of the /secure-folder/my-secure-file.
user@host:~$ debugfs /dev/vda1 -R "blocks /secure-folder/my-secure-file"
debugfs 1.42.9 (4-Feb-2014)
913939

Okay, block number 913939 contains the data of the file /secure-folder/my-secure-file. Let's use dd to get the content, 4096 is the default block size of ext4 or xfs filesystems. Again possible because I can operate on the block device as a normal user.
user@host:~$ dd if=/dev/vda1 of=/tmp/secure-file skip=913939 bs=4096 count=1
1+0 records in
1+0 records out
4096 bytes (4.1 kB) copied, 0.0214174 s, 191 kB/s

Now we can modify /tmp/secure-file and dd it back on the block device.
user@host:~$ cat /tmp/secure-file
XxXxxxxSecretText

user@host:~$ dd if=/tmp/secure-file of=/dev/vda1 seek=913939 bs=4096 count=1
1+0 records in
1+0 records out
4096 bytes (4.1 kB) copied, 0.000356448 s, 11.5 MB/s

Last, as root user let's have a look at the file from the filesystem view. To make it safe we first invalidate all caches to get the content of the disk.
root@host:~# echo 3 > /proc/sys/vm/drop_caches
root@host:~# cat /secure-folder/my-secure-file
XxXxxxxSecretText

root@host:~# ll /secure-folder/my-secure-file
-r-------- 1 root root 18 Jul 27 20:39 /secure-folder/my-secure-file

I have changed a file that belongs to root as normal user and did not have to change any access rights. All based on the fact that I had read/write access to the underlying block device.
This is only a simple example and an advanced attacker could place binary code in your filesystem or exchange well known binaries with malicious ones. Normally the tools used are preinstalled on nearly any distribution.
Well, I must admit that the access rights on the block device are set back  when you reboot by udev, but it opens a security issue when you give read/write access to a normal user to a block device.
Hope it's not too confusing and helps to understand the difference between the filesystem and the block device.

A: I think you are misunderstanding the implication. as a member of the sudo group you have R/W access by default. This doesn't imply that you are in fact root, just that you have similar access depending upon how sudo is configured.
Further reading:
https://help.ubuntu.com/community/Sudoers
https://www.tecmint.com/su-vs-sudo-and-how-to-configure-sudo-in-linux/


text:
Q: Database design/storing formulas in the database I'm making an app that has to do a lot of different calculations based on user answers(mostly YES/NO and some numbers) and every different combination has a different message/text to be displayed. So I thought I'll just store all the different combinations (less then a 500 total) in MySQL and fetch the message I need. But what do I do with the formulas ? Most combinations have different formula that depends on the user input. I thought of storing them as string and writing a parser, but it doesn't seem right.
Here's an example:
> Graduated with above 3.5 GPA: 0(YES), 1(NO)
>
> Attends College: 0(YES), 1(NO)
>
> Makes less then 20,000 yearly: 0(YES) 1(NO)
>
> Age: Number
>
> Working Experience: Number

So the forumula will be something like (60+(10*X)+(15 *Y)) but slightly different for every combination. So I put all the 8 possible combinations in the DB with the according formula and message.


text:
Q: Prove that $f^{-1}\left(U_1\times\cdots\times U_\kappa\right)=\bigcap_{i=1}^\kappa \left(f_i\right)^{-1}\left(U_i\right)$ Im working through Bloch's Proofs and Fundamentals and exercise 4.3.11 is

Let $B$ be a set, let $A_i,\cdots,A_\kappa$ be sets for some
   $k\in\mathbb{N}$ be a subset for all
   $i\in\left\{1,\cdots,\kappa\right\}$ and let $f:B\rightarrow
 A_1\times\cdots\times A_\kappa$ be a function. Prove that
   \begin{align} f^{-1}\left(U_1\times\cdots\times U_\kappa\right)=\bigcap_{i=1}^\kappa
 \left(f_i\right)^{-1}\left(U_i\right), \end{align} where $f_i$ are the
   coordinate functions of $f$.

My (perhaps poor) attempt at a short proof:
proof Suppose $b=f^{-1}\left(U_1\times\cdots\times U_\kappa\right)$ for some $b\in B$. Then \begin{align}f\left(b\right)&=f\left(f^{-1}\left(U_1\times\cdots\times U_\kappa\right)\right)\\&=U_1\times\cdots\times U_\kappa\subseteq A_1\times\cdots\times A_\kappa.\end{align}
Now suppose $b=\bigcap_{i=1}^\kappa\left(f_i\right)^{-1}\left(U_i\right)$ for some $b\in B$. Then \begin{align}f_i\left(b\right)&=f_i\left(\bigcap_{i=1}^\kappa\left(f_i\right)^{-1}\left(U_i\right)\right)\\&=\bigcap_{i=1}^\kappa f_i\left(\left(f_i\right)^{-1}\left(U_i\right)\right)\\&=\bigcap_{i=1}^\kappa U_i\\
&=?\end{align}
I'm not sure if I'm heading in the right direction or if it's wrong altogether. Constructive criticism and hints would be great.

A: Let $X=f^{-1}(U_1\times \dots \times U_k)$ and let $Y=\bigcap_{i=1}^k f_i^{-1}(U_i)$. We will show that $X\subset Y$ and $Y\subset X$.
Let $x\in X$. It means $f(x)\in f(X)\subset U_1\times \dots\times U_k$. Denoting $f(x)=(f_1(x),\dots, f_k(x)), f_i(x)\in A_i$, it means $f_i(x)\in U_i$ for every $i$, implying $x\in f_i^{-1}(U_i)$ for every $i$. So $x$ is in their intersection, meaning $x\in Y$. So $X\subset Y$.
Conversely, let $y\in Y$. Then $y\in f_i^{-1}(U_i)$ for every $i$. This implies $f_i(y)\in U_i$ for every $i$, so $f(y)=(f_1(y),\dots, f_k(y))\in U_1\times \dots \times U_k$. This means $y\in f^{-1}(U_1\times\dots U_k)=X$, so $Y\subset X$ and they're equal.


text:
Q: Firefox undocumented options I came across Firefox
undocumented options
-print-xpcom-dir
-print-xpcom-dirlist
-kill
-killAll
-f
-ftimeout
-fwait
-unsetDefaultMail
-foreground
-new-instance
GTK options

Perhaps someone "in the know" can comment on these or link to a reference? I tried for example firefox -kill and firefox -killAll but they seem to do nothing.

A: Only the first two exist in the source code. In fact they are sort of mummies, only read and not applied anywhere.


text:
Q: Python & Sorting : Sorting Elements In Order Their Subelements in an Array I have an array and it has 4 elements and every element has 3 subelements;
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

As you see, every elements' first subelement is a date. And I want to order these elements with their dates. So I want that output when I enter print(myList);
[['26.03.2019', 'Michelle', '8'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8'], ['03.04.2019', 'Jack', '2']]

How can I do that? Can you give me a solution for this?

A: Convert string date to datetime object and then use sorted
Ex:
import datetime
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

print( sorted(myList, key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y")) )

Output:
[['26.03.2019', 'Michelle', '8'],
 ['01.04.2019', 'George', '2'],
 ['02.04.2019', 'Micheal', '8'],
 ['03.04.2019', 'Jack', '2']]

A: print(myList) would just print your list. You do not want to fiddle with that. What you want to do is sort your list prior to printing. Like so for example:
import datetime

myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]
myList.sort(key=lambda sublist: datetime.datetime.strptime(sublist[0], "%d.%m.%Y"))

print(myList)  # -> [['26.03.2019', 'Michelle', '8'],
               #     ['01.04.2019', 'George', '2'],
               #     ['02.04.2019', 'Micheal', '8'],
               #     ['03.04.2019', 'Jack', '2']]

Note that doing myList.sort(..) permanently changes your list.. If that is not what you want, you can create a new one using sorted as @Rakesh proposes in his answer.

Kudos: the code for the sorting of the dates was taken from here

A: Sort your list on the date string, after changing it to datetime object via strptime
import datetime
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]

myList.sort(key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y"))
print(myList)
#[
#['26.03.2019', 'Michelle', '8'],
#['01.04.2019', 'George', '2'],
#['02.04.2019', #'Micheal', '8'],
#['03.04.2019', 'Jack', '2']
#]


text:
Q: Undefined variable in CodeIgniter view 5 I am learning CodeIgniter and I got stuck on this error.
$categories is fine, but when I want to see $nationality I have an error

Message: Undefined variable: nationality
Filename: pages/add_recipe.php

add_recipes.php
<?print_r($categories);?>
<?print_r($nationality);?>

My controller
class Pages extends CI_Controller
    {
    public function add_recipe($page = 'add_recipe')
            {
                $this->load->helper('url');

                if (!file_exists('application/views/pages/' . $page . '.php')) {
                    show_404();
                }
                $this->load->model('Categories_model');
                $data['categories'] = $this->Categories_model->get_categories();

                $this->load->model('Nationality_model');
                $data['nationality'] = $this->Nationality_model->get_nationality();

                $this->load->view('templates/header');
                $this->load->view('templates/nav');
                $this->load->view('pages/' . $page, $data);
                $this->load->view('templates/sidebar', $data);
                $this->load->view('templates/footer');
            }
    }

Models
public function get_nationality($conditions=null,$limit=null,$offset=0,$order=null){
        if($conditions!=null){
            $this->db->where($conditions);
        }
        if($order!=null) {
            $this->db->order_by($order);
        }
        $query = $this->db->get('nationality',$limit,$offset);
        return $query->result();
    }

public function get_categories($conditions=null,$limit=null,$offset=0,$order=null){
        if($conditions!=null){
            $this->db->where($conditions);
        }
        if($order!=null) {
            $this->db->order_by($order);
        }
        $query = $this->db->get('categories',$limit,$offset);

        foreach($query->result_array() as $row ){
            if(!$row['parent_id']){
                $data[$row['id']][] = $row['title'];
            }else {
                $data[$row['parent_id']]['sub'][$row['id']] = $row['title'];
            }
        }
        return $data;
    }

A: Can you please update the Nationality model function get_nationality with this, try it...

public function get_nationality($conditions=null,$limit=null,$offset=0,$order=null){
        if($conditions!=null){
            $this->db->where($conditions);
        }
        if($order!=null) {
            $this->db->order_by($order);
        }
        $query = $this->db->get('nationality',$limit,$offset);
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
    }

A: it turned out that the page is called from another controller , confused with the names


text:
Q: Firebase Auth: can't delete Firestore documents in promise returned from currentUser.delete() I am using firebase authentication and angularfirestore in my app, and I came across a strange problem. I want to delete a user document in firestore after I delete the user in firebase auth as shown below, but the firestore portion doesnt work.
Edit 2: In the code, this.currentUser is not the same as angularFireAuth.auth.currentUser. It is a local variable I created separately.
return this.angularFireAuth.auth.currentUser.delete().then(() => {
            this.angularFirestore.collection("userData").doc(this.currentUser.email).delete().then(() => {
                this.currentUser = null;
                this.currentUserSubject$.next(this.currentUser);
                this.setAuthenticationDetails({authType: null, rememberMe: false});
                this.storageService.setRememberedUser(null);
            });
        })

However, if I were delete the document from firestore first, and delete the user from firebase auth afterwards, it works.
return this.angularFirestore.collection("userData").doc(this.currentUser.email).delete().then(() => {
            return this.angularFireAuth.auth.currentUser.delete().then(() => {
                this.currentUser = null;
                this.currentUserSubject$.next(this.currentUser);
                this.setAuthenticationDetails({authType: null, rememberMe: false});
                this.storageService.setRememberedUser(null);
            });
        })

Anyone knows why this is happening? They both return promises so i expected the behaviour to be the same.
Edit 1: added catch, but nothing's being printed
return this.angularFireAuth.auth.currentUser.delete().then(() => {
            return this.angularFirestore.collection("userData").doc(this.currentUser.email).delete().then(() => {
                this.currentUser = null;
                this.currentUserSubject$.next(this.currentUser);
                this.setAuthenticationDetails({authType: null, rememberMe: false});
                this.storageService.setRememberedUser(null);
            }, (error) => {
                console.log(error);
            });
        }, (error) => {
            console.log(error);
        })

Edit 3: Security Rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

A: What you're observing makes sense to me.
If you have security rules set up on Firestore that require an authenticated user in order to delete the documents, it makes sense that the documents would fail to delete after removing the user account (as the user is not longer authenticated).  You will definitely want to do everything you can while authenticated before signing out or deleting the user account.
You should add error checking to your code to find out if anything went wrong with the document delete.  Right now, you don't have any catch callbacks on the promise chain, so you'd never know if something went wrong.  I suspect you'll see a "permission denied" type of error on the document delete due to security rules rejecting the request.

A: I think what happened is that after you do auth.currentUser.delete(),  this.currentUser also gets cleared (if it holds auth.currentUser)
So you are just deleting doc("") which didn't fail. But there is no such document, so you won't see anything.


text:
Q: Set the value and display property for jquery's autocomplete source I've got a remote source which does not return id and value or label. How can I use it as a source for jquery's autocomplete plugin?

A: You should pass source a function that makes the AJAX request manually, and then performs some post-processing on the returned data:
source: function(request, response) {
    $.ajax({
        url: url,
        data: request,
        dataType: "json",
        success: function(data) {
            var processedData = $.map(data, function(item) {
                return {
                    value: item._your_property, // Property you want to use for "value"
                    label: item._another_property // Property you want to use for "label"
                }
            });
            response(processedData);
        },
        error: function() {
            response([]);
        }
    });
}

Basically, use $.map to turn the array you get back into an array of objects that the autocomplete widget supports.
For a working example, check out the JSONP example on jQueryUI's demo page.


text:
Q: Running slack bot with python issue - AttributeError: 'WebClient' object has no attribute 'rtm_read' I am following this guide:
At the very end there is a full code snippet which I took, but there is a problem with the last part of it:
if __name__ == "__main__":
    if slack_client.rtm_connect(token = slack_token):
        print("Starter Bot connected and running!")
        # Read bot's user ID by calling Web API method `auth.test`
        starterbot_id = slack_client.api_call("auth.test")["user_id"]
        while True:
            command, channel = parse_bot_commands(slack_client.rtm_read())
            if command:
                handle_command(command, channel)
            time.sleep(RTM_READ_DELAY)
    else:
        print("Connection failed. Exception traceback printed above.")

I am getting
Starter Bot connected and running!
Traceback (most recent call last):
  File "slack2.py", line 67, in <module>
    command, channel = parse_bot_commands(slack_client.rtm_read())

AttributeError: 'WebClient' object has no attribute 'rtm_read'

I've tried reinstalling and instaling slack client as suggested in the first 5 google searches but still having the same issue. My slackclient==2.5.0 and my slack_client = slack.WebClient(token=slack_token).
Any ideas where does the problem lie? Thank you for your suggestions.


text:
Q: Improper nodes and equilibrium points of a linear system For $a$ constant, I want to find all $a$ such that the equilibrium solution for the system below is an improper node.
I don't really know what to do. I know proper and improper nodes occur when eigenvalues are real and repeated, but my book doesn't say how to tell if, in this case, which of the two it is (improper or proper). Also, I don't really understand how a solution can be an improper node at a point (the equilibrium point, as the question says). I thought that what the stability of a system was and the type of critical point depended on the eigenvalues and not on the equilibrium solution.
$x' = \begin{bmatrix}-4 & -3\\3 & a\end{bmatrix} x$


text:
Q: Using EGFs to solve the recurrence relation $a_n=n a_{n-1}+(n+1)!$ I have to solve the recurrence relation
$$a_n = na_{n-1} + (n + 1)!,\qquad a_0 = 1.$$
I am struggling to finish the problem.  I have attached my work.  Can you please help me finish?
$$\begin{eqnarray*}A(x)&=&\sum_{n\geq 0}\frac{a_n}{n!}x^n = a_0+\sum_{n\geq 1}\frac{a_n}{n!}x^n=a_0+\sum_{n\geq 1}\left(na_{n-1}+(n+1)!\right)\frac{x^n}{n!}\\&=&a_0+\sum_{n\geq 1}a_{n-1}\frac{x^n}{(n-1)!}+\sum_{n\geq 1}(n+1)x^n = a_0 + x \sum_{n\geq 1}a_{n-1} \frac{x^{n-1}}{(n-1)!}+\sum_{n\geq 1}(n+1)x^n\\&=&a_0+ x\,A(x)+\underbrace{\sum_{n\geq 1}(n+1)x^n}_{\text{I know that }(n+1)x^n = \frac{d}{dx}x^{n+1}.}\end{eqnarray*}$$

A: By differentiating a geometric series and simplifying we get
$$ a_0+\sum_{n\geq 1}(n+1)x^n = 1+\frac{d}{dx}\left(\frac{x^2}{1-x}\right)=\frac{1}{(1-x)^2},$$
$$ A(x) = x\,A(x)+\frac{1}{(1-x)^2},\qquad A(x)=\frac{1}{(1-x)^3}\stackrel{\text{stars and bars}}{=}\sum_{n\geq 0}\binom{n+2}{2}x^n $$
hence
$$ a_n = \binom{n+2}{2}n! = \color{blue}{\frac{1}{2}(n+2)!}. $$
Let's check it, too:
$$ na_{n-1}+(n+1)! = \frac{1}{2}n(n+1)!+(n+1)! = \frac{n+2}{2}(n+1)!\stackrel{\color{green}{\checkmark}}{=}\frac{1}{2}(n+2)!.$$

A: Next step: What is $\sum_{n=1}^\infty x^{n+1}$?

A: Define the exponential generating function:
$\begin{equation*}
\hat{A}(z) = \sum_{n \ge 0} \frac{a_n}{n!} z^n
\end{equation*}$
Write the recurrence shifted:
$\begin{equation*}
a_{n + 1} = (n + 1) a_n + (n + 2)!
\end{equation*}$
Multiply by $z^n / n!$, sum over $n \ge 0$, recognize some sums:
$\begin{align*}
\sum_{n \ge 0} a_{n + 1} \frac{z^n}{n!}
  &= \sum_{n \ge 0} (n + 1) a_n \frac{z^n}{n!}
       + \sum_{n \ge 0} (n + 2)! \frac{z^n}{n!} \\
\hat{A}'(z)
  &= z \hat{A}'(z) + \hat{A}(z)
       + \sum_{n \ge 0} n (n + 1) z^n
\end{align*}$
Now:
$\begin{align*}
\frac{1}{1 - z}
  &= \sum_{n \ge 0} z^n \\
\frac{d^2}{d z^2} \frac{1}{1 - z}
  &= \frac{2}{(1 - z)^3} \\
  &= \sum_{n \ge 0} (n + 2) (n + 1) z^n
\end{align*}$
thus:
$\begin{equation*}
\sum_{n \ge 0} n (n + 1) z^n
  = \frac{2 z}{(1 - z)^3}
\end{equation*}$
Thus you get the differential equation:
$\begin{equation*}
(1 - z) \hat{A}'(z) = \hat{A}(z) + \frac{2 z}{(1 - z)^3}
\end{equation*}$
This one is linear of the first order. For initial condition you know that $\hat{A}(0) = a_0 = 1$, so (written as partial fractions):
$\begin{equation*}
\hat{A}(z)
  = \frac{2}{1 - z}
      - \frac{2}{(1 - z)^2}
      + \frac{1}{(1 - z)^3}
\end{equation*}$
Expanding by the binomial theorem:
$\begin{align*}
  \hat{A}(z)
    &= \sum_{n \ge 0} 2 z^n
         - \sum_{n \ge 0} 2 \binom{-2}{n} (-z)^n
         + \sum_{n \ge 0} \binom{-3}{n} (-z)^n \\
    &= \sum_{n \ge 0} 2 z^n
         - \sum_{n \ge 0} 2 \binom{n + 1}{1} z^n
         + \sum_{n \ge 0} \binom{n + 2}{2} n^n \\
    &= \sum_{n \ge 0}
         \left(
           2 - 2 (n + 1) + \frac{(n + 2) (n + 1)}{2}
         \right) z^n \\
    &= \sum_{n \ge 0} \frac{n^2 - n + 2}{2} z^n
\end{align*}$
The coefficients are:
$\begin{align*}
a_n
  &= n! [z^n] \hat{A}(z) \\
  &= n! (n^2 - n + 2)
\end{align*}$
But note that this whole mess could be avoided by noting that the recurrence is linear, first order. Dividing through by $n!$ gives a simple recurrence in $a_n / n!$.


text:
Q: Using Quartz Scheduler For Jobs Hello I just started using Quartz Scheduler, I followed the instructions here:
https://dzone.com/articles/quartz-scheduler-configuration-for-web-application
First of all I added the dependencies to my pom.xml file:
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.1</version>
</dependency>

However when I start tomcat my app fails to load and I get this error in my logs:

Exception sending context initialized event to listener instance of
  class [org.quartz.ee.servlet.QuartzInitializerListener]
  java.lang.NoClassDefFoundError: javax/transaction/UserTransaction at
  java.lang.Class.getDeclaredMethods0(Native Method)    at
  java.lang.Class.privateGetDeclaredMethods(Class.java:2701)    at
  java.lang.Class.privateGetPublicMethods(Class.java:2902)  at
  java.lang.Class.getMethods(Class.java:1615)   at
  java.beans.Introspector.getPublicDeclaredMethods(Introspector.java:1336)
    at
  java.beans.Introspector.getTargetMethodInfo(Introspector.java:1197)
    at java.beans.Introspector.getBeanInfo(Introspector.java:426)   at
  java.beans.Introspector.getBeanInfo(Introspector.java:173)    at
  org.quartz.impl.StdSchedulerFactory.setBeanProps(StdSchedulerFactory.java:1393)
    at
  org.quartz.impl.StdSchedulerFactory.instantiate(StdSchedulerFactory.java:1057)
    at
  org.quartz.impl.StdSchedulerFactory.getScheduler(StdSchedulerFactory.java:1519)
    at
  org.quartz.ee.servlet.QuartzInitializerListener.contextInitialized(QuartzInitializerListener.java:171)
    at
  org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5105)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at
  java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at
  org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at
  org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at
  java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at
  org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at
  org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at
  org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at
  org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:671)    at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)   at
  org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493) Caused
  by: java.lang.ClassNotFoundException:
  javax.transaction.UserTransaction     at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275)
    at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104)
    ... 42 more
Dec 21, 2017 9:40:08 AM org.apache.catalina.core.StandardContext
  startInternal SEVERE: One or more listeners failed to start. Full
  details will be found in the appropriate container log file Dec 21,
  2017 9:40:08 AM org.apache.catalina.core.StandardContext startInternal
  SEVERE: Context [/enshika] startup failed due to previous errors Dec
  21, 2017 9:40:08 AM org.apache.coyote.AbstractProtocol start INFO:
  Starting ProtocolHandler ["http-nio-8080"] Dec 21, 2017 9:40:08 AM
  org.apache.coyote.AbstractProtocol start INFO: Starting
  ProtocolHandler ["ajp-nio-8009"] Dec 21, 2017 9:40:08 AM
  org.apache.catalina.startup.Catalina start INFO: Server startup in
  16141 ms

I added this to my web.xml file as instructed:
<listener>
    <listener-class>
        org.quartz.ee.servlet.QuartzInitializerListener
    </listener-class>
</listener>

I created a quartz.properties file and a quartz-jobs.xml file and placed them in my src/main/webapp/WEB-INF/classes directory.


text:
Q: Can I get the N record from set in SQLite I want to get the 2nd (or 3rd, or 4th) record of a selected set using SQLite dialect.
(not the top or the last)

A: The documentation says:

If an expression has an OFFSET clause, then the first M rows are omitted from the result set returned by the SELECT statement and the next N rows are returned.

SELECT *
FROM something
ORDER BY whatever
LIMIT 1 OFFSET 2


text:
Q: Iterate over two strings checking to see if it matches with its pair I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.
I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.
Any help would be greatly appreciated!
''''
    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

A: Since you want to count only the places where there are differences, you can iterate through the minimum length present in both the strings and find out the places where they are different.
In the end, you can add absolute difference of length between seq1 and seq2 and return that value to the main function.
For the logic, all you have to do is apply 4 if conditions to check if character is A,G,C,T and if suitable pair is present in the other string.
public class CountMismatches {

    public static void main(String[] args) {
        {
            String seq1 = "TTCGATGGAGCTGTA";
            String seq2 = "TAGCTAGCTCGGCATGA";

            System.out.println(count_mismatches(seq1, seq2));

        }
    }

    public static int count_mismatches(String seq1, String seq2) {

        int finalCounter = 0;

        for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
            char c1 = seq1.charAt(i);

            char c2 = seq2.charAt(i);

            if (c1 == 'A') {
                if (c2 == 'T')
                    continue;
                else
                    finalCounter++;

            } else if (c1 == 'T') {
                if (c2 == 'A')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'G') {
                if (c2 == 'C')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'C') {
                if (c2 == 'G')
                    continue;
                else
                    finalCounter++;
            }
        }
        return finalCounter + (Math.abs(seq1.length() - seq2.length()));

    }
}

and the output is as follows :
5

A: Make these refactorings:

*

*To make the comparisons easy to code and understand, create a Map whose entires are each pair (both directions)

*Iterate over the Strings up to the length of the shortest one, adding up the number of matching pairs as you go

*The result is the length of the longest String minus the number of pairs

Like this:
public static int count_mismatches(String seq1, String seq2) {
    Map<Character, Character> pairs = Map.of('A', 'T', 'T', 'A', 'G', 'C', 'C', 'G');
    int count = 0;
    for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
        if (pairs.get(seq1.charAt(i)) == seq2.charAt(i)) {
            count++;
        }
    }
    return Math.max(seq1.length(), seq2.length()) - count;
}

See live demo, which returns 5 for your sample input.

A: Good Evening,
Something seems off here, this snippet of code:

     for(int i = 0; i < seq1.length(); i++)
       if (seq1.charAt(i) == seq2.charAt(i)) {
           break; //checks to see if the length of seq1 and seq2 are the same
       }

Does not do what you think it does. This cycle will loop through all characters in sequence1 using i < seq1.length() and for each character that exists in seq1, it will check if said character is equal to the character with the same index in seq2.
This means that a correction is in order:
int countMismatches = 0;

 for(int i = 0; i < seq1.length();i++){
   switch(seq1.charAt(i)){
      case 'A':
         if(seq2.charAt(i) != 'T') countMismatches++;
         break;
   }
 }

Repeat this process for the other letters, and voilá, you should be able to count your mismatches this way.
Do be careful with sequences having different lengths, as if that happens, as soon as you step out of a bound, you will receive an IndexOutOfBoundsException, indicating you've tried to check a character that does not exist.

A: Avoid char
The char type is legacy, essentially broken. As a 16-bit value, char is physically incapable of representing most characters. The char type in your particular case would work. But using char is a bad habit generally, as such code may break when encountering any of about 75,000 characters defined in Unicode.
Code point
Use code point integer numbers instead. A code point is the number assigned to each of the over 140,000 characters defined by the Unicode Consortium.
Here we get an IntStream, a series of int values, one for each character in the input string. Then we collect these integer numbers into an array of int values.
int[] codePoints1 = seq1.codePoints().toArray() ;
int[] codePoints2 = seq2.codePoints().toArray() ;

You said the input strings may be of unequal length. So our two arrays may be jagged, of different lengths. Figure out the size of the shorter array.
int smallerSize = Math.min( codePoints1.length , codePoints2.length ) ;

Keep track of the index number of mismatched rows.
List<Integer> mismatchIndices = new ArrayList <>();

Loop the arrays based on that smaller size.
for( int i = 0 ; i < smallerSize ; i ++ )
{
    if ( isBasePairValid( codePoint first , codePoint second ) )
    {
        …
    } else
    {
        mismatchIndices.add( i ) ;
    }
}

Write an isBasePairValid method
Write the isBasePairValid method, taking two arguments, the code points of the two nucleobase letters.
static int A = "A".codePointAt( 0 ) ;  // Annoying zero-based index counting. So first character is number zero.
static int C = "C".codePointAt( 0 ) ;
static int G = "G".codePointAt( 0 ) ;
static int T = "T".codePointAt( 0 ) ;

if( first == A ) return ( second == T )
else if( first == T ) return ( second == A )
else if( first == C ) return ( second == G )
else if( first == G ) return ( second == C )
else { throw new IllegalStateException( … ) ; }

Count the mismatches.
int countMismatches = mismatchIndices.size() ;

A: The numerical sum of chars T & A and G & C is fixed and unique for legal nucleobase pairs.  So you just need to ensure that the corresponding bases have one of those sums.
String seq1 = "TTCGATGGAGCTGTA";
String seq2 = "TAGCTAGCTCGGCATGA";
System.out.println(count_mismatches(seq1, seq2));

prints
5

*

*find max length to iterate

*establish fixed sums for comparison

*iterate and compare to expected pairing and update count appropriately

public static int count_mismatches(String seq1, String seq2) {
    int len1 = seq1.length();
    int len2 = seq2.length();
    int len = len1;
    if (len1 > len2) {
        len = len2;
    }

    int sumTA = 'T'+'A';
    int sumGC = 'G'+'C';

    int misMatchCount = Math.abs(len1-len2);
    for (int i = 0; i < len; i++) {
        int pair = seq1.charAt(i) + seq2.charAt(i);
        if (pair != sumTA && pair != sumGC) {
            misMatchCount++;
        }
    }
    return misMatchCount;
}

A: First you must find out which string is the shortest in length. Also you need to get the length difference when calculating the shortest string. After that, use that length as a terminating condition in your for loop. You can use booleans to check whether the values are present before incrementing the counter with an if statement.
The absolute value of any number can be obtained by calling the static method abs() from the Math class. Last, just add the mismatchCounts to the absolute value of the length difference in order to obtain the result.
Here is my solution.
public class App {

public static void main(String[] args) throws Exception {
    String seq1 = "TTCGATGGAGCTGTA";
    String seq2 = "TAGCTAGCTCGGCATGA";
    System.out.println(compareStrings(seq1, seq2));
}

public static int compareStrings(String stringOne, String stringTwo) {
    Character A = 'A', T = 'T', G = 'G', C = 'C';
    int mismatchCount = 0;
    int lowestStringLenght = 0;
    int length_one = stringOne.length();
    int length_two = stringTwo.length();
    int lenght_difference = 0;

    if (length_one < length_two) {// string one lenght is greater
        lowestStringLenght = length_one;
        lenght_difference = length_one - length_two;
    } else if (length_one > length_two) {// string two lenght is greater
        lowestStringLenght = length_two;
        lenght_difference = length_two - length_one;
    } else { // lenghts must be equal, use either
        lowestStringLenght = length_one;
        lenght_difference = 0; // there is no difference because they are equal
    }

    for (int i = 0; i < lowestStringLenght; i++) {
        // A matches with T
        // G matches with C
        // evaluate if the values A, T, G, C are present
        boolean A_T_PRESENT = stringOne.charAt(i) == A && stringTwo.charAt(i) == T;
        boolean G_C_PRESENT = stringOne.charAt(i) == G && stringTwo.charAt(i) == C;
        boolean T_A_PRESENT = stringOne.charAt(i) == T && stringTwo.charAt(i) == A;
        boolean C_G_PRESENT = stringOne.charAt(i) == C && stringTwo.charAt(i) == G;
        boolean TWO_EQUAL = stringOne.charAt(i) == stringTwo.charAt(i);

        // characters are equal, increase mismatch counter
        if (TWO_EQUAL) {
            mismatchCount++;
            continue;
        }
        // all booleans evaluated to false, it means that the characters are not proper
        // matches. Increment mismatchCount
        else if (!A_T_PRESENT && !G_C_PRESENT && !T_A_PRESENT && !C_G_PRESENT) {
            mismatchCount++;
            continue;
        } else {
            continue;
        }
    }
    // calculate the sum of the mismatches plus the abs of the lenght difference
    lenght_difference = Math.abs(lenght_difference);
    return mismatchCount + lenght_difference;
}

}


text:
Q: The given path's format is not supported using File.ReadAllText I have a WPF application. I am loading some data from XML file.
I receive an error:
System.NotSupportedException was unhandled
Message: The given path's format is not supported.

on this line:
string html = File.ReadAllText(Advertisement.DescriptionUrl);

the url in the xml it is:
http://mysitetest.com/x/x/Assets/shop/shopdetails/Coffee/image.png

Any ideas how to fix it?

A: File.ReadAllText is meant to take a filename on a file system - not a URL.
You'll need to fetch it with something like WebClient.DownloadString:
string text;
using (WebClient client = new WebClient())
{
    text = client.DownloadString(url);
}
// Now use text

A: That's a web URL, not a file path.
Use a WebClient object to request the resource:
string html;
using (WebClient client = new WebClient()) {
  html = client.DownloadString(Advertisement.DescriptionUrl);
}


text:
Q: Log4j properties for an Webservice/API In my project there are multiple Rest webservices/APIs where I need to have a separate log file for each webservice with appropriate Input request, processing steps and response. All these webservice will call the same jar.
I have tried the below configurations but the common jar processing logs are getting logged in all the api logs.The root package of the common jar is  fr.com.api.common . I have even placed the addivity as false,but it is not working.
log4j.appender.api1Log=org.apache.log4j.RollingFileAppender
log4j.appender.api1Log.File=api1Log.log
log4j.appender.api1Log.Threshold=INFO
log4j.appender.api1Log.Append=true
log4j.appender.api1Log.ImmediateFlush=true
log4j.appender.api1Log.MaxFileSize=50000KB
log4j.appender.api1Log.MaxBackupIndex=10
log4j.appender.api1Log.layout=org.apache.log4j.PatternLayout
log4j.appender.api1Log.layout.ConversionPattern=%d %-5p [%c] (%t) %m%n

log4j.logger.fr.com.api.rest.api1=INFO, api1Log
log4j.additivity.fr.com.api.rest.api1=false

log4j.appender.api2Log=org.apache.log4j.RollingFileAppender
log4j.appender.api2Log.File=api2Log.log
log4j.appender.api2Log.Threshold=INFO
log4j.appender.api2Log.Append=true
log4j.appender.api2Log.ImmediateFlush=true
log4j.appender.api2Log.MaxFileSize=50000KB
log4j.appender.api2Log.MaxBackupIndex=10
log4j.appender.api2Log.layout=org.apache.log4j.PatternLayout
log4j.appender.api2Log.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %-5p %l - %m%n

log4j.logger.fr.com.api.rest.api2=INFO, api2Log
log4j.additivity.fr.com.api.rest.api2=false

log4j.logger.fr.com.api.common=INFO,api2Log,api1Log
log4j.additivity.fr.com.api.common=false


text:
Q: Check select box values and compare them with an input I would like to check if a textfield, newTeamName is already in a list of teamnames stored in a select box. Unfortunately, my code does not work - what's wrong with it? Oh and I have no console problems.
    optionList = [];
    $('#chooseTeam option').each(function() {
        optionList.push($(this).val())
    });
    if (form.newTeamName.value in optionList) {
        $("#text-error").html("Team exists");
        $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
        return false;
    }

Small Update:
Oh and my form.name.value's work fine as they work for other if statements.

A: optionList is an array in used for object properties(or numeric array indices), you can use indexOf to test if a value is in an array
optionList = [];
$('#chooseTeam option').each(function() {
    optionList.push($(this).val())
});
if (optionList.indexOf(form.newTeamName.value) > -1) {
    $("#text-error").html("Team exists");
    $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
    return false;
}

A: Fixed it.
    $('#chooseTeam option').each(function() {
        if (form.newTeamName.value == $(this).val()){
            $("#text-error").html("Team exists");
            $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
            return false;
        }
    });

A: try something like this
  my_array = Array();

  //To find if a value or element exists in an array
  if (my_array.indexOf('find_this_value') != -1)
  {
        alert('Value exists in array.');
  }

 //To find if a value or element DOES NOT exist in an array
 if (my_array.indexOf('find_this_value') == -1)
 {
     alert('Value does not exist in array.');
 }


text:
Q: How do I get the "changes" (commit message) that triggered a Jenkins build? I can go to
http://myjenkins:8080/job/Project/42/changes

and see the commit message that triggered a particular Jenkins build.
However, I want to grab this via REST API or something. I'm not having any luck in search. Is there an easy way to do this?

A: Here's an example of how to get the comment, affected files and commit ID from a Jenkins build:
curl http://jenkins/job/JOB_NAME/BUILD_NUMBER/api/json?pretty=true&tree=changeSet[items[comment,affectedPaths,commitId]]

Here's an explanation of how the tree and depth parameters work.

A: These information can be extracted as well from api
api/json?tree=actions[parameters[*],lastBuiltRevision[branch[*]],tags[*]],artifacts[fileName],changeSet[items[msg,comment,commitId,author[fullName],paths[*]]]

You can always look at the [*] and extract what you want too


text:
Q: How to use multiple controllers and model in codeigniter 3.1.4? I am very new to codeigniter and i am using the version 3.1.4.
I have 2 users in my system and i wanted to use 2 different controllers in the same system, since i felt that using one single controller will have too many functions in it.
what i found as solution was similar to these: How do you use multiple controllers in CodeIgniter?
i dont find any  $route['(:any)']  in my routes file.
Please help me solve this with every step since i am very new.
I want to know how to route it and how to call the function (in both the controllers) in a view page as well as model.
Also i need help in using 2 models.(for that i think i just need to mention the model name while calling the fucntion in model)need advice.

A: You can use routing for all user to redirect to same controller with the routing rule:
$route['users/(:any)'] = "users/index/$1";
for example-
I have two user manager and admin
http://localhost/project/users/manager/create
http://localhost/project/users/admin/create
both request redirect to users/index and now you can get value of the function using
$func = $this->uri->segment(3, 'list');
$user_type = $this->uri->segment(2, 0);
Now use switch case for call a function
switch ($func) {
        case 'create':

            $this->create($user_type);

            return;

        default:

            $this->view($user_type);

            return;

    }