text:
Q: create zapi.item.get from same host I'm having trouble creating the output from Zabbix API tables. I would like to output NAME(hosts), icmpping, icmploss for example.
So I would like something like this:

hostname
ip
ping
loss
status

test.server.1
1.1.1.1
0ms
0%
up

test.server.2
8.8.8.8
1ms
33%
up

For now I have this:
From:
Code example

Thanks for you help

A: The item.get api returns the item's definition (item id, type, key name, interval etc), not the values.
You need to call item.get to get the item id you need, then use the id for a history.get call
Try this script I wrote a while ago:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Get history values for specific items in a time range:

# ./getItemHistoryByName.py -H some-host  -I "ICMP response time" -f "26/6/2018 16:00" -t "27/6/2018 23:59"
ItemID: 77013 - Item: ICMP response time - Key: icmppingsec
1530021641 26/06/2018 16:00:41 Value: 0.1042
1530021701 26/06/2018 16:01:41 Value: 0.0993
1530021762 26/06/2018 16:02:42 Value: 0.1024
1530021822 26/06/2018 16:03:42 Value: 0.0966
[cut]
"""

from zabbix.api import ZabbixAPI
import sys, argparse
import time
import datetime

zabbixServer    = 'http://yourserver/zabbix/'
zabbixUser      = 'someuser'
zabbixPass      = 'somepass'

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('-H', required=True, metavar='Hostname')
    parser.add_argument('-I', required=True, metavar='Item Name')
    parser.add_argument('-f', required=True, metavar='From Timestamp')
    parser.add_argument('-t', required=True, metavar='Till Timestamp')

    args = parser.parse_args()

    zapi = ZabbixAPI(url=zabbixServer, user=zabbixUser, password=zabbixPass)

    fromTimestamp = time.mktime(datetime.datetime.strptime(args.f, "%d/%m/%Y %H:%M").timetuple())
    tillTimestamp = time.mktime(datetime.datetime.strptime(args.t, "%d/%m/%Y %H:%M").timetuple())

    f  = {  'name' : args.I  }
    items = zapi.item.get(filter=f, host=args.H, output='extend' )

    for item in items:
        print "ItemID: {} - Item: {} - Key: {}".format(item['itemid'], item['name'], item['key_'])

        values = zapi.history.get(itemids=item['itemid'], time_from=fromTimestamp, time_till=tillTimestamp, history=item['value_type'])

        for historyValue in values:
            currentDate = datetime.datetime.fromtimestamp(int(historyValue['clock'])).strftime('%d/%m/%Y %H:%M:%S')

            print "{} {} Value: {}".format(historyValue['clock'], currentDate, historyValue['value'])

if __name__ == "__main__":
   main(sys.argv[1:])


text:
Q: Text centered inside the image

  Product

I need it like this and it must be responsiveness too. Can you tell me how to do that?

A: So this question has been asked many times before, here's a snippet from a duplicate I've answered in the past. Hope you can work your own code into the example shown :)

div.counter {
    position: relative;
    display: inline-block;
}
div.counter span {
    position: absolute;
    text-align: center;
    height: 100%;
    width: 100%;
}
div.counter span:before {
   display: inline-block;
   vertical-align: middle;
   height: 100%;
   content: '';
}

    Product

A: below is code what will do that for you.
<!DOCTYPE html>

Center Align Elements

To horizontally center a block element (like div), use margin: auto;

Note: Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.

Just put background-image property inside of div style.

A: One way is to put text as position: absolute;. Another is to put image as background.

#sample-1 img {
  vertical-align: middle;
}

#sample-1 {
  position: relative;
  display: inline-block;
}

#sample-1 span {
  position: absolute;
  left: 5px;
  top: 20px;
}

#sample-2 {
  background-image: url('https://placehold.it/60x60');
  width: 60px;
  height: 60px;
  text-align: center;
}

#sample-2 span {
  line-height: 60px;
}

  Product

  Product 2

A: Try this

 Product

css
.demo {
 width:200px;
 position:relative;
}
.demo span{
 position:absolute;
 left: 0;
 right: 0;
 top: 50%;
 text-align: center;
 margin: -9px auto 0;
}

A: Use below code in this i have seted line height equals to div height and it is responsive also

#imgContainer{
  background: url(https://placehold.it/60x60);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
  text-align: center;
 }
 #imgDesc{
  top: 50%;
        position: relative;
 }

   Works.

A:

.image {
    position:relative;
}

.image img {
  width:300px;
}
.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 100px;
    width: 300px
}

      Text

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't deserialize long in json with Moshi I know it's a very silly question but I am experiencing a strange problem when deserializing with Moshi a Json
My Json has this field:

"version":1499082281552

And in my pojo I have this field:

private long version;

But I always get the error:
W/System.err: com.squareup.moshi.JsonDataException: Expected an int but was 1499082281552 at path $.version

If in my json I have

"version": 1498564139

everything works fine.
UPDATE:
Solved it. Should use a Long instead of long.


text:
Q: Impacts of daily work with gateway-based parental control I am considering to install a gateway-based parental control system at home.
I specifically want to activate ratings-based web filtering.
From the documentation of commercial solutions such as ZyWall USG 20, I understand that the internet users will be attributed a username and password to access the internet.
What bothers me is the impact of this authentication. I was not able to understand when (how frequently and at which stage of the access attempt) the users will have to authenticate.
I am afraid it would be too complex for a 7-8 year old kid, and then reduce its autonomy in accessing internet.
Can anyone help me with a description of the typical authentication use case ?


text:
Q: Not able to use AppCompat v7 switchcompat widget I want to use the Switchcompat in my application. I added the appcompat v7 support library into my project but when i am trying to use the switchcompat in my xml it is giving me following error :
The following classes could not be found:
- android.support.v7.widget.SwitchCompat (Fix Build Path, Edit XML, Create Class)
From the error I am guessing that my project is not able to refer the library project even though i have added the library project as shown :

My XML is as follows:

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
Kindly help what is the issue.Thanks in advance.

A: Try adding android-support-v7-appcompat.jar to build path in library.
You should be getting similar view if you are doing all right!


text:
Q: How to get a list of countries and their cities? Can any one help me to get a list of countries and a list of their cities?
Is there any google Api for getting these lists?

A: Try this once:
ArrayList<String> list=new ArrayList<String>();

String[] locales = Locale.getISOCountries();

for (String countryCode : locales) {

    Locale obj = new Locale("", countryCode);

    System.out.println("Country Name = " + obj.getDisplayCountry());
    list.add(obj.getDisplayCountry());

}

and set the list to adapter.
I think to get cities you have to use webservices.
Refer these links:
1) List of countries and their cities in android
2) Retrieve a list of countries from the android OS


text:
Q: Arch Linux booting in Emergency mode after installing another NVMe SSD So I recently installed another NVMe SSD into my computer and my Arch Linux will no longer boot. Here is the message I receive immediately after booting:

Here is a copy of what my fstab looks like:

In addition note that my system is dual boot with Windows, my boot loader is GRUB.
Also note that after looking into some forums there was an issue with LVM2 a few months ago, see: https://www.reddit.com/r/archlinux/comments/8y2xas/file_system_dependency_not_found_on_boot_yet_the/
I think what has happened is that my boot sequence is looking for root, /home and swap in nvme0n1p*, but installing another NVMe SSD has changed the SSD name of the drive that had Linux on it to nvme1n1p* (Note the change from 0 --> 1)! How do I tell the boot sequence to look in the correct partition on the correct drive?

A: I found a solution to my problem:
The drive and partition that had my arch linux installation on it was renamed from nvme0** to nvme1** after installing an additional nvme drive into my computer. I fixed my issue by simply directly editing my fstab file located in /etc using nano and manually changing the 0 --> 1, so that the boot sequence was actually looking in the correct location for my root, /home and SWAP partitions.
Hopefully this helps someone if they ever encounter this bizarre issue!


text:
Q: Is it possible to edit Reports in Visual Studio 2010? I want to edit the Velocity Report generated with Visual Studio 2010s scrum template.
How can I edit it?

A: You can also refer to this link.. Also you can try to import the report to SSRS environment and try making the changes there.
You can also consider customizing the report you require based on this link.
Hope this helps.

A: I've found a solution for my own issue.
I'm interested in changing the results shown for a Scrum Template report.

*

*Open the report in the "Project Portal" (right click on the Team
project in Visual Studio and select "Show Project Portal".

*Click on the report, e.g. Velocity.

*Click the "properties" tab on the top.

*Click the "Parameters" tab on the left. Some parameters are editable
here, e.g in my case "DoneName". I'm changing this to "Committed"
instead of "Done" so that I can see the items marked as committed.
This parameter can be make editable from the brower ui by selecting
the "Prompt User" checkbox.


text:
Q: How to align next line of the paragraph if the paragraph starts from the title I want to align the paragraph along the green line:

A: Do you want something like this?

.subject, .message {
  float:left;
  display:block;
}
.subject {
  width:35%;
  text-align:right;
}
.message {
  width: 65%;
  padding-top: 10px;
  left: 10px;
  position: relative;
}

Hello this is subject

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Odio ut enim blandit volutpat. Posuere morbi leo urna molestie at elementum eu. Volutpat maecenas volutpat blandit aliquam. Ornare arcu odio ut sem nulla pharetra diam. Quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Egestas sed sed risus pretium quam. Turpis egestas pretium aenean pharetra magna ac placerat vestibulum lectus. Ultrices gravida dictum fusce ut placerat orci nulla pellentesque dignissim. A arcu cursus vitae congue mauris rhoncus. Morbi quis commodo odio aenean sed adipiscing diam. Volutpat lacus laoreet non curabitur gravida arcu ac tortor dignissim.

Eros donec ac odio tempor orci dapibus. Venenatis lectus magna fringilla urna porttitor rhoncus. Mattis ullamcorper velit sed ullamcorper morbi tincidunt. Lectus urna duis convallis convallis tellus id interdum velit laoreet. Eget nunc lobortis mattis aliquam. Ultrices gravida dictum fusce ut placerat orci nulla pellentesque dignissim. Urna molestie at elementum eu facilisis sed odio. Arcu ac tortor dignissim convallis aenean et tortor at. Dictum sit amet justo donec. Tristique et egestas quis ipsum suspendisse ultrices gravida dictum fusce. Cras semper auctor neque vitae. Hendrerit gravida rutrum quisque non tellus orci ac. Dui id ornare arcu odio ut sem. Vitae elementum curabitur vitae nunc. Lectus quam id leo in vitae turpis massa sed. Lobortis scelerisque fermentum dui faucibus in ornare. Dui vivamus arcu felis bibendum ut tristique et egestas. Nisl suscipit adipiscing bibendum est ultricies integer. Pretium aenean pharetra magna ac placerat vestibulum.

In ornare quam viverra orci sagittis eu. Justo nec ultrices dui sapien eget. Mollis aliquam ut porttitor leo. Ullamcorper eget nulla facilisi etiam. Vestibulum sed arcu non odio euismod lacinia at quis. Amet venenatis urna cursus eget nunc scelerisque. Diam ut venenatis tellus in metus vulputate eu scelerisque. Pharetra convallis posuere morbi leo urna molestie at elementum. In nisl nisi scelerisque eu ultrices. Nibh venenatis cras sed felis eget velit. Malesuada proin libero nunc consequat interdum varius sit amet mattis. Pellentesque pulvinar pellentesque habitant morbi tristique senectus et netus et. In ante metus dictum at tempor commodo ullamcorper a. A scelerisque purus semper eget duis at tellus. Gravida in fermentum et sollicitudin ac orci phasellus. Ac feugiat sed lectus vestibulum mattis ullamcorper velit sed. Tellus cras adipiscing enim eu turpis egestas pretium. Nunc id cursus metus aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames.

Volutpat odio facilisis mauris sit amet massa vitae. Id nibh tortor id aliquet lectus proin. Sit amet porttitor eget dolor morbi non arcu risus. Pretium aenean pharetra magna ac. Tempor nec feugiat nisl pretium fusce id velit ut. Turpis egestas pretium aenean pharetra. Accumsan in nisl nisi scelerisque eu ultrices. Eros donec ac odio tempor orci dapibus ultrices in iaculis. Potenti nullam ac tortor vitae purus faucibus. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Feugiat pretium nibh ipsum consequat. Varius duis at consectetur lorem donec massa sapien faucibus et. Lectus quam id leo in vitae.

Id aliquet lectus proin nibh nisl condimentum. Erat imperdiet sed euismod nisi. Tortor consequat id porta nibh venenatis cras. Commodo elit at imperdiet dui accumsan sit amet. Integer vitae justo eget magna fermentum iaculis eu non diam. Ultricies mi eget mauris pharetra et ultrices neque ornare aenean. In eu mi bibendum neque egestas congue quisque egestas diam. Urna nunc id cursus metus aliquam eleifend mi in nulla. Etiam non quam lacus suspendisse faucibus interdum. Malesuada nunc vel risus commodo. Faucibus purus in massa tempor nec feugiat nisl pretium fusce.


text:
Q: Unable to create an object of type 'Context' I'm currently working on a Azure function project In .NET5.
I have the following project structure:

*

*Function.Application

*Function.Domain

*Function.Infrastructure

When I try to generate a migration, I get the following error:

Unable to create an object of type 'Context'. For the different
patterns supported at design time, see
https://go.microsoft.com/fwlink/?linkid=851728

Here Is some code:
Function.Application.Program.cs:
public static void Main()
{
    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(services =>
        {
            var localConnectionString = @"Server=(localdb)\mssqllocaldb;Database=information-services-testdb;Integrated Security=True;";
            services.AddDomain(localConnectionString);
        })
        .Build();

    host.Run();
}

Function.Domain.Injections:
public static class Injections
{
    public static IServiceCollection AddDomain(this IServiceCollection services, string connectionString)
    {
        services.AddPersistence(connectionString);

        return services;
    }
}

Function.Infrastructure.Injections:
public static class Injections
{
    public static IServiceCollection AddPersistence(this IServiceCollection services, string connectionString)
    {
        services.AddDbContext<IContext, Context>(
            options => options.UseSqlServer(connectionString),
            ServiceLifetime.Transient,
            ServiceLifetime.Transient);

        return services;
    }
}

This approach works well when I develop regular ASP.NET Core applications. I just choose which project the Context are In, and then just type Add-migration dbInit, and It works.
Why does this not work when working with Azure Functions?

A: Run below command to find the real problem.
Add-Migration Init -Verbose

There are a lot of ways to help you solve the issues.

*

*Can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

*Find real problem and change your code.
For more details , pls check below post.
Unable to create migrations after upgrading to ASP.NET Core 2.0


text:
Q: Python. Проектирование класса модели Добрый день. Пишу модели для работы с базой данных на Python, использую ORM'ку - SQLAlchemy.
Возник такой вопрос проектирования. Вот к примеру у меня класс Chairman - это класс модели из базы данных, а свойство initials - это уже свойство объекта, который по сути, к БД не относится. То-есть, возможно, тут надо завести еще один класс и в нем писать все методы/свойства этого объекта и просто пробросить ссылку на класс модели, используя композицию/агрегацию.
Но такая ситуация со свойством походу будет единственная.
Вопрос: правильный ли это подход и есть ли смысл тогда заводить отдельный класс в моем случае?
class Chairman(db.Model):
    __tablename__ = "chairmen"

    id = db.Column(INTEGER(unsigned=True), primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    surname = db.Column(db.String(50), nullable=False)
    patronymic = db.Column(db.String(50), nullable=False)

    @property
    def initials(self):
        return "%s.%s.%s%s" % (self.name[0].upper(), self.patronymic[0].upper(), self.surname[0].upper(), self.surname[1:])

    def __repr__(self):
        return "<Chairman(id=%d, surname=%s)>" % (self.id, self.surname)

A: Если, как показано в примере, initials - представляет производное значение из полей модели - не вижу смысла делать для его получения отдельный класс.
Как выше указали - если вам требуется создать свойство, которое будет менять свое "поведение" в зависимости от контекста использования (экземпляр объекта или класс модельки) - то нужно использовать @hybrid_property (ну или для метода -  @hybrid_method)
Например, ваш пример, если его записать, используя гибридное свойство, будет выглядеть как-то так:
class Chairman(db.Model):
    __tablename__ = "chairmen"

    id = db.Column(INTEGER(unsigned=True), primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    surname = db.Column(db.String(50), nullable=False)
    patronymic = db.Column(db.String(50), nullable=False)

    @hybrid_property
    def initials(self):
        return "%s.%s.%s%s" % (self.name[0].upper(), self.patronymic[0].upper(), self.surname[0].upper(), self.surname[1:])

    @initials.expression
    def initials(self):
        return func.concat(
                           func.substr(self.name, 0, 1),
                           func.substr(self.patronymic, 0, 1),
                           func.substr(self.surname, 0, 1),
                           func.substr(self.surname, 1, func.length(self.surname))
                           )

    def __repr__(self):
        return "<Chairman(id=%d, surname=%s)>" % (self.id, self.surname)

Вторая часть гибридного свойства должна возвращать sqlalchemy expression объект.
Что это даст? Вы сможете использовать это короткое свойство в запросах, например можно профильтровать по нему:
session.query(Chairman).filter(Chairman.initials=value)

И вообще, использовать как обычную колонку в большинстве случаев.

A: Ничего разделять в данном случае не нужно. У вас есть абстракция (модель), у этой абстракции есть состояние (поля), которое она может хранить (но не обязана). Так же есть методы, через которые можно менять состояние. Еще можно выделить так называемые свойства - по сути те же поля, только вычисляются динамически.
Какой смысл отделять методы и свойства от модели, и делегировать их кому-то еще?

модели для работы с базой

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

свойство объекта, который по сути, к БД не относится

объект так же не относится к БД, как и класс этого объекта
насчет @hybrid_(method/property) - это просто сахар для выполнения запроса к базе, к вашему вопросу он никакого отношения не имеет. Если вы не собираетесь делать фильтрацию данных в базе по свойству initials, то и @hybrid_property вам не нужен

A: Модель, или точнее класс, который представляет собой запись в БД, это объектное представление используемой бд. То есть структура в которой данные и их поведение были объеденены в единое целое, в отличие от той БД, которой вы пользуетесь, для удобства вашей работы с этими данными.
То есть вы можете писать в привычном вам, ну или требуемым кем-то, объектно-ориентированном стиле.

Вот к примеру у меня класс Chairman - это класс модели из базы данных, а свойство initials - это уже свойство объекта, который по сути, к БД не относится.

Свойство initials, в данном случае, это такое же свойство объекта, как и остальные. Да оно генерируется на основе данных бд, но оно так же является поведением(логикой поведения) вашего объекта. Поэтому вы сделали всё правильно.
Можно даже скрыть все имеющиеся поля, и определить только интерфейс доступа к ним:
class Chairman(db.Model):
    __tablename__ = "chairmen"

    id = db.Column(INTEGER(unsigned=True), primary_key=True)
    _name = db.Column(db.String(50), nullable=False)
    _surname = db.Column(db.String(50), nullable=False)
    _patronymic = db.Column(db.String(50), nullable=False)

    @property
    def initials(self):  # геттер
        return "%s.%s.%s%s" % (self._name[0].upper(),
                               self._patronymic[0].upper(),
                               self._surname[0].upper(), self._surname[1:])

    def set_data(name, surname, patronymic):  # сеттер
        ...

Когда-то смотрел алхимию, помню(очень смутно), что даже можно указывать, чтобы при создании экземпляра модели, всем полям автоматом добавлялся знак подчёркивания.
Ну и, конечно, можно использовать по отношению к модели композицию, агрегацию и другие приёмы объектно-ориентированного проектирования.

A: Могу сказать, что лучше все свойства и методы класса держать в 1 месте. Разделять имеет смысл в том случае, если у вас может быть обьект класса, который не надо хранить в БД, и поэтому некоторые методы для него должны работать по другому.

A: Кроме обычных @property есть ещё @hybrid_property.
Пример из документации:
@hybrid_property
def length(self):
    return self.end - self.start

http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html


text:
Q: ASP.NET MVC - Write less code for route template This is my code:
routes.MapRouteLowercase(
                name: "productadd",
                url: "product/add",
                defaults: new
                {
                    controller = "Product",
                    action = "Add"
                }
                    , namespaces: new[] { "project.Controllers" });
            routes.MapRouteLowercase(
                name: "productlike",
                url: "product/like",
                defaults: new
                {
                    controller = "Product",
                    action = "Like"
                }
                    , namespaces: new[] { "project.Controllers" });
            routes.MapRouteLowercase(
                name: "productshow",
                url: "product/{id}/{seoName}",
                defaults: new
                {
                    controller = "Product",
                    action = "Get",
                    id = UrlParameter.Optional,
                    seoName = UrlParameter.Optional
                }
                    , namespaces: new[] { "project.Controllers" });

I want a solution for writing less codes, actually a template for productshow and another template for product actions

A: you can use Attribute Based Routing in MVC.  This is available by default in MVC5, or can be installed as a NuGet package in MVC4.
With Attribute Based Routing, you can define Attributes on your action methods, rather than magic string matches in the routing table.  You can also perform more advanced type checking, such as minimum and maximum values, and optionally name routes for easy reference in your Razor.
as an example:
[RoutePrefix("product")]
public class ProductController : Controller {

//route /product
[Route]
public ActionResult Index() { ... }

//route /product/add
[Route("add")]
public ActionResult Add() { ... }

//route /product/like
// Like
[Route("like", Name="productlike")]
public ActionResult Like() { ... }

//route /product/{id}/{seoName}
[Route("{id?}/{seoName?}")]
public ActionResult Get(int? id, string seoName) { ... }

}

A: Saman, you can create a default route, like this one below. I'm not sure if that will work with "MapRouteLowercase", you can give it a try.
 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional }
        );

This link has more options if you want.


text:
Q: Genetic Programming and Search Algorithms Is Genetic Programming currently capable of evolving one type of search algorithm into another? For example, has any experiment ever ever bred / mutated BubbleSort from QuickSort (see http://en.wikipedia.org/wiki/Sorting_algorithm)

A: You might want to look at the work of W. Daniel Hillis from the 80s.  He spent a great deal of time creating sorting networks by genetic programming.  While he was more interested in solving the problem of sorting a constant number of objects (16-object sorting networks had been a major academic problem for nearly a decade,) it would be a good idea to be familiar with his work if you're really interested in genetic sorting algorithms.
In the evolution of an algorithm for sorting a list of arbitrary length, you might also want to be familiar with the concept of co-evolution.  I've built a co-evolutionary system before where the point was to have one genetic algorithm evolving sorting algorithms while another GA develops unsorted lists of numbers.  The fitness of the sorter is its accuracy (plus a bonus for fewer comparisons if it is 100% accurate) and the fitness of the list generator is how many errors sort algorithms make in sorting its list.
To answer your specific question of whether bubble had ever been evolved from quick, I would have to say that I would seriously doubt it, unless the programmer's fitness function was both very specific and ill-advised.  Yes, bubble is very simple, so maybe a GP whose fitness function was accuracy plus program size would eventually find bubble.  However, why would a programmer select size instead of number of comparisons as a fitness function when it is the latter that determines runtime?
By asking if GP can evolve one algorithm into another, I'm wondering if you're entirely clear on what GP is.  Ideally, each unique chromosome defines a unique sort.  A population of 200 chromosomes represents 200 different algorithms.  Yes, quick and bubble may be in there somewhere, but so are 198 other, potentially unnamed, methods.

A: There's no reason why GP couldn't evolve e.g. either type of algorithm. I'm not sure that it really makes sense to think of evolving one "into" the other. GP will simply evolve a program that comes ever-closer to a fitness function you define.
If your fitness function only looks at sort correctness (and assuming you have the proper building blocks for your GP to use) then it could very well evolve both BubbleSort and QuickSort. If you also include efficiency as a measure of fitness, then that might influence which of these would be determined as a better solution.
You could seed the GP with e.g. QuickSort and if you had an appropriate fitness function it certainly could eventually come up with BubbleSort - but it could come up with anything else that is fitter than QuickSort as well.
Now how long it takes the GP engine to do this evolution is another question...

A: I'm not aware of one, and the particular direction you're suggesting in your example seems unlikely; it would take a sort of perverse fitness function, since bubble sort is in most measures worse than quicksort.  It's not inconceivable that this could happen, but in general once you've got a well-understood algorithm, it's already pretty fit -- going to another one probably requires passing through some worse choices.
Being trapped in local minima isn't an unknown problem for most search strategies.


text:
Q: How to get value from upcomming row if condition is met? I searched in google and SO but could not find any answer to my question.
I try to get a value from the first upcomming row if the condition is met.
Example:
Pupil   participation   bonus
  2           55          6
  2           33          3
  2           88          9
  2            0          -100
  2           44          4
  2           66          7
  2            0          -33

to
Pupil   participation   bonus   bonusAtNoParti   sumBonusTillParticipation=0
  2           55          6          -94                    6+3+9 = 18
  2           33          3          -97                      3+9 = 12
  2           88          9          -91                       9
  2            0          -100        0                        0
  2           44          4          -29                     4+7=11
  2           66          7          -26                       7
  2            0          -33         0                        0

So I need to do this:
Iterate through the dataframe and check next rows till participation equals to 0 and get the bonus from that line and add the bonus from the current line and write it to bonusAtNoPati.
My problem here is the "check next rows till participation equals to 0 and get the bonus from that line"
I know how to Iterate through the whole list but not after the current point(row)
I would need to do this process to the whole list where i can get any random participation value in random order.
Has anyone any idea how to realize it?
Edit, I also added another column("sumBonusTillParticipation=0", only sum value is required) which is even harder to realize. R is such a hard to learn language =(

A: you can use which to get which row number participation is 0.
df <- read.table(text = 'Pupil   participation   bonus
             2           55          6
             2           33          3
             2           88          9
             2            0          -100
             2           44          4
             2           66          7
             2            0          -33', header = T)

index <- c(0, which(df$participation == 0))
diffs <- diff(index)
df$tp <- rep(df$bonus[index], times = diffs)
df$bonusAtNoParti <- df$bonus + df$tp
df$bonusAtNoParti[index] <- 0
df$tp <- NULL

     Pupil participation bonus bonusAtNoParti
 1     2            55     6            -94
 2     2            33     3            -97
 3     2            88     9            -91
 4     2             0  -100              0
 5     2            44     4            -29
 6     2            66     7            -26
 7     2             0   -33              0


text:
Q: Rails ransack filter on multiple instances I have a poll app that allows to create polls as draft or published. Admin can see all. Users only published ones.
Then I am using ransack to filter.
This is my controller:
    @q = Poll.includes(:division).includes(:vote_options).ransack(params[:q])
    @p = Poll.where(published: '1').includes(:division).includes(:vote_options).ransack(params[:p])
    @polls = @q.result.order(:sort)
    @published_polls = @p.result.order(:sort)
    @display_polls = current_user.admin_role? ? @polls : @published_polls

As I needed to create two instances of Poll I added @p beside @q. And I'm not sure this is the right approach.
In my view I have
<% @display_polls.each_with_sortable_id do |poll, sortable_id| %>

For ransack filters I have:
<%= search_form_for @q, url: polls_path do |f| %>

Published and unpublished items show correctly as expected. But ransack filters won't work.
How can I make filters work again?

A: I think it might be because your search_form_for is only searching on @q. I think this might be a better approach in your controller:
if current_user.admin_role?
    @q = Poll.includes(:division, :vote_options).ransack(params[:q])
else
    @q = Poll.where(published: '1').includes(:division, :vote_options).ransack(params[:q])
end

@polls = @q.result.order(:sort)


text:
Q: Changing Locale at runtime not effecting fragments When user changes language i execute following code,it works fine for the present fragment in the activity, but if i go to other fragment, it partially updates the language, some strings gets updated and shows old language, and most importantly the date does not changes in inner fragments,and other activities.
I tested this in nougat, marshmallow and oreo, and its happening in all of OS.
When user changes the language i execute following.
 LocaleHelper.setLocale(getApplicationContext(), language);
 recreate();

LocalHelper
public static Context setLocale(Context context, String language) {
        persist(context, language);

        Log.d("LocaleSet", language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

Method for post marshmallow OS.
   @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);

        return context.createConfigurationContext(configuration);
    }

Pre Nougat
@SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }

In each activity, i execute following code.
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.onAttach(base, LocaleHelper.getLanguage(base)));
}

Mainfest
<application
        android:name=".GlobalApplication"
        android:allowBackup="false"
        android:icon="@mipmap/app_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:windowSoftInputMode="adjustPan"
        tools:replace="android:allowBackup">

        <activity
            android:name=".activities.homeactivity.HomeActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:configChanges="locale"
            android:theme="@style/AppTheme.NoActionBar" />

        <activity
            android:name=".activities.profilepageactivity.ProfilePageActivity"
            android:label="@string/title_activity_profile_page"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" />

A: I assume that you are using this approach. Where its not suggested any change in the AndroidManifest.xml so the android:configChanges="locale" may cause the misbehavior you defined.
For the date formating you should take into consideration that your application is not using the Locale.getDefault() but something different that is defined by the user and your LocaleHelper mechanism.
Some extra details about config change
The android:configChanges means you don't want the system to recreate your activity when one of the provided attribute happens. In your case the locale.
In terms of development with that approach in order to properly handle this option in the manifest you have to implement the
@Override
public void onConfigurationChanged(Configuration newConfig) {
  // refresh your views here
  super.onConfigurationChanged(newConfig);
}

and then perform your own handling. Something that you didn't required in your case.

A: Application class which extended in the manifest file.
package com.example.languageapplication;

import android.content.Context;

public class Application extends android.app.Application {

    private static Application applicationInstance;

    public static synchronized Application getInstance() {
        return applicationInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        applicationInstance = this;
    }

    public void initAppLanguage(Context context) {
        LocaleUtils.initialize(context, LocaleUtils.getSelectedLanguageId());
    }

}

Locale utils class for set language in shared preferences and update configuration for set language
public class LocaleUtils {

    public static final String ENGLISH = "en";
    public static final String FRENCH = "fr";
    public static final String SPANISH = "es";

    public static void initialize(Context context, @LocaleDef String defaultLanguage) {
        setLocale(context, defaultLanguage);
    }

    public static boolean setLocale(Context context, @LocaleDef String language) {
        return updateResources(context, language);
    }

    private static boolean updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        context.createConfigurationContext(configuration);
        configuration.locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return true;
    }

    @Retention(RetentionPolicy.SOURCE)
    @StringDef({ENGLISH, FRENCH, SPANISH})
    public @interface LocaleDef {
        String[] SUPPORTED_LOCALES = {ENGLISH, FRENCH, SPANISH};
    }

    private static SharedPreferences getDefaultSharedPreference(Context context) {
        if (PreferenceManager.getDefaultSharedPreferences(Application.getInstance().getApplicationContext()) != null)
            return PreferenceManager.getDefaultSharedPreferences(Application.getInstance().getApplicationContext());
        else
            return null;
    }

    public static void setSelectedLanguageId(String id){
        final SharedPreferences prefs = getDefaultSharedPreference(Application.getInstance().getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("app_language_id", id);
        editor.apply();
    }

    public static String getSelectedLanguageId(){
        return getDefaultSharedPreference(Application.getInstance().getApplicationContext())
                .getString("app_language_id", "en");
    }
}

set Language on click of a button in another activity and restart launcher activity
public class setLaunguageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

    }

    public void setEnglish(View view) {
        LocaleUtils.setSelectedLanguageId("en");
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        startActivity(i);

    }

    public void setFrance(View view) {
        LocaleUtils.setSelectedLanguageId("fr");
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        startActivity(i);

    }
}

Initialize Application class in the main activity like this
public class MainActivity extends AppCompatActivity {

    TextView textInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Application.getInstance().initAppLanguage(this);
        setContentView(R.layout.activity_main);
}

this code is working for me


text:
Q: Group by with null values Trying to group by the result bellow:
+-------------+------+
| ID | Coln1 | Coln2 |
+-------------+------+
| 10 |     A |  NULL |
| 10 |  NULL |     X |
| 15 |     B |  NULL |
| 15 |  NULL |     Y |
| 20 |     C |  NULL |
| 20 |  NULL |     Z |
+--------------+-----+

With the following select:
SELECT * FROM
(
SELECT
    DB1.dbo.TABLE1.id AS ID,
    DB1.dbo.TABLE1.Coln1 AS Coln1,
    NULL AS Coln2
FROM
    DB1.dbo.TABLE1
UNION
SELECT
    DB2.dbo.TABLE2.id AS ID,
    NULL AS Coln1,
    DB2.dbo.TABLE2.Coln2 AS Coln2
FROM
    DB2.dbo.TABLE2
) AS A
GROUP BY
    ID,
    Coln1,
    Coln2
ORDER BY ID ASC

Expecting this:
+-------------+------+
| ID | Coln1 | Coln2 |
+-------------+------+
| 10 |     A |     X |
| 15 |     B |     Y |
| 20 |     C |     Z |
+--------------+-----+

With no luck. Tried to use some HAVING with no luck neither. Thanks for any information on this.

A: An aggregate function should help you. Aggregate function will eliminate the NULL values.Try this
SELECT ID, max(Coln1), max(Coln2)
FROM tablename
GROUP BY
ID

Update your query like this..
SELECT ID,
       Max(Coln1),
       Max(Coln2)
FROM   (SELECT DB1.dbo.TABLE1.id    AS ID,
               DB1.dbo.TABLE1.Coln1 AS Coln1,
               NULL                 AS Coln2
        FROM   DB1.dbo.TABLE1
        UNION
        SELECT DB2.dbo.TABLE2.id    AS ID,
               NULL                 AS Coln1,
               DB2.dbo.TABLE2.Coln2 AS Coln2
        FROM   DB2.dbo.TABLE2) AS A
GROUP  BY ID
ORDER  BY ID ASC

A: You just have to change
Max function is used to select highest values & this function is very helful for avoiding for NULL values
SELECT ID, max(Coln1), max(Coln2)
FROM ID, Coln1, Coln2
GROUP BY
ID

A: Why are you doing a union?
SELECT
    t1.id AS ID,
    t1.Coln1 AS Coln1,
    t2.Coln2 AS Coln2

FROM
    DB1.dbo.TABLE1 t1

    JOIN DB2.dbo.TABLE2 t2
         ON t1.id = t2.id


text:
Q: Calculating AUC on Random Forest Model in R I'm trying to calculate AUC on my two models Random Forest and Naive Bayes
but getting the same error ""$ operator is invalid for atomic vectors" .
Would you have some ideas please ?
Background: Target variable "Diagnosis" is non-numerical with values B and M
Here is sample code for RF model
fitControl <- trainControl(method="cv",number = 5,preProcOptions = list(thresh = 0.4),classProbs = TRUE,summaryFunction = twoClassSummary)

wdbc_model_rf <- train(Diagnosis~.,train_wdbc,method="ranger",metric="ROC",preProcess = c('center', 'scale'),trControl=fitControl)

A: Below is an example of R code that works. Please note: your interest in ROC implies there are only two classes.
Predict <- function(class_obj, newdata, Param) {

if(Param$method == 'RF') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'prob')
} else if(Param$method == 'GBM') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'response', n.trees = Param$n.trees)[,,1]
} else if(Param$method == 'SVM') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'probabilities')
} else if(Param$method == 'logit') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'response')
    Predicted_Probs         <- cbind(1 - Predicted_Probs, Predicted_Probs)
} else {
    cat('\nPredict(): unknown classification method.')
}

Predicted_Probs[,2]

}

@@@
AUC <- function(Truth, Predicted_Probs) {

###########################################################################################################
# SETTINGS

d_Prob              <- 0.01

###########################################################################################################
# CALCULATIONS

Prob_Grid               <- seq(1, 0, -d_Prob)
NP                  <- length(Prob_Grid)
True_Positive_Rate      <- c()
False_Positive_Rate     <- c()

for(Prob_Threshold in Prob_Grid) {
    Forecast                <- as.factor( c(0, 1, 1 * (Predicted_Probs >= Prob_Threshold)) )
    levels(Forecast)            <- c('0', '1')
    Forecast                <- Forecast[-c(1,2)]
    Table               <- xtabs(~Truth + Forecast)
    False_Positive_Rate     <- c(False_Positive_Rate, Table[1,2] / (Table[1,1] + Table[1,2]))
    True_Positive_Rate      <- c(True_Positive_Rate, Table[2,2] / (Table[2,1] + Table[2,2]))
}

AUC                 <- 0

for(i in 2:NP) {
    AUC                 <- AUC + True_Positive_Rate[i] * (False_Positive_Rate[i] - False_Positive_Rate[i-1])
}

AUC

}

Please note: the code is quite generic and can be applied to many methods, like support vector machines, gradient boosting, random forests, etc. Hopefully, it is straightforward to modify the code to your needs.


text:
Q: Finding the dimension of subspace span(S) Problem:
Consider the set of vectors $S= \{a_1,a_2,a_3,a_4\}$ where
$a_1= (6,4,1,-1,2)$
$a_2 = (1,0,2,3,-4)$
$a_3= (1,4,-9,-16,22)$
$a_4= (7,1,0,-1,3)$
Find the dimension of the subspace $span(S)$?

*

*I know that dimension is the maximum number of linearly independent vectors in a subspace.

*So is the dimension in this case 4? Since there are 4 vectors?
Find a set of vectors in $S$ that forms basis of $span(S)$?

*

*How do I solve this?

A: Write your four vectors as column vectors of a $ \ 5 \times 4 \ $ matrix and row reduce it:
$$ \left( \begin{array}{cc} 6 & 1 & 1 &7 \\4&0&4&1\\1&2&-9&0\\-1&3&-16&-1\\2&-4&22&3 \end{array} \right)  \ \ \rightarrow \ \ \left( \begin{array}{cc} 0 & 0 & 0 &0 \\0&0&0&0\\0&0&0&1\\1&-3&16&1\\0&1&-5&\frac{1}{2} \end{array} \right) $$
[I used the fourth row here to work against the other rows; that doesn't matter particularly.]
What does the "zeroing-out" of two rows tell us?  How can we use what non-zero rows remain to construct a basis for span(S) ? (Notice that these are five-dimensional vectors, so we are already starting out "short a coordinate variable", making it "free".)
EDIT -- Since the discussion has advanced further, we can say something about the basis of span(S).  Taking the hint from Omnomnomnom or the above, the subspace spanned by your set of four vectors only has dimension 3.  So we need to set up three linearly independent vectors, using the columns of the row-reduced matrix.
We could "reduce" those last two rows a bit more to obtain
$$  \rightarrow \ \ \left( \begin{array}{cc} 0 & 0 & 0 &0 \\0&0&0&0\\0&0&0&1\\1&0&1&0\\0&1&-5&0 \end{array} \right) \ \ . $$
With the matrix fully "reduced", we need to pick out three (five-dimensional) column vectors which are linearly independent.  The third column is a linear combination of the first two, so we can toss that one out.  A suitable basis for span(S) is then
$$ \left( \begin{array}{cc} 0 \\0\\1\\0\\0 \end{array} \right) \ \ , \ \ \left( \begin{array}{cc} 0 \\0\\0\\1\\0 \end{array} \right) \ \ , \ \ \left( \begin{array}{cc} 0 \\0\\0\\0\\1 \end{array} \right) \ \  . $$

A: I think colormegone's procedure to find basis is correct in terms of row reducing the matrix. However I don't think his statement that the set of $$\begin{pmatrix}0 \\ 0 \\ 1 \\ 0 \\ 0 \end{pmatrix}, \begin{pmatrix} 0 \\ 0 \\ 0 \\ 1 \\ 0\end{pmatrix}, \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 1\end{pmatrix}$$ is a basis is true. Because a basis should be able to represent any vector in the vector space with linear combination, but if we take $a1 = \begin{pmatrix} 6 \\ 4 \\ 1 \\ −1 \\2 \end{pmatrix}$, there's no way to use linear combination of vectors in the above set to represent it.
These 3 vectors correspond to the first, second and fourth column in the original matrix, so a basis (or one possible set of basis) should be the set of corresponding column vectors in the original matrix, i.e. $$\left\{\begin{pmatrix}6 \\ 4 \\ 1 \\ -1 \\ 2 \end{pmatrix}, \begin{pmatrix} 1 \\ 0 \\ 2 \\ 3 \\ -4\end{pmatrix}, \begin{pmatrix} 7 \\ 1 \\ 0 \\ -1 \\ 3\end{pmatrix}\right\}$$


text:
Q: Why does my Mac's graphics freeze when I put a video game in full screen? When I play The Walking Dead (Telltale, season 1) via Steam on my Mac, it only works if it's not full screen. When I switch to full screen, the screen freezes. The screen doesn't get stuck, it just goes all weird, as seen in my linked screenshot.
I have a Macbook Retina, mid 2012. Graphics card NVIDIA GeForce GT 650M 1024 MB.


text:
Q: Testing if an event has been triggered in NestJS In the project we are building, there is a standard sequence in the workflow.

*

*Controller receives a request

*Then fires an event through @nestjs/event-emitter

*Event listener listens to it and executes some code depending on the event

How can we properly test if an event has been triggered but without actually executing the code inside?
We are using Jest for testing.
Mocking with Jest doesn't seem to work, because we want to test the actual trigger event and not the result.
Any suggestions?
"node": "16.14.2"
"@nestjs/event-emitter": "^1.1.0",
"jest": "^27.5.1",

A: Following the suggestion from @ovidijus-parsiunas we managed to spy on the "OnEvent" method successfully.
it.only("start selling", async () => {
    const user = await userSeeder.createOne();

    const spy = jest
      .spyOn(StartSellingListener.prototype, 'startSelling')
      .mockImplementation(() => null);

    expect(eventEmitter.hasListeners(EventsEnum.USER_START_SELLING)).toBe(true);

    const startSelling = userService.startSelling(user);
    expect(startSelling).toBeTruthy();

    expect(spy).toBeCalledWith(user);

    spy.mockRestore();
  });

A: You will have to spy on the handler method that listens to the event or alternatively spy on the encapsulated methods that get called within it. Once your spies are set up you should then be able to trigger the event emitter code from your test and validate if the spies have been triggered.


text:
Q: choose a link with 2 parameters using javascript

        Title 1
        year1

        Title 3
        year2

        Title 3
        year1

I need to automate some function in a website. I want to redirect to the link, if you know the title AND the year, using javascript.
for example: I want to be redirected to the link of title3 and year1.
I tried with this:
function picktitle() {
  chrome.storage.sync.get('title', function(data) {
      var items = document.getElementsByClassName('article-link');

      for(i = 0; i < items.length; i++) {
        if((items[i].innerHTML).includes(title)) {
          chrome.runtime.sendMessage({redirect: items[i].href});
          break;
        }
      }
  });
}

but it choose only the first parameter and i need that it choose the href based on both title and year.
I hope I explained myself.

A: I'm really sorry if im misunderstanding this, but wouldn't using the && keyword in your if statement be the solution? For example:
if (statement1 && statement2) // only runs if both statement1 AND statement2 are true
    // do stuff

Also, maybe select the parent element and check to see if it's children have two elements with the required text properties:
function picktitle() {
  chrome.storage.sync.get('title', function(data) {
      var items = document.getElementsByClassName('article-link');

      for(i = 0; i < items.length; i++) {
        if(
          // Checks if the parent contains the title and the year
          (items[i].parentElement.innerText).includes(title) &&
          (items[i].parentElement.innerText).includes(year)) {

          chrome.runtime.sendMessage({redirect: items[i].href});
          break;
        }
      }
  });
}

I also changed innerHTML to innerText because you probably don't need all the html code with it too.


text:
Q: Making a Gradle project that includes test files Using the Gradle API, I'm trying to make a project that includes example files. The plugin I'm trying to make should make java interfaces in a folder.
@Test
public void pluginCreatesFiles() {
    Project project = ProjectBuilder.builder().withProjectDir(new File(testDir, "example")).build() //Build project with Example.java
    project.pluginManager.apply 'solar.dimensions.orbit' //Apply the plugin
    assertTrue(new File(project.getRootDir(), "src/main/java/solar/dimensions/api").exists()); //Does the file exist?
}

I apply my gradle plugin with the Example.java and test to see if the folder that should be created exists. How do I get the testDir?

A: you have to setup that directory on your own. The best way in a junit test for this is to use the temporary folder rule:
@Rule
public TemporaryFolder myfolder = new TemporaryFolder();

@Test
public void pluginCreatesFiles() {
    def projectDir = new File(myfolder.newFolder("folder"), "example")
    Project project = ProjectBuilder.builder().withProjectDir(projectDir).build() //Build project with Example.java
    project.pluginManager.apply 'solar.dimensions.orbit' //Apply the plugin
    assertTrue(new File(project.getRootDir(), "src/main/java/solar/dimensions/api").exists()); //Does the file exist?
}


text:
Q: Need to do Versioning of existing system I am working on a system which now requires versions to be maintained.
Will explain you the project in brief.
We have a CMS in which there are three users 1. Super Admin, 2. Editor, 3. Approver.
Editor add's data from CMS and send it to approver if he approves the data only in that case it is visible on the front end. Now if the editor edits the same data then its disapproved and removed from the frontend and agian he will send it to the approver and the same process will follow. This is how its working now.
The client has now changed the requirement and now what he wants is that once the data is approved and visible in the site i.e frontend and the editor now edits the data it should not be removed from the frontend and new edited data should be send for approval and when the approver approves the data the old one should be replaced with new one in the front end.
The database design is real bad so it's going to be difficult to achieve this.
The solution that we have thought of is...
For example the Editor can add some kind of news in the front end. All the data w.r.t news is added in news table. Editor add's the news sends it for approval and then he approves. Till here there are no issues. Now suppose that for some reason he wants to edit the same news which is approved. The moment he clicks on edits button it is removed from front end so what we thought is like maintain another table something like temp_news with the same structure and the moment he clicks on edit news after its being approved a new record should be inserted in temp_news table with the values from news table added in this table. Till then in frontend we will display the news from news table. So now we have the same news data in two tables. Approver and editor can now do all the changes and we will update the temp_news table. The moment approver approves this changed data we will update the new's table with values from temp_news table. so now in front end we have the updated new's.
The problem with this solution is that once the changed is approved both tables news and temp_news have the latest data. This not versioning.
Need a solution for this.
I am just a beginner.

A: I would just have one table that you use to store multiple versions of the same data
news
----
ID           int
newsItem     int
dateCreated  datetime
IsApproved   boolean
content      text

Then for display on the front end.  Just
SELECT top(1) * FROM news where IsApproved = true orderby dateCreated desc

So the front will only show the most recently approved version.
and newer version will just get a new ID and dateCreated  but the isApproved would be false
so say if you had  3 version of the same news item.  it would look like
ID    newsitem    dateCreated    IsApproved
1         1        2011-4-26        false
2         1        2011-3-20        true
3         1        2011-1-6         true

A: How about a version control system like Git? Keep the versions, including the one to be approved in Git and the approved one in database table ( only one .) When a new one is approved, move it to the db. Since you are using C# and ASP.NET, something like git# might be helpful for you
People are already doing this:

This is a django website with a twist:
  all content is stored in text files. I
  manage those files with git. A little
  script loads those files into the
  database and then django serves them.
In fact, all of the content and its
  history is actually publicly available
  (but you don't have to make your
  history available in order to use this
  system). You can all see this an
  example of how to use django-gitcms.

http://luispedro.org/software/git-cms
http://nestacms.com/docs/creating-content/publishing-articles-with-git
Git-based content management?


text:
Q: gulp-concat for each project using wildcard I have N projects that has the same structure and all the projects are inside src path:
projectName/

├── index.html
├── anotherPage.html
└── assets/
        ├── css/
        │   └── {bunchofstyles}.css
        ├── imgs/
        │   └── {bunchofimages}.{someImageFormat}
        └──js/
            └── {bunchofjs}.js

I want to join the css files into one, same for the javascript files. Im using gulp for this with gulp-concat, for example, for the js I have something similar to this:
//this was made by memory, if its wrong dont pay attention to the minnor details
var gulp = require("gulp");
var concat = require("gulp-concat");

gulp.task("joinJSFiles", function(){
    gulp.src("./src/**/assets/js/*.js")
        .pipe(concat("script.js"))
        .gulp.dest("./dist")
})

But I have the following issues:

*

*concat joins all the files that are in the gulp.src, including of other projects

*concat deletes the structure of my project, saving the file into dist root instead of having the same structure

*Optional: I have two tasks that make the same thing but for different extension, one for js and another for css, can I have a single task to get this approach?

How can I solve this?

A: Define config which has path to all the libraries.
var config = {
    js : {
        libsSrc : [
            path.src + "js/libs/jquery/jquery.ui.widget.js",
            path.src + "js/libs/jquery/jquery.js",
        ],
        libsBundleName : "libs-bundle",

        // JS Custom
        customSrc : [
            path.src + "js/custom.js"
        ],
        customBundleName : "custom-bundle"
    },

    // Themes and Styles
    css : {
        // CSS Imports
        libsSrc : [
            path.dist + "themes/libs/custom-bootstrap.css",
            path.dist + "themes/libs/bootstrap-datepicker/bootstrap-datepicker3.css"
        ],
        libsBundleName : "libs-bundle",

        // CSS Custom
        customSrc : [

        ],
        customBundleName : ""
    }

}

Then write gulp tasks for bundling JS and CSS
gulp.task('bundle-scripts', ['scripts'], function()  {
    // JS Destination path
    var jsDestPath = path.dist.concat('scripts/bundles');

    // Libs
    var libsTask = gulp.src(config.js.libsSrc)
        .pipe(concat(config.js.libsBundleName + ".js"))
        .pipe(gulp.dest(jsDestPath))
        .pipe(rename(config.js.libsBundleName + ".min.js"))
        .pipe(uglify())
        .pipe(gulp.dest(jsDestPath));

    // Custom Code
    var customJsTask = gulp.src(config.js.customSrc)
        .pipe(concat(config.js.customBundleName + ".js"))
        .pipe(gulp.dest(jsDestPath));

    return eventStream.concat(libsTask, customJsTask);
});

gulp.task('bundle-themes', ['fonts', 'sass'], function()  {
    // JS Destination path
    var cssDestPath = path.dist + 'themes/bundles';

    // Libs
    var libTask = gulp.src(config.css.libsSrc)
        .pipe(concat(config.css.libsBundleName + ".min.css"))
        .pipe(gulp.dest(cssDestPath));

    return eventStream.concat(libTask);
});

This way you can control everything from the config variable

A: Following the suggestion that @Mark made, I made a gulp task that loops over each project but instead of gulp-foreach I used gulp-flatmap (I think its the same thing) and followed the following SO anwser https://stackoverflow.com/a/39933109/4637140
So my gulp task looks like this:
gulp.task('joinJSFiles', function () {
  return gulp.src('src/*')
     .pipe(flatmap(function(steam, dir){
        return gulp.src(dir.path + "/assets/js/*.js", {base:dir.path})
          .pipe(concat("script.js"))
          .pipe(gulp.dest("./dist/"+path.relative(dir.base, dir.path+"/assets/js")))
  }))
});


text:
Q: JDK extraction and installation error issues on windows 10 I got this error while extracting JDK to program files folder cannot create jdk 13... The system cannot find the path specified. (This error is upto 597 error)
So I extracted the file to another folder and followed the required steps to install JDK, that is going to environment variables and I copied the path and all of that. Went to the command prompt to confirm the installation, and to error occurred

*

*Unrecognised option version

*Could not create the Java Virtual Machine


text:
Q: Show that exp is not a tempered distribution I'm trying to show that $x \mapsto e^x$ is not a tempered distribution. For that I want to find a schwartz function $\varphi \in S(\mathbb{R}) $ such that the support of $\varphi$ is contained in $[-1,1]$ and
$$ \langle e^x, \tau_a\varphi\rangle = \int_\mathbb{R} e^x \varphi(x-a) dx = e^a \int_\mathbb{R} e^x \varphi(x) dx = e^a.
$$
Because then I can show by contradiction that $e^x \notin S'(\mathbb{R})$. Is it even possible to find such a $\varphi$?

A: First, since integration-against-$e^x$ certainly is a distribution (dual to test functions $C^\infty_c$), if you have a Schwartz function supported on $[-1,1]$, it's actually a test function, and your displayed formula is correct. So I don't quite understand what contradiction you were getting.
Second, yes, the palpable fact that there are (e.g., positive, real-valued) Schwartz functions that integrate to $+\infty$ against $e^x$ is a compelling heuristic to believe that $e^x$ [sic] is not a tempered distribution. But it may be interesting to think about whether this is really a proof or not... in light of things like principal-value integrals, Hadamard's "finite part" integrals, and so on.
In particular, and perhaps connecting to your implicit argument-by-contradiction starting with the displayed formula, while there is a (not-necessarily-tempered) distribution $u$ given by integration against $e^x$, and with that displayed property under translation, we might imagine proving that $u$ has no extension to a tempered distribution with that same property under translation...?  Is this actually what you're thinking?
(As a silly comment: if there is no condition imposed on such an extension, then Hahn-Banach gives many... meaningless... extensions.)
If so, it might be technically more convenient to pose the condition (by differentiating) as $u'=a\cdot u$, with real $a$, to have the characterization be by a single equation.
Perhaps can you clarify?


text:
Q: Expose property for WPF user control Here i've one user- control in WPF, which basically a shows folder tree in one pane and another pane(listview) shows files in that directory.
Now i exposed one property called fileextensionfilter which basically required to shows specific file only in listview. e.g. if fileextensionfilter= XML it shows only xml files.
Now in my main application i am using the above control thrice, but with differen fileextensionfilet e.g 1>xml another instance .pdf only and so on....
now i am getting the extension filter value from settings.default.xmlfilter,settings.default.PDFFilter so on......
here problem is when i load control properties of usercontrol is not initialized and i have something in constructor which makes uses of this properties and (at that time "null") so filter not working on first time. next once again its get refreshed the filter porperty will get applied and hence it works.

A: You can try using your current property and use the Loaded Event to run the Code you are currently running in your constructor. Here is a small example:
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1">
    <Grid>
        <my:UserControl1 FileExtensionFilter="RTF" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl1" VerticalAlignment="Top" />
        <my:UserControl1 FileExtensionFilter="XML" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl2" VerticalAlignment="Top" />
        <my:UserControl1 FileExtensionFilter="PDF" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl3" VerticalAlignment="Top" />
    </Grid>
</Window>

UserControl
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        string filter = "NULL";
        public UserControl1()
        {
            InitializeComponent();
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Constructor");
        }

        public string FileExtensionFilter
        {
            get { return filter; }
            set { filter = value; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Loaded");
        }

        private void UserControl_Initialized(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Initialized");
        }
    }
}

Output

PropertyNULLSet during Initialized
  PropertyNULLSet during Constructor
  PropertyNULLSet during Initialized
  PropertyNULLSet during Constructor
  PropertyNULLSet during Initialized
  PropertyNULLSet during Constructor
  PropertyRTFSet during Loaded
  PropertyXMLSet during Loaded
  PropertyPDFSet during Loaded


text:
Q: How to Remove a Specific Element and Its Child Elements from a String with JQuery I have a string containing HTML elements as below
var div_elements = "
This is the Quoted
TextThis is the Original Text Within the Div
";

I want to remove the span of class="quote" and all of its child elements and also text within this span. And I want to Get the Result Back as a string not as an object.
Actually I want the following output
var new_div_elements = "
This is the Original Text Within the Div
";

I just want to get a string excluding the span of class quote and all its childs, text etch.
How can I perform this Action with JQuery

A: How about something like this?
var div_elements =  "This is the Quoted TextThis is the Original Text";
var tempHTMLElement = document.createElement('div');
tempHTMLElement.innerHTML = div_elements;

var new_div_elements = $(".original", $(tempHTMLElement)).html();

A: Just turn it into a jQuery object and use the normal DOM manipulation techniques.
alert($("
This is the Quoted TextThis is the Original Text
").find(".quote").remove().html());

http://jsfiddle.net/ZyMjD/


text:
Q: inserting big json file into mongodb I am working on flask and mongodb. I am new to mongodb, I realized that mongodb do not let me  insert json file to database, the file size is greater than 16mb
Is there  any other database that is similar to mongodb (JSON object based) ?
Thank You

A: You can make use of PostgreSQL also for json kind of data to store, based on your Application requirements.
Please refer their official documentation for more information.
Hope the below links can be useful.
1.Postgre Data Types
2.Postgre SQL and Json


text:
Q: IntelliJIDEA WELD-001408 exception when trying to deploy javaEE maven packed application on glassfish Im using JavaEE 7, Glassfish 4, Maven 3.2.1.
I have read several posts where users get exact error, which represents wide area of actual problems, as stated here: CDI Inject fails on maven-embedded-glassfish-plugin -- org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type
So, how can I determine whats the actual problem? All annotations seem to be correct, as same code works for my teammates on their own machines...
For example for project manager, I have interface like:
@Local
public interface ProjectManager { some mtehods...}

then I have implementation of it like:
@Stateless(mappedName = "projectManager")
public class ProjectManagerEJB implements ProjectManager {

    @PersistenceContext(unitName = "scrumkin_PU")
    private EntityManager em;

    @Inject
    private GroupManager gm;

    @Override
    public void someMethod(...);

    some other methods...
}

And the RESTful:
@Path("project")
@Stateless
@Consumes("application/json")
@Produces("application/json")
public class ProjectService {

    @Inject
    private UserManager um;
    @Inject
    private ProjectManager pm;

    @POST
    public void createProject(ProjectJSON project, @Context HttpServletResponse response) {...}

    some other methods...
}

EDIT:
The problem was, I imported project on which I was working on with eclipse, so now I pulled repository into another location and I was able to deploy with IntelliJIDEA (is it possible to use same location of project for Eclipse and IntelliJIDEA (as in, import project in IntelliJIDEA without Eclipse settings (settings files), because they are causing problems)?).
But now, calls to RESTful service are not working, this is what glassfish log looks like after deploying (the warnings part):
[2014-04-11T23:48:57.922+0200] [glassfish 4.0] [WARNING] [] [org.jboss.weld.interceptor.util.InterceptionTypeRegistry] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252937922] [levelValue: 900] [[
  Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled]]

[2014-04-11T23:48:57.923+0200] [glassfish 4.0] [WARNING] [] [org.jboss.weld.interceptor.util.InterceptionTypeRegistry] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252937923] [levelValue: 900] [[
  Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled]]

[2014-04-11T23:48:58.643+0200] [glassfish 4.0] [INFO] [] [org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938643] [levelValue: 800] [[
  Registering the Jersey servlet application, named com.scrumkin.rs.RESTApplication, at the servlet mapping /*, with the Application class of the same name.]]

[2014-04-11T23:48:58.698+0200] [glassfish 4.0] [INFO] [AS-WEB-GLUE-00172] [javax.enterprise.web] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938698] [levelValue: 800] [[
  Loading application [scrumkin-ear-1.0-SNAPSHOT#scrumkin-rs-1.0-SNAPSHOT.war] at [/api]]]

[2014-04-11T23:48:58.729+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938729] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.RESTApplication, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.RESTApplication]]

[2014-04-11T23:48:58.730+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938730] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.ProjectService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.ProjectService]]

[2014-04-11T23:48:58.731+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938731] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.SprintService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.SprintService]]

[2014-04-11T23:48:58.731+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938731] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.ProjectService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.ProjectService]]

[2014-04-11T23:48:58.732+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938732] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.SprintService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.SprintService]]

[2014-04-11T23:48:58.733+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938733] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.SprintService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.SprintService]]

[2014-04-11T23:48:58.734+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938734] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserStoryService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserStoryService]]

[2014-04-11T23:48:58.734+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938734] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserService]]

[2014-04-11T23:48:58.735+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938735] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserStoryService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserStoryService]]

[2014-04-11T23:48:58.736+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938736] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.ProjectService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.ProjectService]]

[2014-04-11T23:48:58.736+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938736] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserStoryService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserStoryService]]

[2014-04-11T23:48:58.737+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938737] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserService]]

[2014-04-11T23:48:58.738+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938738] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserService]]

[2014-04-11T23:48:58.739+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938739] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.LoginService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.LoginService]]

[2014-04-11T23:48:58.739+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938739] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.SprintService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.SprintService]]

[2014-04-11T23:48:58.740+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938740] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserStoryService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserStoryService]]

[2014-04-11T23:48:58.741+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938741] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.ProjectService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.ProjectService]]

[2014-04-11T23:48:58.741+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938741] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.UserService, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.UserService]]

[2014-04-11T23:48:58.742+0200] [glassfish 4.0] [WARNING] [AS-WEB-UTIL-00035] [javax.enterprise.web.util] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938742] [levelValue: 900] [[
  Unable to load class com.scrumkin.rs.RESTApplication, reason: java.lang.ClassNotFoundException: com.scrumkin.rs.RESTApplication]]

[2014-04-11T23:48:58.777+0200] [glassfish 4.0] [INFO] [AS-WEB-GLUE-00172] [javax.enterprise.web] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252938777] [levelValue: 800] [[
  Loading application [scrumkin-ear-1.0-SNAPSHOT#scrumkin-web-1.0-SNAPSHOT.war] at [/]]]

[2014-04-11T23:48:59.125+0200] [glassfish 4.0] [INFO] [] [javax.enterprise.system.core] [tid: _ThreadID=40 _ThreadName=admin-listener(4)] [timeMillis: 1397252939125] [levelValue: 800] [[
  scrumkin-ear-1.0-SNAPSHOT was successfully deployed in 9.668 milliseconds.]]

[2014-04-11T23:48:59.779+0200] [glassfish 4.0] [WARNING] [] [javax.enterprise.system.container.web.com.sun.web.security] [tid: _ThreadID=23 _ThreadName=http-listener-1(1)] [timeMillis: 1397252939779] [levelValue: 900] [[
  Context path from ServletContext:  differs from path from bundle: /]]

And when I try to call some valid RESTful path (a GET method), I get:
[2014-04-12T00:05:17.679+0200] [glassfish 4.0] [INFO] [] [org.glassfish.jersey.server.ApplicationHandler] [tid: _ThreadID=27 _ThreadName=http-listener-1(5)] [timeMillis: 1397253917679] [levelValue: 800] [[
  Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...]]

[2014-04-12T00:05:17.853+0200] [glassfish 4.0] [INFO] [] [org.glassfish.jersey.gf.ejb.EjbComponentProvider] [tid: _ThreadID=27 _ThreadName=http-listener-1(5)] [timeMillis: 1397253917853] [levelValue: 800] [[
  The Jersey EJB interceptor is bound. JAX-RS EJB integration support is enabled.]]

[2014-04-12T00:05:18.934+0200] [glassfish 4.0] [WARNING] [ejb.system_exception] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=27 _ThreadName=http-listener-1(5)] [timeMillis: 1397253918934] [levelValue: 900] [[
  EJB5184:A system exception occurred during an invocation on EJB ProjectService, method: public com.scrumkin.rs.json.ProjectJSON com.scrumkin.rs.ProjectService.getProject(int)]]

[2014-04-12T00:05:18.934+0200] [glassfish 4.0] [WARNING] [] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=27 _ThreadName=http-listener-1(5)] [timeMillis: 1397253918934] [levelValue: 900] [[

javax.ejb.EJBException
    at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
    at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
    at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy219.getProject(Unknown Source)
    at com.scrumkin.rs.__EJB31_Generated__ProjectService__Intf____Bean__.getProject(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at com.scrumkin.rs.ProjectService.getProject(ProjectService.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 54 more
]]

[2014-04-12T00:05:18.977+0200] [glassfish 4.0] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=27 _ThreadName=http-listener-1(5)] [timeMillis: 1397253918977] [levelValue: 900] [[
  StandardWrapperValve[com.scrumkin.rs.RESTApplication]: Servlet.service() for servlet com.scrumkin.rs.RESTApplication threw exception
java.lang.NullPointerException
    at com.scrumkin.rs.ProjectService.getProject(ProjectService.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy219.getProject(Unknown Source)
    at com.scrumkin.rs.__EJB31_Generated__ProjectService__Intf____Bean__.getProject(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
]]