text:
Q: Why is this code not performant? Updating inner text vs replacing entire tags Can someone explain why this code isn't working. If you click the cats quickly, it freezes the browser.
    render: function(catName){
                var cat = controller.getCat(catName);
                var displayArea = $('#displayArea');
                var catImage = $('#catImage');
                var num = $('#numClicks');
                // the two lines below are not performant
                catImage.attr('src', cat.url);
                num.text(cat.numClicks);
                // the three lines below can replace the two lines above and they work. Why?
                //displayArea.empty();
                //displayArea.append('<img src=\"' + cat.url + '\"' + '');
                //displayArea.append('
' + cat.numClicks + '
');
                $("#displayArea img").click(function(){
                    cat.numClicks++;
                    controller.updateClicks(cat.name, cat.numClicks);
                    view.render(cat.name);
                });

    }

Here is the jsfiddle: https://jsfiddle.net/ryangittens/fo2g24dp/1/

A: You're constantly re-hooking the click event. Changing the src of an img doesn't unhook the handlers. (Note that I'm assuming, partially on the basis of the commented-out code, that #catImage is inside #displayArea.)
Just hook click on $("#displayArea img") once.

A: it's because you are adding a click event every time render is called.
try
$("#displayArea img").off('click',).on('click', function(){
  cat.numClicks++;
  controller.updateClicks(cat.name, cat.numClicks);
  view.render(cat.name);
});

This will remove previously bound events


text:
Q: Pymongo GridFS put Type/Attribute errors Put operation causing Type and Attribute errors when using with MongoClient and GridFS. However the same operation passes with mongofiles utility.Appreciate pointers.
Version information
[xxxx@yyyy ~]$ python
Python 3.5.1 (default, Jan 20 2018, 19:04:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.

[xxxx@yyyy ~]$ mongo
MongoDB shell version v3.6.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.1

>>> pymongo.version
'3.6.0'

Code
>>> from pymongo import MongoClient
>>> from gridfs import GridFS
>>> from bson import objectid
>>> db = MongoClient().test
>>> fs = GridFS(db)
>>> with open("/tmp/dictionary") as dictionary:
...   uid = fs.put(dictionary)

Errors
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/local/lib/python3.5/site-packages/gridfs/__init__.py", line 122, in put
    grid_file.write(data)
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 365, in write
    self.__flush_data(to_write)
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 257, in __flush_data
    self._file['md5'].update(data)
TypeError: Unicode-objects must be encoded before hashing

>>> ob = fs.put("hello world")

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 337, in write
    read = data.read
AttributeError: 'str' object has no attribute 'read'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 344, in write
    data = data.encode(self.encoding)
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 235, in __getattr__
    raise AttributeError("GridIn object has no attribute '%s'" % name)
AttributeError: GridIn object has no attribute 'encoding'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/site-packages/gridfs/__init__.py", line 122, in put
    grid_file.write(data)
  File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 347, in write
    "order to write %s" % (text_type.__name__,))
TypeError: must specify an encoding for file in order to write str

Working example with mongofiles
[xxxx@yyyy]$ mongofiles put /tmp/dictionary
018-01-21T07:46:36.914-0800 connected to: localhost
added file: /tmp/dictionary
[xxxx@yyyy]$ mongofiles list
2018-01-21T07:46:40.885-0800    connected to: localhost
/tmp/dictionary 4953699
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
/tmp/dictionary 4953699
[xxxx@yyyy]$ mongo
MongoDB shell version v3.6.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.1
<snip>
> db.fs.files.find()
{ "_id" : ObjectId("5a633e0f50fe750b83159c55"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-20T13:03:11.640Z"), "length" : 4953699, "md5" : "40c0825855792bd20e8a2d515fe9c3e3", "filename" : "/tmp/dictionary" }
{ "_id" : ObjectId("5a649cc350fe75402441749c"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T13:59:31.947Z") }
{ "_id" : ObjectId("5a649f2150fe7540f6fbe2bf"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "uploadDate" : ISODate("2018-01-21T14:09:37.428Z"), "chunkSize" : 261120, "length" : 0 }
{ "_id" : ObjectId("5a64a06850fe7540f6fbe2c0"), "encoding" : "utf-8", "md5" : "d41d8cd98f00b204e9800998ecf8427e", "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T14:15:04.993Z"), "length" : 0 }
{ "_id" : ObjectId("5a64a36b50fe7541e001ab63"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "chunkSize" : 261120, "length" : 0, "uploadDate" : ISODate("2018-01-21T14:27:55.166Z") }
{ "_id" : ObjectId("5a64a6ba50fe754250c7ef4b"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "uploadDate" : ISODate("2018-01-21T14:42:02.976Z"), "chunkSize" : 261120 }
{ "_id" : ObjectId("5a64a70750fe754250c7ef4c"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "uploadDate" : ISODate("2018-01-21T14:43:19.887Z"), "chunkSize" : 261120 }
{ "_id" : ObjectId("5a64a72750fe754250c7ef4d"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "uploadDate" : ISODate("2018-01-21T14:43:51.084Z"), "chunkSize" : 261120 }
{ "_id" : ObjectId("5a64abd850fe754301c8b2d2"), "length" : 0, "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T15:03:52.886Z"), "md5" : "d41d8cd98f00b204e9800998ecf8427e" }
{ "_id" : ObjectId("5a64ac4950fe754301c8b2d3"), "length" : 0, "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T15:05:45.734Z"), "md5" : "d41d8cd98f00b204e9800998ecf8427e" }
{ "_id" : ObjectId("5a64acf750fe754301c8b2d4"), "length" : 0, "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T15:08:39.102Z"), "md5" : "d41d8cd98f00b204e9800998ecf8427e" }
{ "_id" : ObjectId("5a64adc150fe754411469314"), "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T15:12:01.892Z") }
{ "_id" : ObjectId("5a64b1b850fe7544ac42cde3"), "chunkSize" : 261120, "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "uploadDate" : ISODate("2018-01-21T15:28:56.951Z") }
{ "_id" : ObjectId("5a64b2c550fe7544ac42cde4"), "chunkSize" : 261120, "md5" : "d41d8cd98f00b204e9800998ecf8427e", "length" : 0, "uploadDate" : ISODate("2018-01-21T15:33:25.168Z") }
{ "_id" : ObjectId("5a64b5dc50fe7545bbffcbdb"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-01-21T15:46:37.023Z"), "length" : 4953699, "md5" : "40c0825855792bd20e8a2d515fe9c3e3", "filename" : "/tmp/dictionary" }
>

A: gridfs.GridFS.put should be passed a file opened in binary mode.
with open('/tmp/dictionary', 'rb') as dictionary:
    uid = fs.put(dictionary)

You can also pass a str object. However, you'll need to pass an encoding keyword argument.
with open('newtmp') as f:
    uid = fs.put(f.read(), encoding='utf-8')

Note that this is relevant to Python 3 because of the distinctions between str, unicode, bytes

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to register user in devise with active record association? I'm doing experiment using rails and devise_token_auth for authentication. I successfully create a new user for devise_token_auth. I already search this in google or here in this forum but I can't find a solid documention on how going to do it. But if you provide me link. It will more appreciated for a new rails developer to study it. I'm trying to add a profiles with users. In user table I add reference for profile and here is the result.

as you can see there is profile_id added in my user table. In my user model, I have this.
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable
  include DeviseTokenAuth::Concerns::User

  belongs_to :profile
end

and also in my profile model. I have this
class Profile < ApplicationRecord
    has_one :user
end

in my application_controller.rb. I have this
class ApplicationController < ActionController::Base
    include DeviseTokenAuth::Concerns::SetUserByToken
    before_action :configure_permitted_parameters, if: :devise_controller?
    #protect_from_forgery with: :exception

    protected

    def configure_permitted_parameters
        registration_params = [ :name, :city, :email, :password, :password_confirmation, :profile => [:address]]
        devise_parameter_sanitizer.permit(:sign_up, keys: registration_params)
    end
end

I try to use postman for register a user to devise. I have these params to send
{
    "name": "rayn",
    "email": "helloworld.232910@gmail.com",
    "password": "sample123",
    "password_confirmation": "sample123",
    "city": "green",
    "profile": {
        "address": "address here"
    },
    "confirm_success_url": "http://localhost:3000"
}

but when i submit this i got these error
{
    "status": 500,
    "error": "Internal Server Error",
    "exception": "#<ActiveRecord::AssociationTypeMismatch: Profile(#70239077093620) expected, got {\"address\"=>\"address here\"} which is an instance of ActiveSupport::HashWithIndifferentAccess(#47165751411560)>",
    "traces": {

I don't know if my model is correct. I just want to add profile every each user. Correct me for what I did in my code. How can I register a user with profile added?

A: I think you missing accepts_nested_attribute and so active_record is not able to follow what to do with this object - Assuming, there's a column address in Profile:
# user.rb
accepts_nested_attributes_for :profile


text:
Q: SyntaxError: Unexpected end of JSON input while fetchinbg local storage I am suffering from this error, really do not know what to do at this point. Aparently this error is returning because the localstorage is empty.
SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at index.tsx:52:32
    at d (regeneratorRuntime.js:86:17)
    at Generator._invoke (regeneratorRuntime.js:66:24)
    at Generator.next (regeneratorRuntime.js:117:21)
    at r (asyncToGenerator.js:3:20)
    at l (asyncToGenerator.js:25:9)
    at asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21:12

    interface IchartData {
        chain: any,
        address: string,
        dex: any,
    }

    const [ items, setItems ] = useState<IchartData>({chain: '', address: '', dex: ''})

    const getLocalStorage = async () => {
        try {
            const items = await JSON.parse(localStorage?.getItem('ChartData') || "")
            return items
        } catch (error) {
           console.log(error)
        }
    }

    getLocalStorage().then((res) => setItems(res))

I'm using this code to avoid the localStorage to be empty but without success

  useEffect(() => {
    const chartData = {chain: '', address: '', dex: ''}
    if(window.localStorage === undefined){
       localStorage.setItem('ChartData', JSON.stringify(chartData))
    }
  }, [])

A: Your issue is probably because you are passing an empty string if 'ChartData' is undefined in the JSON.parse. Try adding an empty object to a string.
const items = await JSON.parse(localStorage?.getItem('ChartData') || "{}")

A: If you are using a value in your rendering that might be undefined during initial loading of the page (before the useEffect gets executed in your case), you should save a boolean as a loading state and conditionally render your component so that whenever your loading state is true, you render a generic component without data.
You can then set the loading state to false in the final line of your useEffect to cause a re-render, this time with the value loaded in memory and ready.


text:
Q: Errors in scanning variables at runtime I'm beginner to Java programming. I want to solve an expression of the form
(a+20b)+(a+20b+21b)+........+(a+20b+...+2(n-1)b) where you are given "q" queries in the form of a, b  and n for each query, print the expression value corresponding to the given a, b and n values. That means
Sample Input:
20 2 105 3 5
Sample Output:
4072
196
My code was:
import java.util.Scanner;

public class Expression {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int q=in.nextInt();
    for(int i=0;i<q;i++){
        int a = in.nextInt();
        int b = in.nextInt();
        int n = in.nextInt();
    }
    int expr=a+b;                 //ERROR:a cannot be resolved to a variable
    for(int i = 0; i<n;i++)       //ERROR:n cannot be resolved to a variable
        expr+=a+Math.pow(2, i)*b; //ERROR:a and b cannot be resolved to variables
    System.out.print(expr);
    in.close();
}

}

A: The error here is declaring a, b and n in the for loop, that means that when the loop ends the variables too will be lost and the garbage collector will take care of them.
The solution to this is really easy
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int q=in.nextInt();
    int a, b, n;               // Declare outside if you need them outside ;)
    for(int i=0;i<q;i++){
        a = in.nextInt();
        b = in.nextInt();
        n = in.nextInt();
    }
    int expr=a+b;              //ERROR:a cannot be resolved to a variable
    for(int i = 0; i<n;i++) {  //ERROR:n cannot be resolved to a variable
        expr+=a+(2*i)*b;       //ERROR:a and b cannot be resolved to variables
        System.out.print(expr);
    }
    in.close();
}


text:
Q: Class property not set by function I am using MATLAB classes and experience a problem with properties.
The code I call is
theory = ODtheory;
theory.enableDebug(true);
theory.captureRange();

The last function should print out values since the debug is set to true
This is the code for the class:
    function obj = ODtheory(~)
        obj.isDebug = false;
    end

    function obj = enableDebug(obj,value)
        obj.isDebug = value;
    end

But in function range = captureRange(obj) the variable (property) obj.isDebug is still set to false.
function range = captureRange(obj)
   ...
   if obj.isDebug; disp(['FOW: ' num2str(round(FOW,1)) '/mm']); end
end

A: I assume your ODtheory class is a value class, so you need to assign it back to itself to register the change of the object properties.
For example:
theory = ODtheory;
theory = theory.enableDebug(true);
theory.captureRange();

If your captureRange function also modifies object properties, you should also call that with
theory = theory.captureRange();

An alternative would be to make the class a handle class (see the above link)
classdef ODtheory < handle
%  ... class definition here ...
end

Then you could use your original code without the assignments.


text:
Q: Configuring sms centre for kannel I have configured Kannel on windows. I tested it with a fake sms centre and it is working. What I require now is a message centre through which I am able to send sms to mobile. However i am not sure how to get this sms centre information.

*

*Do i need to buy it from some network operators or are there any other free options available?

*On the documentation of kannel, it says I can configure my own mobile to act as sms center. Can anyone tell me how to do so?

*Is it possible to send free sms using kannel by any technique?

A: *

*You can connect to SMSC of mobile operator directly or to SMS gateway.

*Yes, you can use any GSM-modem (or mobile handset) that supports standard AT commands and sending SMS in PDU mode.

*This does not depend on Kannel.

A: You can connect Kannel to the SMSC of an SMS aggregator such as Infobip, Routesms etc.. You would need to register and purchase some credit units in order to send SMS.
You can also connect your GSM modem to Kannel and use it for sending SMS. However none of these is free. The Kannel user guide http://goo.gl/6Iqn4 would help in getting started with setting up the GSM modem.
You can also follow this link http://goo.gl/Y3jDa to have an idea of what configuring a GSM modem is like.


text:
Q: MDX query for hierarchical inclusion/exclusion I'm trying to craft an MDX query to answer a question of the form:
Show me all records in 2008, except those in November, unless they occurred on November 17th.
The query has to be generalized to working with more than just three clauses and should not be date specific.  (I'm asking using dates as an example because it's easy to understand - I'm interested in generalizing my MDX for different hierarchies.
This is the closest I've gotten so far:
SELECT
NON EMPTY {     [Measures].[Session Count] } ON COLUMNS,
NON EMPTY {     ([SessionIDs].[Session ID].Children) } ON ROWS
FROM (
      SELECT
            Union(
                  Descendants([Start Date].[Date].Year.[2008], , LEAVES),
                  Descendants([Start Date].[Date].[Date].&[20081117], , LEAVES)
            )
            -
            Descendants([Start Date].[Date].[Month].&[2008]&[11], , LEAVES)
             ON COLUMNS
      FROM [ADM]
) ;

The problem is that the secondary inclusion (Nov 17, 2008) is eliminated by the exclusion.  I've tried maintaining duplicates in the first union, however Exclude (minus operator) eliminates all copies of members that match.
Edit:
Here is another example to help in understanding what I mean when I ask for a "generalizable" solution.
Consider a mapping application where a user can select to see data in geographical regions of their choice.  They choose these regions by zooming in and out of the map, and selecting/deselecting quadkeys.  Quadkeys map neatly to a hierarchy, which is typically somewhere between 18 and 23 levels deep.
A valid use case would then be:

*

*Select   QK0

*Deselect QK002

*Select   QK0021230

*Deselect QK002123033201 and QK002123033202

In words (and completely fabricating the place names that map to these quadkeys), this would be something like: Show me all of the data for North America but not data for USA unless that data is for New York State, but not in Albany or Glens Falls.
So the same query structure that worked for dates, above, must work for mapping or any other hierarchical set.  It is also worth noting that I'm constructing this MDX on the fly in response to user actions.

A: In the subselect you just need to put this on the column:
{Except([Start Date].[Date].Month.Members, {[Start Date].[Date].[Month].&[2008]&[11]}), [Start Date].[Date].[Date].&[20081117]}

I assumed that you have a Month level. The first part of the expression will return all the monthes but November 2008, then November 17 2008 is added.
EDIT:
For your second example you can write something like this:
Except(all the cities in north america,
        Except(all the cities in USA,
                Except(all the cities in New York state,
                        {Albany , Glens Falls})))

You can retrieve the cities in the North America, in the USA and in New York state with the Descendants function and the LEAVES flag.

A: Not sure to understand what you mean by "working with more than just three clauses... any hierarchy" but here is the set you're requesting :
select

  Hierarchize (
    Union(
      Except(
        Descendants( [Start Date].[Date].[Year].[2008]       , [Start Date].[Date].[Month], SELF ),
        Descendants( [Start Date].[Date].[Month].&[2008]&[11], [Start Date].[Date].[Month], SELF )
      ),
      [Start Date].[Date].[Date].&[20081117]
    )
  )

  on 0 from [ADM]


text:
Q: Story about a student that does not learn like other students This student doesn't learn by rote and is singled out as an individual thinker that can innovate.
He was fearful that he would not pass his exams about repairing space craft but in the end he proves to be much better than the other students.

A: Sounds like a garbled memory of "Profession" (1957) by Isaac Asimov, where the student in question cannot learn a profession direct from the machines, but must learn the old-fashioned way. He eventually learns he has been chosen to create the programs for the teaching machines.
A full version is available to read online here


text:
Q: Internal server error on Azure deployed web app I have deployed an web app to Azure server but when I open my website it gives me error
The page cannot be displayed because an internal server error has occurred.
In browser console the error are
Failed to load resource: the server responded with a status of 500 (URL Rewrite Module Error.)
aspapireact.azurewebsites.net/:1
Failed to load resource: the server responded with a status of 500 (URL Rewrite Module Error.)
I did all the changes required to deploy app on Azure like
connection string in appsettings,
API url in all pages,
Allow access to other resource for Azure SQL DB
connection string in configuration in Azure app service setting
Now I don't know what to do and where should I do changes
this is link for my project on git
https://github.com/rlbrs/ASPAPIReact
this one has all localhost connection but in Azure I have made required changes
Connection string - tcp:aspapireact.database.windows.net,1433;Initial Catalog=ReactTask;Persist Security Info=False;User ID=rlbrs;Password=*****;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
API URL - https://aspapireact.azurewebsites.net/api/Customers
It say URL module error do I have to make changes in my DB Context.cs file
namespace RahulTask1.Model
{
public class DatabaseContext: DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }

    public DbSet<Customer> Customer { get; set; }
    public DbSet<Sale> Sales { get; set; }
    public DbSet<Product> Product { get; set; }
    public DbSet<Store> Store { get; set; }
}
}

Web Config file from azure/server
<?xml version="1.0" encoding="utf-8"?>
  <configuration>
    <location path="." inheritInChildApplications="false">
      <system.webServer>
        <handlers>
          <add name="aspNetCore" path="*" verb="*"
          modules="AspNetCoreModuleV2" resourceType="Unspecified" />
        </handlers>
           <aspNetCore processPath=".\RahulTask1.exe"
           stdoutLogEnabled="false" stdoutLogFile="\\?
           \%home%\LogFiles\stdout" hostingModel="inprocess" />
   </system.webServer>
   </location>
   </configuration>


text:
Q: Problem with rendering jpeg compressed image - Caused by: java.lang.ClassNotFoundException: org.libjpegturbo.turbojpeg.TJException I have a problem with rendering GeoTiff image that is jpeg compressed image. It's size is about 50MB but uncompressed it is 1200MB.
This is what gdalinfo command tells about compressed image:
    Size is 18780, 16918
Coordinate System is:
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0],
    UNIT["degree",0.0174532925199433],
    AUTHORITY["EPSG","4326"]]
Origin = (-77.708530426025376,18.131659398391491)
Pixel Size = (0.000000219372812,-0.000000219372812)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  COMPRESSION=JPEG
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  ( -77.7085304,  18.1316594) ( 77d42'30.71"W, 18d 7'53.97"N)
Lower Left  ( -77.7085304,  18.1279480) ( 77d42'30.71"W, 18d 7'40.61"N)
Upper Right ( -77.7044106,  18.1316594) ( 77d42'15.88"W, 18d 7'53.97"N)
Lower Right ( -77.7044106,  18.1279480) ( 77d42'15.88"W, 18d 7'40.61"N)
Center      ( -77.7064705,  18.1298037) ( 77d42'23.29"W, 18d 7'47.29"N)
Band 1 Block=256x256 Type=Byte, ColorInterp=Red
  NoData Value=0
Band 2 Block=256x256 Type=Byte, ColorInterp=Green
  NoData Value=0
Band 3 Block=256x256 Type=Byte, ColorInterp=Blue
  NoData Value=0
Band 4 Block=256x256 Type=Byte, ColorInterp=Alpha
  NoData Value=0

When I decompress this image, GeoServer has no problem rendering it, but because of saving storage on my server I would like to keep them compressed.
Because of this reason I tried installing libjpegturbo,
but even after successful installation:
WARN [turbojpeg.TurboJPEGMapResponse]-The turbo jpeg encoder is available for usage

I'm getting this error when trying to render this compressed image:
java.lang.NoClassDefFoundError: org/libjpegturbo/turbojpeg/TJException
    at org.libjpegturbo.turbojpeg.TJDecompressor.decompress(Native Method)
    at org.libjpegturbo.turbojpeg.TJDecompressor.decompress(TJDecompressor.java:281)
    at org.libjpegturbo.turbojpeg.TJDecompressor.decompress(TJDecompressor.java:437)
    at it.geosolutions.imageio.plugins.turbojpeg.TurboJpegImageReader.read(TurboJpegImageReader.java:142)
    at javax.imageio.ImageReader.read(ImageReader.java:939)
    at it.geosolutions.imageioimpl.plugins.tiff.TIFFJPEGDecompressor.decodeRaw(TIFFJPEGDecompressor.java:270)
    at it.geosolutions.imageio.plugins.tiff.TIFFDecompressor.decode(TIFFDecompressor.java:2466)
    at it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader.decodeTile(TIFFImageReader.java:1722)
    at it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader.read(TIFFImageReader.java:2021)
    at com.sun.media.jai.imageioimpl.ImageReadOpImage.computeTile(ImageReadOpImage.java:697)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
    at javax.media.jai.OpImage.getTile(OpImage.java:1129)
    at javax.media.jai.PlanarImage.getData(PlanarImage.java:2085)
    at javax.media.jai.PlanarImage.getExtendedData(PlanarImage.java:2440)
    at javax.media.jai.ScaleOpImage.computeTile(ScaleOpImage.java:1101)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
    at javax.media.jai.OpImage.getTile(OpImage.java:1129)
    at javax.media.jai.PlanarImage.copyData(PlanarImage.java:2343)
    at javax.media.jai.PlanarImage.copyExtendedData(PlanarImage.java:2398)
    at javax.media.jai.PlanarImage.getExtendedData(PlanarImage.java:2459)
    at com.sun.media.jai.opimage.MosaicOpImage.computeTile(MosaicOpImage.java:432)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
    at javax.media.jai.OpImage.getTile(OpImage.java:1129)
    at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:962)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
    at javax.media.jai.OpImage.getTile(OpImage.java:1129)
    at javax.media.jai.PlanarImage.cobbleByte(PlanarImage.java:2850)
    at javax.media.jai.PlanarImage.getData(PlanarImage.java:2169)
    at javax.media.jai.RenderedOp.getData(RenderedOp.java:2276)
    at it.geosolutions.imageio.plugins.turbojpeg.TurboJpegImageWriter.write(TurboJpegImageWriter.java:191)
    at org.geoserver.map.turbojpeg.TurboJpegImageWorker.writeTurboJPEG(TurboJpegImageWorker.java:130)
    at org.geoserver.map.turbojpeg.TurboJPEGMapResponse.formatImageOutputStream(TurboJPEGMapResponse.java:103)
    at org.geoserver.wms.map.RenderedImageMapResponse.write(RenderedImageMapResponse.java:123)
    at org.geoserver.ows.Dispatcher.response(Dispatcher.java:991)
    at org.geoserver.ows.Dispatcher.handleRequestInternal(Dispatcher.java:272)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:147)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:75)
    at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:50)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerAnonymousAuthenticationFilter.doFilter(GeoServerAnonymousAuthenticationFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.geoserver.security.filter.GeoServerBasicAuthenticationFilter.doFilter(GeoServerBasicAuthenticationFilter.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1.doFilter(GeoServerSecurityContextPersistenceFilter.java:53)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.geoserver.security.GeoServerSecurityFilterChainProxy.doFilter(GeoServerSecurityFilterChainProxy.java:152)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.LoggingFilter.doFilter(LoggingFilter.java:87)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.GZIPFilter.doFilter(GZIPFilter.java:42)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.SessionDebugFilter.doFilter(SessionDebugFilter.java:48)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.FlushSafeFilter.doFilter(FlushSafeFilter.java:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.libjpegturbo.turbojpeg.TJException
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
    ... 122 more

Is the problem in the fact that the compression ratio is too big?
I tried using LZW compression and it worked, but I'm still getting pretty large images; about 550MB.
EDIT 1:
As Andrea suggested I deleted all jars from WEB-INF/lib that I added when installing libjpeg-turbo.
There were following jars:

*

*gs-libjpeg-turbo-2.10-SNAPSHOT.jar

*imageio-ext-turbojpeg-1.1.13.jar

*imageio-ext-turbojpeg-1.1.15.jar

*turbojpeg-wrapper-1.2.1.1.jar
And now I have the following error:
2016-10-06 11:03:06,187 ERROR [geoserver.ows] -
java.lang.NullPointerException
    at com.sun.media.jai.opimage.BandSelectOpImage.computeTile(BandSelectOpImage.java:135)
    at com.sun.media.jai.opimage.BandSelectOpImage.getTile(BandSelectOpImage.java:144)
    at javax.media.jai.RenderedOp.getTile(RenderedOp.java:2257)
    at com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeOnThread(JPEGImageWriter.java:401)
    at com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(JPEGImageWriter.java:363)
    at org.geotools.image.ImageWorker.writeJPEG(ImageWorker.java:3674)
    at org.geoserver.wms.map.JPEGMapResponse.formatImageOutputStream(JPEGMapResponse.java:70)
    at org.geoserver.wms.map.RenderedImageMapResponse.write(RenderedImageMapResponse.java:123)
    at org.geoserver.ows.Dispatcher.response(Dispatcher.java:991)
    at org.geoserver.ows.Dispatcher.handleRequestInternal(Dispatcher.java:272)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:147)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:28)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:75)
    at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:50)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerAnonymousAuthenticationFilter.doFilter(GeoServerAnonymousAuthenticationFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.geoserver.security.filter.GeoServerBasicAuthenticationFilter.doFilter(GeoServerBasicAuthenticationFilter.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1.doFilter(GeoServerSecurityContextPersistenceFilter.java:53)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.geoserver.security.GeoServerSecurityFilterChainProxy.doFilter(GeoServerSecurityFilterChainProxy.java:152)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.LoggingFilter.doFilter(LoggingFilter.java:87)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.GZIPFilter.doFilter(GZIPFilter.java:42)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.SessionDebugFilter.doFilter(SessionDebugFilter.java:48)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.geoserver.filters.FlushSafeFilter.doFilter(FlushSafeFilter.java:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

This problem occurs both on geoserver 2.9.1 and 2.10 beta
Does anyone have any idea why this happens?

A: GeoServer cannot read RGB-ALPHA JPEG compressed images, they are outside of the base JPEG compression specification.
JPEG cannot compress imagery with alpha channel, by definition, it can only work against Gray and RGB data, see http://www.faqs.org/faqs/jpeg-faq/part1/ and search for "transparency". Looking at the internet, it seems there are some esoteric ways to get alpha in anyways, but GeoServer won't be able to handle them (unless it gets modified to do so, that's always possible of course).

A: Looks like you have a classpath problem with the TurboJPEG extension, maybe you have installed a version that's not compatible with your current version of GeoServer.
The quickest way to solve it is to remove the TurboJPEG extesion.


text:
Q: Best performance for small files on external drive? Which bus has the best read/write performance for small files when used with an external drive? I'd guess eSATA, but the MacBook Pro in question lacks an ExpressCard slot. So it comes down to either USB2 or FireWire 800.
The reason I'm asking is because I want to run Ubuntu Server virtualized (through VirtualBox) on an external hard drive. I'll only use it for web development (Apache, MySQL, PHP) so the reads/writes should mainly be of smaller files.
Thanks!

A: If you use an external HDD, small files doesn't matter. It'll work as a HDD. Only pendrives are slow if you copy small files. When it comes down to pure speed, Firewire wins. If you have an option to use that, go for it.


text:
Q: Decorating a generic interface with Structuremap I have a generic interface, that takes in two generic types. I want to decorate all versions returned, but since I don't know the type when calling EnrichWith, it obviously doesn't compile. I've tried using the EnrichWith overload that passes in the context, thinking maybe I could grab the generic types passed in and call Activator.CreateInstance, but the context doesn't have any useful information on it when debugging and inspecting it.
Here's what I have so far. This is my generic interface:
public interface IServiceOperation<in TRequest, out TResponse> where TResponse : ServiceResult, new()
{
    TResponse PerformService(TRequest validatedRequest);
}

Here's a sample implementation:
public class SignUpService : IServiceOperation<SignUpRequest, SignUpResult>
{
    private readonly IUserRepository _userRepo;

    public SignUpService(IUserRepository userRepo)
    {
        _userRepo = userRepo;
    }

    public SignUpResult PerformService(SignUpRequest validatedRequest)
    {
        var user = Mapper.Map<User>(validatedRequest);

        user.MarkAsLoggedIn();
        user.ChangePassword(validatedRequest.UnhashedPassword);

        using(var transaction = _userRepo.BeginTransaction())
        {
            _userRepo.Save(user);
            transaction.Commit();
        }

        return new SignUpResult();
    }
}

Here is my decorator, that takes in another service as well:
public class ValidateServiceDecorator<TRequest, TResponse> : IServiceOperation<TRequest, TResponse> where TResponse : ServiceResult, new()
{
    private readonly IServiceOperation<TRequest, TResponse> _serviceOperation;
    private readonly IValidationService _validationService;

    public ValidateServiceDecorator(IServiceOperation<TRequest, TResponse> serviceOperation,
        IValidationService validationService)
    {
        _serviceOperation = serviceOperation;
        _validationService = validationService;
    }

    public TResponse PerformService(TRequest request)
    {
        var response = new TResponse();
        var validationResult = _validationService.Validate(request);

        if (!validationResult.IsValid)
        {
            response.ValidationErrors = validationResult.ValidationErrors;
            return response;
        }

        return _serviceOperation.PerformService(request);
    }

Lastly, here is how far I've gotten on my container. This obviously doesn't compile, but the EnrichWith line shows what I'm trying to achieve:
public class StructureMapServiceScanner : Registry
{
    public StructureMapServiceScanner()
    {
        Scan(scanner =>
                {
                    scanner.AssemblyContainingType(typeof (IServiceOperation<,>));
                    scanner.ConnectImplementationsToTypesClosing(typeof (IServiceOperation<,>));
                });

        For(typeof (IServiceOperation<,>))
        .EnrichWith((ioc, original) => new ValidateServiceDecorator(original, ioc.GetInstance<IValidationService>()));
    }
}

And just because this question needed a little more code, here's my test that I'm trying to get to pass:
[TestClass]
public class StructureMapServiceScannerSpecs
{
    [TestMethod]
    public void Test()
    {
        ObjectFactory.Configure(cfg =>
                                    {
                                        cfg.AddRegistry<StructureMapServiceScanner>();
                                        cfg.For<IUserRepository>().Use(new Mock<IUserRepository>().Object);
                                        cfg.For<IValidationService>().Use(new Mock<IValidationService>().Object);
                                    });

        var service = ObjectFactory.GetInstance<IServiceOperation<SignUpRequest, SignUpResult>>();

        service.ShouldNotBeNull();
        service.ShouldBeType<ValidateServiceDecorator<SignUpRequest, SignUpResult>>();
    }
}

I feel like this is something that should be simple, and I'm really missing something with how to use StructureMap. I could create type-specific versions for all combinations of Request and Response types, but obviously that's not desirable. So what am I missing?

A: Was able to figure it out, eventually. I created a RegistrationConvention:
public class ServiceRegistrationConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        var interfacesImplemented = type.GetInterfaces();

        foreach (var interfaceImplemented in interfacesImplemented)
        {
            if (interfaceImplemented.IsGenericType && interfaceImplemented.GetGenericTypeDefinition() == typeof(IServiceOperation<,>))
            {
                var genericParameters = interfaceImplemented.GetGenericArguments();
                var closedValidatorType = typeof(ValidateServiceDecorator<,>).MakeGenericType(genericParameters);

                registry.For(interfaceImplemented)
                    .EnrichWith((context, original) => Activator.CreateInstance(closedValidatorType, original,
                                                                                context.GetInstance<IValidationService>()));
            }
        }
    }
}

A: Here's an approach that still leverages StructureMap's IoC capabilities, allowing additional services to be injected easily into your decorator.  It's not perfect since it assumes you are using the primary container and not a child container, but it will probably work for most scenarios.
public class ServiceRegistrationConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        var handlerInterfaces = (from t in type.GetInterfaces()
                                 where t.IsGenericType &&
                                       t.GetGenericTypeDefinition() == typeof (IHandle<,>)
                                 select t);

        foreach (var handler in handlerInterfaces)
        {
            var decoratorType = typeof (ValidationDecorator<,>).MakeGenericType(handler.GetGenericArguments());

            registry.For(handler)
                .EnrichWith((ctx, orig) => ObjectFactory.With(handler, orig).GetInstance(decoratorType));
        }
    }
}

Ideally, StructureMap's IContext should expose the With method just like IContainer does.  Without that, there's not really a great solution to this problem.


text:
Q: Razor page link ignores route argument I can't believe how frustratingly difficult I'm finding such a simple task.
I want to create a link with a page query argument.
I tried the following:
Character Classifications

And here's the link that is generated.
Character Classifications

I've been Googling for an hour. Can anyone tell me the Razor Pages way to create a link with a query argument?
Also, is there a shortcut if I'm linking to the current page?

A: page is a reserved routing name:

The following keywords are reserved names and can't be used as route names or parameters:

*

*action

*area

*controller

*handler

*page

If you change asp-route-page to something that's not on the list above, e.g. asp-route-pageNumber, it'll work.

A: Kirk's answer is straight to the point but I like to elaborate a bit on why it is not possible and the reason behind the reserved words.
The official reason - as taken from the github issue  - goes like this:

This decision was made in 2007 during the initial release of MVC.
  Route data is something that user code can see, inspect and modify.
  The 'keys' for route values like are frequently typed in user-provided
  routes and calls to apis like Url.Route and Url.Action. It's important
  that any 'key' also be a valid C# identifier to make it easy to use
  with the APIs that accept an anonymously typed object. We made a
  decision not to mangle page because it would be esoteric and weird
  compared to the other route values that are straightforward.

I think one can debate if using "page" as route is esotoric - I personally don't think so - but maybe that's just me.
Since several other people complained about the reserved words problem, especially the fact that you get no warning or sensible error message an github issue was opened to remedy this problem with an analyzer:
Create an Analyzer to prevent usage of reserved keywords in code #4930
Sadly until today (August 2019) the issue has not been closed.
There is some discussion to rework the internals for .NET 3.0 so that there is no need for reserved keywords anymore when it comes to routing.
But as of today - take care you don't use any of the reserved words for your routing.


text:
Q: How to debug before execution stops at nullpointerexception, of a pre-compiled jar file? I would like to debug why an object return null from this line
debug_log = LoggingConfigFileLoader.getLogFilePaths().get("debug.log");

At here: https://github.com/UniversalMediaServer/UniversalMediaServer/blob/master/src/main/java/net/pms/PMS.java#L356
I hope to know what java execution is happening before the exception take place. Unfortunately the .jar is from a big project and may be difficult to build. Especially for me, who knows nothing java. This is on openjdk7, (which the java developer use too). However the code was never before run on FreeBSD.
In the end, I would like to find the true reason / underlying cause for this unhandled exception:
ums4 UMS/ root~# /usr/local/openjdk7/bin/java -Djava.awt.headless=true -classpath /usr/local/share/universal-media-server/ums.jar net.pms.PMS
 18:18:12.424 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is null, name is /root/.config/UMS/UMS.conf
 18:18:12.430 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file /root/.config/UMS/UMS.conf at null: no protocol: /root/.config/UMS/UMS.conf
 18:18:12.431 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the absolute path /root/.config/UMS/UMS.conf
 18:18:12.431 [main] DEBUG o.a.c.c.PropertiesConfiguration - Base path set to file:///root/.config/UMS/UMS.conf
 18:18:12.463 [main] DEBUG o.a.c.c.PropertiesConfiguration - FileName set to UMS.conf
 18:18:12.464 [main] DEBUG o.a.c.c.PropertiesConfiguration - Base path set to /root/.config/UMS
 18:18:12.480 [main] DEBUG n.p.c.ConfigurationReader - Reading cred.path: default: "", current: "/root/.config/UMS/UMS.cred"
 18:18:12.498 [main] INFO  net.pms.PMS - Starting Universal Media Server 4.0.0-a1
 18:18:12.499 [main] INFO  net.pms.PMS - Based on PS3 Media Server by shagrath, copyright 2008-2014
 18:18:12.499 [main] INFO  net.pms.PMS - http://www.universalmediaserver.com
 18:18:12.499 [main] INFO  net.pms.PMS -
 18:18:12.499 [main] INFO  net.pms.PMS - Build: 38318285b (2014-06-02)
 18:18:12.499 [main] INFO  net.pms.PMS - Java: OpenJDK 64-Bit Server VM 1.7.0_60 64-bit by Oracle Corporation
 18:18:12.500 [main] INFO  net.pms.PMS - OS: FreeBSD 64-bit 9.2-RELEASE-p3
 18:18:12.500 [main] INFO  net.pms.PMS - Encoding: US-ASCII
 18:18:12.522 [main] INFO  net.pms.PMS - Memory: 313 MB
 18:18:12.522 [main] INFO  net.pms.PMS - Language: en
 18:18:12.522 [main] INFO  net.pms.PMS -
 18:18:12.523 [main] INFO  net.pms.PMS - Working directory: /var/db/universal-media-server/.config/UMS
 18:18:12.525 [main] INFO  net.pms.PMS - Temp directory: /tmp/universalmediaserver
 18:18:12.525 [main] INFO  net.pms.PMS - Logging config file: internal defaults
 18:18:12.526 [main] INFO  net.pms.PMS -
 18:18:12.526 [main] INFO  net.pms.PMS - Profile directory: /root/.config/UMS
 18:18:12.527 [main] INFO  net.pms.PMS - Profile directory permissions: rw
 18:18:12.527 [main] INFO  net.pms.PMS - Profile path: /root/.config/UMS/UMS.conf
 18:18:12.527 [main] INFO  net.pms.PMS - Profile permissions: rw
 18:18:12.527 [main] INFO  net.pms.PMS - Profile name: ums4
 18:18:12.528 [main] INFO  net.pms.PMS -
 18:18:12.528 [main] INFO  net.pms.PMS - Web conf path: /root/.config/UMS/WEB.conf
 18:18:12.528 [main] INFO  net.pms.PMS - Web conf permissions: file not found
 18:18:12.528 [main] INFO  net.pms.PMS -
 18:18:12.540 [main] ERROR net.pms.PMS - A serious error occurred during PMS init
 java.lang.NullPointerException: null
    at net.pms.newgui.DbgPacker.<init>(DbgPacker.java:40) ~[ums.jar:4.0.0-a1]
    at net.pms.PMS.displayBanner(PMS.java:357) [ums.jar:4.0.0-a1]
    at net.pms.PMS.init(PMS.java:509) [ums.jar:4.0.0-a1]
    at net.pms.PMS.createInstance(PMS.java:1038) [ums.jar:4.0.0-a1]
    at net.pms.PMS.main(PMS.java:1138) [ums.jar:4.0.0-a1]

A: You may try to load the project into IDE and set up "break on exception" breakpoint (e.g. in Eclipse it's in "Run -> Add Java Exception Breakpoint...").
But I believe that this method is suitable only for relatively small projects. For example yesterday I's tired of waiting while a guava's Preconditions check breaks the execution of a long batch processing and I added some logging and re-ran the process w/o debugger. So YMMV.


text:
Q: Remove specific rows from a structure I have a 1x1 structure (EEG) with 42 fields. One of these fields is called event and is a 1x180 structure, with 13 different fields, some of which are strings and some numeric values.
The 4th field of EEG.event is type and it contains strings (i.e. 'preo', 'pred', 'to', 'td', 'po', 'pd').
I would like to keep only those rows of the structure that contain 'preo' in the column EEG.event.type.
My ultimate aim is to create a matrix with all the columns from the structure EEG.event and only the rows with 'preo' in EEG.event.type, plus other columns from other variables.
So far I tried:
S = struct2table(EEG.event);

and it correctly returns a 180x13 table.
However I was not able to select only the rows with 'preo' in type. I tried:
A= S(S.type=='preo', :);

and it gives me an error:
 Undefined operator '==' for input arguments of type 'cell'.

I also tried:
array(strcmp(S(:, 4), 'preo'), :) = [];

and it gives me this error:
Deletion requires an existing variable.

Then I thought that maybe I should have converted the table into matrix, to directly delete rows from the matrix. I tried:
B = cell2mat(S);

but it returns this error:
Error using cell2mat (line 42)
You cannot subscript a table using only one subscript. Table subscripting requires both row and variable subscripts.

Any suggestion or tip is welcome, because I don't know how to continue.
Example list that I have (only 18 rows here):
13  1   201011  'preo'  2502    201 1   1   'y' 'h' 13  13.9230000000000    13
14  1   201011  'pred'  2684    201 1   1   'y' 'h' 14  14.1049999960000    14
15  1   201012  'to'    2707    201 1   2   'y' 'h' 15  14.1280000000000    15
16  1   201012  'td'    2993    201 1   2   'y' 'h' 16  14.4140000000000    16
17  1   201013  'po'    3019    201 1   3   'y' 'h' 17  14.4400000000000    17
18  1   201013  'pd'    3383    201 1   3   'y' 'h' 18  14.8040000000000    18
55  2   61011   'preo'  8213    61  1   1   'y' 'h' 55  53.9000000000000    55
56  2   61011   'pred'  8522    61  1   1   'y' 'h' 56  54.2089999850000    56
57  2   61012   'to'    8547    61  1   2   'y' 'h' 57  54.2340000000000    57
58  2   61012   'td'    8834    61  1   2   'y' 'h' 58  54.5210000000000    58
59  2   61013   'po'    8858    61  1   3   'y' 'h' 59  54.5450000000000    59
60  2   61013   'pd'    9091    61  1   3   'y' 'h' 60  54.7780000000000    60
85  3   124011  'preo'  13924   124 1   1   'y' 'h' 85  82.4550000000000    85
86  3   124011  'pred'  14159   124 1   1   'y' 'h' 86  82.6899999990000    86
87  3   124012  'to'    14181   124 1   2   'y' 'h' 87  82.7120000000000    87
88  3   124012  'td'    14448   124 1   2   'y' 'h' 88  82.9790000000000    88
89  3   124013  'po'    14470   124 1   3   'y' 'h' 89  83.0010000000000    89
90  3   124013  'pd'    14713   124 1   3   'y' 'h' 90  83.2440000000000    90

Example list that I would like to have (from the 18 rows above):
13  1   201011  'preo'  2502    201 1   1   'y' 'h' 13  13.9230000000000    13
55  2   61011   'preo'  8213    61  1   1   'y' 'h' 55  53.9000000000000    55
85  3   124011  'preo'  13924   124 1   1   'y' 'h' 85  82.4550000000000    85

A: I found a solution, I post it here for others with my same issue.
I first create a cell array, and then I delete rows from the cell array. At the moment is the best I can think of.
myCell= struct2cell(EEG.event);
%it results in a 3d cell array, with the fields as first dimension (42) x a singleton dimension as second dimension x the number of the rows as third dimension (180)
new_Cell = permute(myCell,[3,1,2]);
%it deletes the singleton dimension and swap the other 2 dimensions, obtaining 180x42.
[r,c] = find(strcmp(new_Cell,'preo'));
%indices as rows (r) and columns (c) of cells with the string 'preo'
y = new_Cell([r],:);
%It keeps only the rows that you want from the original cell array 'myCell'.


text:
Q: VALIDATION ERROR! Validation check if email address already exist in the db phpmyadmin If the email address is already exists in the database, so the program should not be executed and display the error of "Email already registered", but its not working like that. Code looks fine to me no syntax error. But not working like I want instead of showing me the error of email exist. It executes the form and insert duplicate email address in the mysql database.
Here is the code, Please let me know if anyone can helps.
<?php
include('dbconnection.php');
if(isset($_REQUEST['rSignup'])){
    if(($_REQUEST['rName'] == "") || ($_REQUEST['rEmail'] =="") || ($_REQUEST['rPassword'] =="")){
        $regmsg = '
All Fields are Required
';
    }else{
        $sql = "SELECT r_email FROM requestorlogin_tb WHERE r_email='".$_REQUEST['rEmail']."'";
        $result = $conn->query($sql);
        if($result->num_rows==1){
            $regmsg = '
Email ID Already Registered
';
        } else{
            $rName = $_REQUEST['rName'];
            $rEmail = $_REQUEST['rEmail'];
            $rPassword = $_REQUEST['rPassword'];
            $sql = "INSERT INTO requesterlogin_tb(r_name,r_email,r_password) VALUES('$rName','$rEmail','$rPassword')";
            if($conn->query($sql) == TRUE){
                $regmsg = '
Account Successfully Created
';
            } else{
                $regmsg = '
Unable to Create Account
';
                }
            }
    }
}

?>

A: Please update your query for prevent sql inject and try that :
  $remail=$_REQUEST['rEmail'];
   $stmt = $conn->prepare("SELECT r_email FROM requestorlogin_tb WHERE r_email=?");
    $stmt->bind_param('s', $remail);
    $stmt->execute();
    $result = $stmt->get_result(); // Assign the result to a variable

    if ($result->num_rows > 0) { // Check the number of rows in the MySQLi result object
        echo "exist";

        $stmt->close();
        $conn->close();
    } else {
    ....


text:
Q: Python using .find to search an XML (Attribute Error) I'm getting an error with my code: 'AttributeError:Document instance has no attribute 'find'
Can I use the find function with an xml doc? Eventually I want to find a word and replace it in the xml doc.
from xml.dom.minidom import parse

config_file = parse('/My/File/path/config.xml')

def find_word(p):
        index = p.find('Word')
        return index

print find_word(config_file)

A: After parsing, the XML document is a Document (DOM) object, not a string. Document objects indeed do not have a find() method because you can't just search and replace text in them.
If you know the ID or tag of the element that contains the text you wish to change, you could use getElementById or getElementsByTagName and then search the children of the returned elements for the text. Otherwise, you can recursively walk all the nodes in the document and search each text node for the text you wish to change.
See the DOM documentation for more information on working with the Document Object Model.

A: config_file here is of type xml.dom.minidom.Document and not string. And so, find will not work. Use the getElementsByTagName method on the minidom document to find the elements that you want.
You should be doing the following instead,
>>> from xml.dom.minidom import parseString
>>> my_node = parseString('<root><wordA>word_a_value</wordA></root>');
>>> name = my_node.getElementsByTagName('wordA');
>>> print name[0].firstChild.nodeValue
word_a_value
>>>


text:
Q: Cannot implicity convert type object to system.data.datatable Hi I'm trying to do the following but it throws the error title. As I can fix?
Thanks!!!
public static object conectar(string query)
{
    DataTable Tabla = new DataTable();
    SqlConnection connection = BaseDatos1.getConexion();
    SqlDataAdapter Da = new SqlDataAdapter();
    DataSet Ds = new DataSet();
    Da = new SqlDataAdapter(query, connection);
    Da.FillSchema(Tabla, SchemaType.Source);
    Da.FillLoadOption = LoadOption.PreserveChanges;
    Da.Fill(Tabla);
    BaseDatos1.closeConnection();
    return Tabla;
}

public static string Verificar()
{
    bool functionReturnValue ;
    DataTable Dt1;
    DataTable Dt2;
    DataTable Dt3;
    int j;
    int k;
    int DigitoVerificador;
    int Acum;
    string A;
    string tablas = "";
    string[] table = new string[6];
    string registro = "";
    bool errorEnTablaActual;
    int reg = 0;
    try {
        functionReturnValue = true;
        //Verifico en Base Seguridad
        **Dt1 = conectar("select Tabla from DigitoVerificador");**

A: You get the error because the conectar method returns an object, which you then assign to Dt1, which is a DataTable, and so you get the message that the value cannot be implicitly converted..
You can explicitly cast the return value to a DataTable, as the conectar method never returns null:
Dt1 = (DataTable)conectar("select Tabla from DigitoVerificador");

Alternatively, and probably better, you would change the return type of conectar to DataTable.


text:
Q: How to declare an array of an object statically I'm a long time C programmer but new to C#. I want to declare an object then creating an array of that object filling it statically (I have a very large table to enter). For example
class MyObject {
    int i1;
    string s1;
    double d1;
};

static MyObject[] myO = new MyObject {{1,"1",1.0}, {2,"2",2.0}};

This doesn't work but you get the idea. Any help appreciated.

A: You need to fill the array with object instances.
Create a constructor that takes parameters, then write
new MyObject[] { new MyObject(a, b, c), new MyObject(d, e, f) }

A: You'll have to initialize the array with new object instances.
class MyObject
{
    int i1;
    string s1;
    double d1;

    public MyObject(int i, string s, double d)
    {
        i1 = i;
        s1 = s;
        d1 = d;
    }
};

static MyObject[] myO = new MyObject[] {
    new MyObject(1, "1", 1.0),
    new MyObject(2, "2", 2.0)
};

Unfortunately there is no way to specify custom initializers like they are for arrays of built-in types or dictionaries. For (future) reference of what I mean:
int[] arr = { 1, 2, 3, 4 };
var list = new List<string> { "abc", "def" };
var dict = new Dictionary<string, int> { { "abc", 1 }, { "def", 2 } };

A: You'll need to instantiate the objects in the array:
static MyObject[] myO = new MyObject
{
   new MyObject { i1 = 1, s1 = "1", d1 = 1.0 },
   new MyObject { i1 = 2, s1 = "2", d1 = 2.0 },
};

A: Assuming you have public fields/properties on your class:
class MyObject
{
    public int i1 { get; set; }
    public string s1 { get; set; }
    public double d1 { get; set; }
}   // note: no semicolon needed here

static MyObject[] myO = { new MyObject { i1 = 1, s1 = "1", d1 = 1.0 },
                          new MyObject { i1 = 2, s1 = "2", d1 = 2.0 },
                        };

A: I see a few things wrong here. Firstly all your variables are private. Secondly you are not calling a constructor.
    class MyObject
    {
        public MyObject(int i1, string s1, double d1)
        {
            this.i1 = i1;
            this.s1 = s1;
            this.d1 = d1;
        }

        int i1;
        string s1;
        double d1;
    };

    static MyObject[] objects = new MyObject[] { new MyObject(1, "2", 3), new MyObject(1, "2", 3) };

A: It is exactly what you want but you can achieve your goal with following code:
class MyObject
{
    public int i1;
    public string s1;
    public double d1;
};

static MyObject[] myO = new[]  { new MyObject { i1=1, s1="1", d1=1.0 }, new MyObject { i1=2, s1="2", d1=2.0 } };

A: Try
class Foo
{
  public static Widget[] Widgets { get ; private set ; }
  static Foo()
  {
    Widgets = new Widget[]{ new Widget(1) , new Widget(2) , ... } ;
  }
}


text:
Q: Table Scan Which Columns Are Checked? How exactly does a table scan work?
Here is what I know:

*

*A table scan searches the entire table.

*A clustered index scan searches just whatever column(s) are defined on that index.

Let's pretend we have this scenario:
table_a
Columns: ID, City, Country
I have a clustered index on City.
The query I run is this:
select city
from table_a
where city = 'austin'

Actual questions:

*

*In this scenario would the table scan only look at the city column or would it check the ID, City, and country columns.

*If the table scan only searches one column, is it safe to say that the table scan and the index scan have the same performance?
Edit Part 1:
Google search wrote:

When the table scan occurs SQL Server reads all the rows and columns into memory. When the Index Scan occurs, it's going to read all the rows and only the columns in the index.

A: Look at the execution plan. I would expect a clustered index seek so that only those rows with the specified City are touched. If you search on a non-indexed column, a clustered index scan will be performed so all rows are touched but only qualifying rows are returned.
Only the columns needed by the query will be extracted from the rows and extraneous columns will not be examined during the scan or seek operation.


text:
Q: How do I add blank lines into a Bootstrap Tooltip I am working on a website that has different features a person can order. I would like to put a bootstrap glyphicon next to those features and then when the user rolls over the glyphicon a tooltip would show what was included in those features.
I am having trouble introducing blank lines into the tooltip. I've tried \n  and &#013 (with the pre-wrap command in my css) Here is the portion of my code cooresponding to the tooltip.

2 Printed Sheets

I'm also using the following JQuery command:

How can I put blank lines where the &#013 is. It is worth noting that before I added in the JQuery section the blank lines did work properly, but when I added in the JQuery section the line breaks were removed.

A: Set the html to true and use
 in title attribute, or you can also set the data attribute data-html="true"

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip({
        html:"true"
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Tooltip below

          <a href="#" data-toggle = "tooltip" data-placement = "down" title="One printed sheet can include
1 8 x 10
2 5 x 7
2 4 x 6
4 3.5 x 5
9 wallet photos">
          Tooltip

Demo: https://bootsnipp.com/user/snippets/BE2dE

A: You could add

   title="1st line of text
 2nd line of text"

  title =
        "One printed sheet can include

            1 8 x 10

            2 5 x 7

            2 4 x 6

            4 3.5 x 5

            9 wallet photos"

A: add data-html="true" attribute next to data-toggle and then you can use breakrow tags inside the title anywhere to implement new line


text:
Q: How to call a function after an asynchronous for-loop? I have the following for-loop:
for await (const account of accountCursor) {
  const newAccount = handleAccount(account, migrationService);
  try {
    await migrationService.accountService.create(newAccount);
  } catch (error) {
    console.log('Unable to create account');
    throw Error(error)
  }
}

handleRelatedAccounts();  // call once the for-loop has completed

Once it has finished, I want to call another function. Since it is asynchronous, how can I call the function after the for-loop has finished, not during?

A: Assuming you want to run the function whether or not an error is caught and re-thrown in your loop, you can just wrap the entire loop in a try...finally statement: below is an example. (If not, I'm not sure why you are re-throwing the caught error and what kind of behavior you expect.)
try {
  for await (const account of accountCursor) {
    const newAccount = handleAccount(account, migrationService);
    try {
      await migrationService.accountService.create(newAccount);
    } catch (error) {
      console.log('Unable to create account');
      throw Error(error)
    }
  }
}
finally {
  handleRelatedAccounts();  // call once the for-loop has completed
}

A: You do not have to do anything. handleRelatedAccounts(); always run after the loop. await means it will wait until the premise is finished to do the next code.
Because you throw Error(error), it will stop the execution when there is an exception, handleRelatedAccounts(); will be never hit in this case.


text:
Q: How do I link storyboard and swift in a Mac application? I am trying to IBsegue from the story board to my subclass of NSHostingView. Is this the proper way to link storyboard and SwiftUI for a Mac application?(If not, what is the proper way?) If so, I get four errors in the subclass file:
import Cocoa

class hosty: NSHostingView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }

    @IBSegueAction func termo(_ coder: NSCoder) -> NSViewController? {
        return NSHostingController(coder: coder, rootView: ContentView())
    }
}

Use of undeclared type 'NSHostingView' class hosty: NSHostingView {
Method does not override any method from its superclass override func draw(_ dirtyRect: NSRect) {
'super' members cannot be referenced in a root class super.draw(dirtyRect)
Use of unresolved identifier 'NSHostingController' return NSHostingController(coder: coder, rootView: ContentView())

A: You need import SwiftUI and specify generics type for NSHostingView like below
import Cocoa
import SwiftUI

class hosty: NSHostingView<ContentView> {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }

    @IBSegueAction func termo(_ coder: NSCoder) -> NSViewController? {
        return NSHostingController(coder: coder, rootView: ContentView())
    }
}


text:
Q: How to convert the type for a number of fields in all documents in a collection? After a mongoimport from CSV I ended up with a large number of boolean fields stored as strings.
The string values are all "TRUE", "FALSE" or empty.
How can I convert these fields to proper booleans, for the entire collection?

A: in mogodb shell you can use following statement
db.collection.find({"Fieldname":"TRUE"}).forEach(function(a){a.Fieldname=true; db.collection.save(a)})

db.collection.find({"Fieldname":"False"}).forEach(function(a){a.Fieldname=false; db.collection.save(a)})

this way you can change it from string to Boolean.

A: While you can do something very efficient with $set possibly (although you're changing the nature of the size of data making strings into booleans), I'd go simple in this case.
From the MongoDB console, you could use code like this:
db.myCollection.find().forEach(function(doc) {
      var changed = false;
      // loop through all fields, looking for "TRUE" or "FALSE"
      for(var field in doc) {
         var value = doc[field];
         if (value === "TRUE") {
             doc[field] = true;
             changed = true;
         } else if (value === "FALSE") {
             doc[field] = false;
             changed = true;
         } else if (value === "" || value === null ) {
             // remove empty
             delete doc[field];
             changed = true;
         }
      }
      // continue pattern checking more fields if needed

      if (changed) {    // if something changed, update the entire document
          db.myCollection.update({_id: doc._id}, doc);
      }
});

A: Loop over the different fields that should be converted, and generate a query that contains the current key and the value that should be converted. For each document that matches the query, replace the string value with a boolean value.
var boolean_fields = ['Key_a1','Key_a2', ..,'Key_an'];
var queryFunction = function(key, value){
    var expression = {};
    expression[key] = value;
    return expression;
}

boolean_fields.forEach(function(fieldname, index, array) {

    db.products.find( queryFunction(fieldname, "TRUE") ).forEach( function (match) {
      match[fieldname] = true; // convert field to boolean
      db.products.save(match);
    });

    db.products.find( queryFunction(fieldname, "FALSE") ).forEach( function (match) {
      match[fieldname] = false; // convert field to boolean
      db.products.save(match);
    });

    db.products.find( queryFunction(fieldname, "") ).forEach( function (match) {
      match[fieldname] = null; // remove string type
      db.products.save(match);
    });

});


text:
Q: IntelliJ module settings change when the build.gradle is updated So i have a multi-module project in IntelliJ. I added new modules to the project with dependencies on the existing modules. Using Cucumber as framework and Gradle as the dependency management tool. Every module has a build.gradle.
Example :

automation-rest  --> dependent on 'core' module
(NEW MODULE CREATED) automation-client . --> dependent on 'rest' and 'core'

Whenever i update the build.gradle in automation-client module, the Source and Test Resources setting in the Module Dependencies are changed automatically.
Why does it do that everytime? Is it related to the folders that I am setting as my Source and test resource?

A: This is an intended behavior. To disable it, please go to File | Settings | Build,Execution,Deployment | Build Tools | Gradle, then check "Offline work". Click the "OK" button.Then Rebuild the Project.


text:
Q: turicreate image classifier for unknown types I am using truicreate to create mlmodel for my iOS app. My aim is to classify different furnitures. it is working fine, but I want to identify the unknown type i.e. not included in my dataset. Is is possible to find that?
My Ref: https://www.appcoda.com/core-ml-model-with-python/

A: A classifier can only identify the things that are in your dataset.
It is possible to add an "unknown" category, but you'll have to add all kinds of different objects to this category (non-furniture objects and furniture that isn't in your main dataset).


text:
Q: does class reference itself static anti pattern in prism I have an application and my desing approach look like this:
class Manager
{
    public int State;

    static Manager _instance = null;
    public static Manager Instance
    {
        get { return _instance; }
        set
        {
            if (_instance == value)
                return;
            _instance = value;
        }
    }

    public Manager()
    {
        State = 0;
        Instance=this;
    }
}
class Module1
{
    public void GetState()
    {
        Console.WriteLine(Manager.Instance.State);
    }
}
class Module2
{
    public void GetState()
    {
        Console.WriteLine(Manager.Instance.State);
    }
}
class Module3
{
    public void GetState()
    {
        Console.WriteLine(Manager.Instance.State);
    }
}

Manager class already registered in Bootstrapper like :
 protected override void ConfigureContainer()
 {
       base.ConfigureContainer();
       Container.RegisterType<Manager>(new ContainerControlledLifetimeManager());
 }
 protected override void InitializeModules()
 {
      Manager man= Container.Resolve<Manager>();
 }

Question is do I need to define my manager object as static in its field to be able to reach its state? Or this is anti pattern or bad for performance?


text:
Q: How does `next` predicate work, making two opposite choices? I'm making the Einstein's Riddle, I have a solution but I don't understand how works one specific statement, here is the code:
zebra_owner(Owner) :-
    houses(Hs),
    member(h(Owner,zebra,_,_,_), Hs).

water_drinker(Drinker) :-
    houses(Hs),
    member(h(Drinker,_,_,water,_), Hs).

houses(Hs) :-
    % each house in the list Hs of houses is represented as:
    %      h(Nationality, Pet, Cigarette, Drink, Color)
    length(Hs, 5),                                            %  1
    member(h(english,_,_,_,red), Hs),                         %  2
    member(h(spanish,dog,_,_,_), Hs),                         %  3
    member(h(_,_,_,coffee,green), Hs),                        %  4
    member(h(ukrainian,_,_,tea,_), Hs),                       %  5
    next(h(_,_,_,_,green), h(_,_,_,_,white), Hs),             %  6
    member(h(_,snake,winston,_,_), Hs),                       %  7
    member(h(_,_,kool,_,yellow), Hs),                         %  8
    Hs = [_,_,h(_,_,_,milk,_),_,_],                           %  9
    Hs = [h(norwegian,_,_,_,_)|_],                            % 10
    next(h(_,fox,_,_,_), h(_,_,chesterfield,_,_), Hs),        % 11
    next(h(_,_,kool,_,_), h(_,horse,_,_,_), Hs),              % 12
    member(h(_,_,lucky,juice,_), Hs),                         % 13
    member(h(japanese,_,kent,_,_), Hs),                       % 14
    next(h(norwegian,_,_,_,_), h(_,_,_,_,blue), Hs),          % 15
    member(h(_,_,_,water,_), Hs),       % one of them drinks water
    member(h(_,zebra,_,_,_), Hs).       % one of them owns a zebra

next(A, B, Ls) :- append(_, [A,B|_], Ls).
next(A, B, Ls) :- append(_, [B,A|_], Ls).

The last part where the next is, I understand what it refers to, they are used to say that a house is next to another, but I do not understand how can the same function use two things in reverse to one another, how does Prolog know when to use one or the other? maybe I am forgetting some of this logical language but I don't remember right now and that is my doubt. I want to understand how it works.


text:
Q: Why refreshing my mq patch leaves modified files in the working directory? Please, observe:
PS Z:\dev> hg version
Mercurial Distributed SCM (version 1.9.2)
(see http://mercurial.selenic.com for more information)

Copyright (C) 2005-2011 Matt Mackall and others
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
PS Z:\dev> hg st
A windows\NC\NC.Entities.Agent\DTO\StartTask.cs
A windows\nc\NC.Entities.Agent\DTO\Sample.cs
A windows\nc\NC.Entities.Agent\DTO\StopTask.cs
A windows\nc\NC.Entities.Agent\DTO\Task.cs
A windows\nc\NC.Entities.Agent\Web\Sample.cs
PS Z:\dev> hg qrefresh -v
windows/Common/Shunra.Common.Contract/Shunra.Common.Contract.SL.csproj
windows/NC/NC.Client.SL.Web/Bootstrapper.cs
windows/NC/NC.Entities.Agent.Contract/NC.Entities.Agent.Contract.csproj
windows/NC/NC.Entities.Agent/DTO/AgentInfo.cs
windows/NC/NC.Entities.Agent/DTO/Sample.cs
windows/NC/NC.Entities.Agent/DTO/StopTask.cs
windows/NC/NC.Entities.Agent/DTO/Task.cs
windows/NC/NC.Entities.Agent/NC.Entities.Agent.csproj
windows/NC/NC.Entities.Agent/Web/AgentInfo.DTO.cs
windows/NC/NC.Entities.Agent/Web/AgentInfo.cs
windows/NC/NC.Entities.Agent/Web/Sample.DTO.cs
windows/NC/NC.Entities.Agent/Web/Sample.cs
windows/NC/NC.Entities.Agent/Web/SampleSet.cs
windows/NC/NC.Entities.Agent/Web/StartTask.DTO.cs
windows/NC/NC.Entities.Agent/Web/StartTask.cs
windows/NC/NC.Entities.Agent/Web/StopTask.DTO.cs
windows/NC/NC.Entities.Agent/Web/StopTask.cs
windows/NC/NC.Entities.Server/AgentPortal.AgentEntitiesMarshal.cs
windows/NC/NC.Entities.Server/AgentPortal.PrimitivesMarshal.cs
windows/NC/NC.Entities.Server/AgentPortal.cs
windows/NC/NC.Entities.Server/ExecutionInfoProvider.cs
windows/NC/NC.Entities.Server/Handlers/AgentInfoHandler.cs
windows/NC/NC.Entities.Server/Handlers/SampleHandler.cs
windows/NC/NC.Entities.Server/Handlers/TaskHandler.cs
windows/NC/NC.Entities.Server/IExecutionInfoProvider.PrimitivesMarshal.cs
windows/NC/NC.Entities.Server/IProtocolMetadataResolver.cs
windows/NC/NC.Entities.Server/IProtocolValuesHelper.cs
windows/NC/NC.Entities.Server/Mobile/Web/MobileRunReport.cs
windows/NC/NC.Entities.Server/NC.Entities.Server.csproj
windows/NC/NC.Entities.Server/ProtocolMetadataResolver.cs
windows/NC/NC.Entities.Server/ProtocolValuesHelper.cs
windows/NC/NC.Entities/Rest/ProtoBufSerializer.cs
windows/NC/NC.ProtoBuf/NC.ProtoBuf.SL.csproj
windows/nc/NC.Entities.Agent/DTO/PrimitiveCollection.cs
windows/nc/NC.Entities.Agent/DTO/StartTask.cs
windows/nc/NC.Entities.Agent/DTO/String2String.cs
windows/nc/NC.Entities.Agent/DTO/StringTPair.cs
windows/nc/NC.Entities.Agent/DTO/StringTPairList.cs
PS Z:\dev> hg st
A windows\NC\NC.Entities.Agent\DTO\StartTask.cs
A windows\nc\NC.Entities.Agent\DTO\Sample.cs
A windows\nc\NC.Entities.Agent\DTO\StopTask.cs
A windows\nc\NC.Entities.Agent\DTO\Task.cs
A windows\nc\NC.Entities.Agent\Web\Sample.cs
PS Z:\dev>

What is unclear to me is why hg status returns the same added files after I have refreshed the MQ patch? Note, that these files do appear in the verbose output of hg qrefresh.
What am I supposed to do with it now?
Thanks.

A: The casing of nc and NC directories in the files that were left out is different between hg qrefresh -v output and hg st.
Try forgetting the files reported by hg st and add them with the proper casing.


text:
Q: How can I make K8S find Elasticsearch Kind type? I am following this doc https://www.elastic.co/guide/en/cloud-on-k8s/master/k8s-deploy-elasticsearch.html to deploy Elasticsearch on Kuberenete. I have created the spec file:
apiVersion: elasticsearch.k8s.elastic.co/v1
kind: Elasticsearch
metadata:
  name: quickstart
spec:
  version: 7.15.0
  nodeSets:
  - name: default
    count: 1
    config:
      node.store.allow_mmap: false

But I got an error when run kubectl apply -f es.yml:
 no matches for kind "Elasticsearch" in version "elasticsearch.k8s.elastic.co/v1"

what should I do to solve the issue? It seems K8S doesn't know this kind Elasticsearch. Do I need to install anything?

A: it looks like you may have omitted to install the custom resource definition (CRD) for elastic.
Kubectl version 1.16 and above:
kubectl create -f https://download.elastic.co/downloads/eck/1.8.0/crds.yaml
kubectl apply -f https://download.elastic.co/downloads/eck/1.8.0/operator.yaml

Kubectl version below 1.16:
kubectl create -f https://download.elastic.co/downloads/eck/1.8.0/crds-legacy.yaml
kubectl apply -f https://download.elastic.co/downloads/eck/1.8.0/operator-legacy.y


text:
Q: biglm finds the wrong data.frame to take the data from I am trying to create chunks of my dataset to run biglm. (with fastLm I would need 350Gb of RAM)
My complete dataset is called res. As experiment I drastically decreased the size to 10.000 rows. I want to create chunks to use with biglm.
library(biglm)

formula <- iris$Sepal.Length ~ iris$Sepal.Width

test <- iris[1:10,]

biglm(formula, test)

And somehow, I get the following output:
> test <- iris[1:10,]
> test
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1           5.1         3.5          1.4         0.2  setosa
2           4.9         3.0          1.4         0.2  setosa
3           4.7         3.2          1.3         0.2  setosa
4           4.6         3.1          1.5         0.2  setosa
5           5.0         3.6          1.4         0.2  setosa
6           5.4         3.9          1.7         0.4  setosa
7           4.6         3.4          1.4         0.3  setosa
8           5.0         3.4          1.5         0.2  setosa
9           4.4         2.9          1.4         0.2  setosa
10          4.9         3.1          1.5         0.1  setosa

Above you can see the matrix test contains 10 rows. Yet when running biglm it shows a sample size of 150
> biglm(formula, test)
Large data regression model: biglm(formula, test)
Sample size =  150

Looks like it uses iris instead of test.. how is this possible and how do I get biglm to use chunk1 the way I intend it to?

A: I suspect the following line is to blame:
formula <- iris$Sepal.Length ~ iris$Sepal.Width

where in the formula you explicitly reference the iris dataset. This will cause R to try and find the iris dataset when lm is called, which it finds in the global environment (because of R's scoping rules).
In a formula you normally do not use vectors, but simply the column names:
formula <- Sepal.Length ~ Sepal.Width

This will ensure that the formula contains only the column (or variable) names, which will be found in the data lm is passed. So, lm will use test in stead of iris.


text:
Q: Pandas filtering based on minimum data occurrences across multiple columns I have a dataframe like this
country     data_fingerprint   organization
US          111                Tesco
UK          222                IBM
US          111                Yahoo
PY          333                Tesco
US          111                Boeing
CN          333                TCS
NE          458                Yahoo
UK          678                Tesco

I want those data_fingerprint for where the organisation and country with top 2 counts exists
So if see in organization top 2 occurrences are for Tesco,Yahoo and for country we have US,UK .
So based on that the output of data_fingerprint should be having
data_fingerprint
111
678

What i have tried for organization to exist in my complete dataframe is this
# First find top 2 occurances of organization
nd = df['organization'].value_counts().groupby(level=0, group_keys=False).head(2)
# Then checking if the organization exist in the complete dataframe and filtering those rows
new = df["organization"].isin(nd)

But i am not getting any data here.Once i get data for this I can do it along with country
Can someone please help to get me the output.I have less data so using Pandas

A: You can do
# First find top 2 occurances of organization
nd = df['organization'].value_counts().head(2).index
# Then checking if the organization exist in the complete dataframe and filtering those rows
new = df["organization"].isin(nd)

Output - Only Tesco and Yahoo left
df[new]

    country data_fingerprint    organization
0        US              111           Tesco
2        US              111           Yahoo
3        PY              333           Tesco
6        NE              458           Yahoo
7        UK              678           Tesco

You can do the same for country

A: Annotated code
# find top 2 most occurring country and organization
i1 = df['country'].value_counts().index[:2]
i2 = df['organization'].value_counts().index[:2]

# Create boolean mask to select the rows having top 2 country and org.
mask = df['country'].isin(i1) & df['organization'].isin(i2)

# filter the rows using the mask and drop dupes in data_fingerprint
df.loc[mask, ['data_fingerprint']].drop_duplicates()

Result
   data_fingerprint
0               111
7               678

A: here is one way to do it
df[
    df['organization'].isin(df['organization'].value_counts().head(2).index) &
    df['country'].isin(df['country'].value_counts().head(2).index)
]['data_fingerprint'].unique()

array([111, 678], dtype=int64)