Q: Enable JPA 2nd level cache in Spring Data JPA repository I try to enable JPA 2nd level cache for Spring Data JPA. I enabled cache in persistence.xml:
<persistence-unit name="ds-default">
    <jta-data-source>SAMPLE_DATASOURCE</jta-data-source>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
        <property name="hibernate.cache.use_second_level_cache" value="true" />
        <property name="hibernate.cache.use_query_cache" value="true" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.cache.region.factory_class" value="org.jboss.as.jpa.hibernate5.infinispan.InfinispanRegionFactory" />
    </properties>
</persistence-unit>

In my repository I provided query hints for the cache as well:
public interface SampleRepository extends JpaRepository<SampleEntity, String> {

    @Override
    @QueryHints(value = {
            @QueryHint(name = "org.hibernate.cacheable", value = "true")
    })
    List<SampleEntity> findAll();
}

I expect that the result of findAll query should be cached and that I should see only one select query in the logs. However, I see it more than once which leads me to the conclusion that cache is not configured correctly. What am I missing?
I do not want to use the Spring Cache mechanism (I do not use Spring Boot etc.).

A: I can give you some steps to check and follow and a sample project in github:

*

*Check in persistence.xml
<persistence-unit name="testPersistenceUnit" transaction-type="JTA">
...
        <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
       <properties>
...
        <property name="hibernate.cache.use_second_level_cache" value="true"/>
        <property name="hibernate.cache.use_query_cache" value="true"/>
        <property name="hibernate.cache.region_prefix" value="hibernate.test"/><!-- Optional -->
         <!-- Use Infinispan second level cache provider -->
        <property name="hibernate.cache.region.factory_class" value="org.infinispan.hibernate.cache.v53.InfinispanRegionFactory"/>

            <!-- Optional: Initialize a caches (for standalone mode / test purpouse) -->
            <property name="hibernate.cache.infinispan.cfg"
                      value="META-INF/infinispan-configs-local.xml"/>
...
       </properties>
</persistence>

PS: "org.infinispan.hibernate.cache.v53.InfinispanRegionFactory" package depends on your maven dependencies and Hibernate version.

*If you want to use JCache interceptors. Add to beans.xml:
<interceptors>
    <class>org.infinispan.jcache.annotation.InjectedCacheResultInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCachePutInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCacheRemoveEntryInterceptor</class>
    <class>org.infinispan.jcache.annotation.InjectedCacheRemoveAllInterceptor</class>
</interceptors>

PS. Take in mind, that Infinispan have a variant without "Injected" in the name of the Interceptors for environments where the cache manager is not injected in a managed environment.

*Check that your cache is configured (in your application server) or your cdi producer. Eg.
@ApplicationScoped
public class CacheConfigProducer {
@Produces
public Configuration defaultCacheConfiguration() {
return new ConfigurationBuilder().simpleCache(false).customInterceptors().addInterceptor()
    .interceptor(new TestInfinispanCacheInterceptor()).position(Position.FIRST).expiration().lifespan(60000l)
    .build();
}
}

*Add to your repository your hints like you are adding:
@Eager public interface CacheableReadWriteRepository extends ReadWriteRepository<CacheableEntity, Integer>{

    @QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")})
    List<CacheableEntity> findByValue(Integer value);
}

*Take care to add @Cacheable to your entity

You have this project with Spring Data JPA and CDI integration (spring-data-jpa with cdi). It has tests with JCache, Hibernate 2nd level cache and query cache.
I hope it helps.


Q: Generic types in array with Google HTTP Client Library I have base http response which looks like:
{
"data" : [],
"total" : 0,
"hasMore" : false
}

In data can be any object - Users, FeedItems and etc.
So i want create base class something like
public class BaseDataReponse<T> {

@Key
public List<T> data;

@Key
public Integer total;

@Key
public Boolean hasMore;

}

I can do so in Retrofit for Android library.
But i can't understand how to do this in Google HTTP Client Library.


Q: Im not sure what functions to use when sorting a dictionary Im not sure what functions to use to sort a dictionary which gets added to as the programme runs, the format of the dictionary is (name:score,name:score ..... )
print(" AZ : print out the scores of the selected class alphabteically \n HL : print out the scores of the selected class highest to lowest \n AV : print out the scores of the selected class with there average scores highest to lowest")
    choice = input("How would you like the data to be presented? (AZ/HL/AV)")

while True:
if choice.lower() == 'az':
  for entry in sorted(diction1.items(), key=lambda t:t[0]):
  print(diction1)
  break
elif choice.lower()=='hl':
  for entry in sorted(diction1.items(), key=lambda t:t[1]):
  print(diction1)
  break
elif choice.lower() == 'av':
  print(diction1)
  break
else:
  print("invalid entry")
  break

A: A dictionary is unordered.
You can sort the data for output.
>>> data = {'b': 2, 'a': 3, 'c': 1}
>>> for key, value in sorted(data.items(), key=lambda x: x[0]):
...     print('{}: {}'.format(key, value))
...
a: 3
b: 2
c: 1
>>> for key, value in sorted(data.items(), key=lambda x: x[1]):
...     print('{}: {}'.format(key, value))
...
c: 1
b: 2
a: 3

Using an OrderedDict is not an option here, because you don't want to maintain order, but want to sort with different criteria.


Q: Hyper-V replication between datacentres over WAN I'm trying to enable Windows Hyper-V replication over WAN.
I have (finally!) been able to achieve this in a test environment over LAN using the certificate-based authentication method (rather than Kerberos) and have been able to successfully get two servers to replicate using the hostname.
My confusion now is that I do not know how to get them to communicate over the WAN for the purpose of replication.
In production, I currently have one server (Win 2012 R2) sat in a datacentre and the intention is to spin up another server to take the replication, but this will be in another datacentre, connected only via the internet using external IP addresses. There is no active directory in place, they are just in a workgroup. I'd rather not set up AD or DC just for this (unless I really have to). I already have an A record pointing towards the server (via our domain names provider), so it has an entry in the form of server1.domain.com. So I have server1.domain.com pointing to external IP address, which reaches the server correctly.
In a test environment, this is what I have done so far.
Both servers are Windows 2012 R2.
Server 1 is the main host server with a number of VM's, it's named SERVER1 (Computer Name)
Server 2 has been spun up to take the replication of the VM's from server 1, it's named SERVER2.
They are currently connected internally only via internal network and internal IP addresses. As mentioned above, I have successfully achieved replication between SERVER1 and SERVER2 using certificate-based authentication and it works correctly, but this is using the computer name SERVER2 as a destination replication server. Obviously once this is in a production environment, this method will not be possible.
My question is, how do I set this up so that SERVER1 can see SERVER2 across a WAN (for the purpose of Hyper-V replica) where there is no active directory. How will they resolve?
Do I make an entry on the HOSTS file? If so, what should I enter? Is it as easy as
SERVER1    External IP address of SERVER1
SERVER2    External IP address of SERVER2
Or do I point it to the FQDN (which is created as an A record) in the format:
SERVER1    SERVER1.domain.com
SERVER2    SERVER2.domain.com
I'd appreciate any assistance on this as I'm currently a bit stuck and as I'm currently unable to test this is a live production environment I'd rather go in with as much knowledge as possible.
Thank you.

A: I am afraid this not an answer to what you currently have.
What you should be running for your configuration, (ie no AD, no shared storage)is a shared nothing configuration supported on Windows Server 2016.
https://social.technet.microsoft.com/Forums/windows/en-US/e14e7171-d8fb-418c-9e9e-b3883f4c4ea3/windows-2016-2node-shared-nothing-stretched-cluster-with-storage-replicas?forum=winserverClustering
https://www.starwindsoftware.com/blog/part-2-storage-replica-with-microsoft-failover-cluster-and-scale-out-file-server-role-windows-server-technical-preview

A: So after a bit of playing around I was able to resolve this by entering the hostname of the Replica server in the Host server and making an entry in the HOSTS file that points the hostname to the IP address. It wasn't that difficult in the end.


Q: C Programming: fgets() function is not reading the values that I think it should I am trying to open and read a .txt file that simply contains a 2 digit number from 00 to 99.
Currently the file contains the following numbers: 05
When I read the first two values with fgets(), I instead get 48 and 53, and I've noticed whatever number I put in there, the number that fgets() grabs is 48 higher.  While I could just subtract 48 from the number like I am doing now, I would like to figure out what I am doing wrong so that I don't have to do that.  Here is the relevant section of my code:
char buff[3];
FILE *fp;
fp = fopen("savedata/save.txt","r");
fgets(buff, 3, fp);
SampleLevelIndex = (buff[0]-48)*10 + buff[1]-48;
fclose(fp);

A: Your file contain the characters '0' and '5'. Note that the ASCII code for '0' is 48.
You are reading the values of the bytes, not the number represented. If you had an 'A' in the file, you would have the byte 65.
Your approach works for manually converting numeric characters into a number (although you might one some extra checking, it will break if it doesn't contain two numbers). Or you could use a function like atoi() which converts a numeric string into the number.


Q: Is there anything that is widely considered to be done better in Windows? I'm currently taking an operating systems course in my comp sci engineering education. All the examples are UNIX with a "Windows (or MS-DOS) does this slightly different" footnote. It seems like everything is just slightly worse in Windows/MS-DOS (no clear definition of syscalls, FAT, etc.)
This got me wondering... is there anything in the Windows operating system that UNIX looks at and say "Yep, we should've done it like that"?

A: UNIX was developed by computer scientists. Windows was initially developed by college kids. That's not a good start for most things.
UNIX and Unix-like systems have always been in the domain of professional operations and universities around the world and its target user is such organizations. Windows target has always been the average user, even those average users within corporations now.
Why oh why corporations have their mission critical software run on Windows is beyond me, and I belong to a franchised operation that does such a thing, and Windows, along with its related software, is a constant source of fundamental problems for us.
Meanwhile, my "real job" runs on FreeBSD, where I have had zero issues worth mentioning since 2004.
UNIX and Unix-like systems are professional operating systems for professionals. That is the answer to your question.

A: In many cases power management is better done under Windows. This is a situation that has improved by leaps and bounds using Linux, though it is still not quite parity.

A: File permissions/ACLs are better done in Windows than POSIX. You can set and view very granular permissions. Some Linux filesystems have the idea of xattrs, but they're generally difficult to work with and are unused in my experience.  This really shows up when trying to provide network shares to POSIX and Windows clients.  If a Windows client sets granular permissions, it's extremely difficult to translate that into something that a POSIX system can understand.


Q: Connect to gitlab production postgresql database with psycopg2? I am trying to connect to GitLab production (installed with omnibus package) postgresql database with psycopg2.
My configuration is like below:
onn = psycopg2.connect(database="gitlabhq_production", user="gitlab-psql", host="/var/opt/gitlab/postgresql", port="5432")

It gives the following error:
FATAL:  Peer authentication failed for user "gitlab-psql"

I can connect to the postgresql server on command line with:
sudo -u gitlab-psql -i bash /opt/gitlab/embedded/bin/psql --port 5432 -h /var/opt/gitlab/postgresql -d gitlabhq_production

Does anyone know what will be the correct parameters to pass into?

A: Peer authentication works by checking the user the process is running as. In your command line example you switch to gitlab-psql using sudo.
There are two ways to fix this:

*

*Assign a password to the gitlab-psql postgres user (not the system user!) and use that to connect via python. Setting the password is just another query you need to run as a superuser like so:
sudo -u postgres psql -c "ALTER USER gitlab-psql WITH PASSWORD 'ReplaceThisWithYourLongAndSecurePassword';"

*Run your python script as gitlab-psql like so:
sudo -u gitlab-psql python /path/to/your/script.py


Q: GCC regular expressions How do I use regular expressions in GNU G++ / GCC for matching, searching and replacing substrings? E.g. could you provide any tutorial on regex_t and others?
Googling for above an hour gave me no understandable tutorial or manual.

A: I strongly suggest using the Boost C++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.
The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html
But if you don't have any knowledge of this fine library, I suggest you start here:
http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html

A: I found the answer here:
#include <regex.h>
#include <stdio.h>

int main()
{
  int r;
  regex_t reg;

  if (r = regcomp(&reg, "\\b[A-Z]\\w*\\b", REG_NOSUB | REG_EXTENDED))
  {
    char errbuf[1024];

    regerror(r, &reg, errbuf, sizeof(errbuf));
    printf("error: %s\n", errbuf);

    return 1;
  }

  char* argv[] = { "Moo", "foo", "OlOlo", "ZaooZA~!" };

  for (int i = 0; i < sizeof(argv) / sizeof(char*); i++)
  {
    if (regexec(&reg, argv[i], 0, NULL, 0) == REG_NOMATCH)
      continue;

    printf("matched: %s\n", argv[i]);
  }

  return 0;
}

The code above will provide us with
matched: Moo
matched: OlOlo
matched: ZaooZA~!

A: Manuals should be easy enough to find: POSIX regular expression functions. If you don't understand that, I would really recommend trying to brush up on your C and C++ skills.
Note that actually replacing a substring once you have a match is a completely different problem, one that the regex functions won't help you with.


Q: Hibernate - automatic and generic way to check if a defined unique key constraint exists? Imagine a City to Postalcode relation mapping. (For simplicity using no foreign-keys)
<class name="CityToPostalcode" table="city_to_postalcode" catalog="database">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <property name="city" type="String">
        <column name="city" not-null="true"/>
    </property>
    <property name="postalcode" type="Integer">
        <column name="postalcode" not-null="true"/>
    </property>
    <properties name="businessKey" unique="true">
        <property name="city"/>
        <property name="postalcode"/>
    </properties>
</class>

Is there a function in the framework to check if the unique key "businessKey" for a given combination is unique (also for single-column unique constraints)?
Maybe in combination of mapping "businessKey" to a class? (Similar to usage of composite-id)
It is just so much redundance to write the code for each table to check its business-key, if it definetly could be done automatic.

A: there is natural Id which automaticly creates a unique constraint on schema creation and can be used to query for it more efficiently. in xml
<natural-id>
    <property name="name"/>
    <property name="org"/>
</natural-id>

naturalids use the second level cache more efficient and from H4.1 on loading by naturalid uses the first level cache and can save roundtrips. Other than that natural ids are just like normal properties. you could however write a generic natural id checker

*

*create a new object with the properties set

*access through the sessionfactory the classmetadata of the object

*iterate the natural id properties and use them to get the values from your object and set them on the using(propertyname, propertyvalue)

*if something is found copy the data, else just save the object you just created


Q: Read TIFF ICC profile using Twelvemonkeys ImageIO I need to extract the embedded ICC profile from TIFF files. I can read the IIOMetadata and my IDE shows the ifd field containing the ICC profile (tag ID 34675). But how can I read it to a ICC_Profile object?
ImageInputStream input = ImageIO.createImageInputStream(file);

try {
    ImageReader reader = ImageIO.getImageReaders(input).next();
    if (reader == null) {
        throw new IllegalArgumentException("No image reader for file: " + file);
    }

    try {
        reader.setInput(input);
        IIOMetadata metadata = reader.getImageMetadata(0);
        // metadata contains a field "ifd" containing the ICC profile
        // How to extract it?

    } finally {
        reader.dispose();
    }

} finally {
    input.close();
}

A: You can use the function getProfile() of the ICCProfile class.
Usage:
int profileId = ...;
ICCProfile iccp = new ICCProfile(profileId, input);
ICC_Profile icc_p = iccp.getProfile();

In accordance to the code at google result #1 for twelvemonkeys icc_profile.

A: Found a solution. For this Twelvemonkeys package imageio-metadata is needed in version 3.4. Older version does not contain TIFFEntry class.
 /**
 * Extract ICC profile from an image file.
 *
 * @param file image file
 * @return ICC profile
 * @throws IOException on file errors
 */
protected ICC_Profile extractICCProfile(File file) throws IOException {

    ICC_Profile profile;

    try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
        ImageReader reader = ImageIO.getImageReaders(input).next();
        if (reader == null) {
            throw new IllegalArgumentException("No image reader for file: " + file);
        }

        try {
            reader.setInput(input);
            TIFFImageMetadata metadata = (TIFFImageMetadata) reader.getImageMetadata(0);
            TIFFEntry entry = (TIFFEntry) metadata.getTIFFField(TIFF.TAG_ICC_PROFILE);
            byte[] iccBytes = (byte[]) entry.getValue();
            profile = ICC_Profile.getInstance(iccBytes);
        } finally {
            reader.dispose();
        }
    }

    return profile;
}


Q: How to use a 3D stl viewer on Ruby on Rails I found this javascript plugin that allows to visualize STL files in 3D:
https://www.viewstl.com/plugin/
The example works very well, the problem is that I can not find how to put that into a rails template. I took all the javascript files to my assets/javascript, then I added the respective '// = require' in aplication.js, I took the small script with the div:

and put them in my template but it does not work. Watching the console of my browser I found the following error: ReferenceError: importScripts is not defined. I saw that it has to do with web workers and that an importScripts only works inside them but this problem does not appear in the test.html so I guess something I'm doing wrong when putting them in rails that blocks or prevents the correct operation of importScripts.
I apologize for my lack of fluency in English.
Help :(


Q: Server Side Hooks on Bitbucket I'm new to creating git hooks. I've successfully created a local git hook but I am having a hard time figuring out how to install a server side hook on Bitbucket.
I've tried using a plugin called External Hooks and making a External Pre Receive Hook, but that results in my push to Bitbucket being rejected with:
remote: Hook external-pre-receive-hook blocked the push
 ! [remote rejected] master -> master (pre-receive hook declined).
I've tried putting the hook in the .git folder on the server. But there's not a .git folder that I can find. I did find ApplicationData/Bitbucket/bin/git-hooks. I tried putting a pre-receive hook file in there but that was not successful. It did not prevent a push to the repo but the file also did not execute.
The hook/file that I'm using is as simple as can be so I don't think thats the problem. It has this text:
#!/bin/sh
#

echo 'hi there soldier'

A: I found out where to add a pre-receive or post-receive hook on a repository basis by adding a file to the Bitbucket server. In the Atlassian folder, it is in ApplicationData\Bitbucket\shared\data\repositories\[repository#]\hooks\.
Bitbucket keeps track of repos internally using numbers and not names so in the above replace [repository#] with the repo number. That can be found out this way.
Put the pre-receive hook in the pre-receive.d folder. Put the post-receive hook in the post-receive.d folder.
The names of the hooks/files should begin with a number. That determines what order the hooks are 'activated'. Begin the numbers with at least 21 because the default hook in the folder begins with 20. You want your hook to be activated after the one shipped with Bitbucket server. So a file name for a pre-receive hook could be 21_pre_receive.
Don't change the default hooks that are in the folder because they are needed to help Bitbucket work.
More information can be found here.


Q: How can I get the maximum amount of the total amounts for different products in a month in Postgresql? I've just begun using Postgresql recently. I have a table named 'sales'.
create table sales
    (
        cust    varchar(20),
        prod    varchar(20),
        day integer,
        month   integer,
        year    integer,
        state   char(2),
        quant   integer
    )

insert into sales values ('Bloom', 'Pepsi', 2, 12, 2001, 'NY', 4232);
insert into sales values ('Knuth', 'Bread', 23, 5, 2005, 'PA', 4167);
insert into sales values ('Emily', 'Pepsi', 22, 1, 2006, 'CT', 4404);
insert into sales values ('Emily', 'Fruits', 11, 1, 2000, 'NJ', 4369);
insert into sales values ('Helen', 'Milk', 7, 11, 2006, 'CT', 210);
...

There are 500 rows, 10 distinct products and 5 distinct customers in total.
It looks like this:

Now I need to , find the most “popular” and least “popular” products (those products with most and least total sales quantities) and the corresponding total sales quantities (i.e., SUMs) for each of the 12 months (regardless of the year).
The result should be like this:

Now I can only write query like this:
select month,
       prod,
       sum(quant)
from sales
group by month,prod
order by month,prod;

And it gives me the result like this:

Now I need to pick up the maximum value for each month. For example, the biggest value in the first 10 sums of month 1, and so on...
I also need to get the minimum value of the sums (regardless of the year). And combine them horizontally... I have no idea about this...

A: Note: for a TLDR, skip to the end.
Your problem is a very interesting textbook case as it involves multiple facets of Postgres.
I often find it very helpful to decompose the problem into multiple subproblems before joining them together for the final result set.
In your case, I see two subproblems: finding the most popular product for each month, and finding the least popular product for each month.
Let's start with the most popular products:
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
  month,
  prod,
  SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum DESC;

Explanations:

*

*WITH is a common table
expression,
which acts as a temporary table (for the duration of the query) and
helps clarify the query. If you find it confusing, you could also opt
for a subquery.

*generate_series(1, 12) is a Postgres function which generate a series of integers, in this case from 1 to 12.

*the LEFT JOIN allows us to associate each sale to the corresponding month. If no sale can be found for a given month, a row is returned with the month and the joined columns with NULL values. More information on joins can be found here. In your case, using LEFT JOIN is important, as using INNER JOIN would exclude products that have never been sold (which in that case should be the least popular product).

*GROUP BY is used to sum over the quantities.

*at this stage, you should -potentially- have multiple products for any given month. We only want to keep those with the most quantities for each month. DISTINCT ON is especially useful for that purpose. Given a column, it allows us to keep the first iteration of each value. It is therefore important to ORDER the sales by sum first, as only the first one will be selected. We want the bigger numbers first, so DESC (for descending order) should be used.

We can now repeat the process for the least popular products:
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
  month,
  prod,
  SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum;

Conclusion (and TLDR):
Now we need to merge the two queries into one final query.
WITH months AS (
  SELECT generate_series AS month
  FROM generate_series(1, 12)
), agg_sales AS (
  SELECT
    month,
    prod,
    SUM(quant)
  FROM months
  LEFT JOIN sales USING (month)
  GROUP BY month, prod
), most_popular AS (
  SELECT DISTINCT ON (month)
    month,
    prod,
    sum
  FROM agg_sales
  ORDER BY month, sum DESC
), least_popular AS (
  SELECT DISTINCT ON (month)
    month,
    prod,
    sum
  FROM agg_sales
  ORDER BY month, sum
)
SELECT
  most_popular.month,
  most_popular.prod AS most_popular_prod,
  most_popular.sum AS most_pop_total_q,
  least_popular.prod AS least_popular_prod,
  least_popular.sum AS least_pop_total_q
FROM most_popular
  JOIN least_popular USING (month);

Note that I used an intermediate agg_sales CTE to try and make the query a bit clearer and avoid repeating the same operation twice, although it shouldn't be a problem for Postgres' optimizer.
I hope you find my answer satisfactory. Do not hesitate to comment otherwise!
EDIT: although this solution should work as is, I would suggest storing your dates as a single column of type TIMESTAMPTZ. It is often much easier to manipulate dates using that type and it is always good practice in case you need to analyze and audit your database further down the line.
You can get the month of any date by simply using EXTRACT(MONTH FROM date).


Q: Using Breeze With Web Api And Angular js i want to select item from drop down list and then i will see selected customer data in input
then iwant to edit inputs and then save them in database by breez js and web api
I have Web Api Controller like This :
[BreezeController]
    public class ZzaController : ApiController
    {
        readonly EFContextProvider<ZzaDbContext> _contextProvider =
            new EFContextProvider<ZzaDbContext>();

        // ~/breeze/Zza/Metadata
        [HttpGet]
        public string Metadata()
        {
            return _contextProvider.Metadata();
        }

        // ~/breeze/Zza/Customers
        [HttpGet]
        public IQueryable<Customer> Customers()
        {
            var customers = _contextProvider.Context.Customers;
            return customers;
        }

        // ~/breeze/Zza/SaveChanges
        [HttpPost]
        public SaveResult SaveChanges(JObject saveBundle)
        {
            return _contextProvider.SaveChanges(saveBundle);
        }
    }

Angular Service Like This :
var services = function (http) {
    breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
    this.getBybreeze = function (successed) {

        var dataService = new breeze.DataService({
            serviceName: 'breeze/Zza',
            hasServerMetadata: false
        });
        var manager = new breeze.EntityManager(
        {
            dataService: dataService
        });
        var entityQuery = breeze.EntityQuery;
        return entityQuery.from('Customers').using(manager).execute().then(successed).catch();

    }
    this.saveByBreeze  =function () {

        var dataService = new breeze.DataService({
            serviceName: 'breeze/Zza',
            hasServerMetadata: false
        });
        var manager = new breeze.EntityManager(
        {
            dataService: dataService
        });
        manager.saveChanges().fail(function (error) { alert("Failed save to server: " + error.message); });

    }
}

services.$inject = ["$http"];
app.service("TestService", services);

And Angular Controler Like This :
var controller = function (scope, testService, ngTableParams, filter, upload, notification) {
    var self = this;
    self.title = "Test";
    self.customers = [];
    self.selected = "";
    self.selectedFirstName="";
    self.selectedLastName="";
    testService.getBybreeze(function (data) {
        self.customers = data.results;
    });
    self.selectedCustomer = function () {
        angular.forEach(self.customers, function (item) {
            if (item.Id === self.selected) {
                self.selectedFirstName = item.FirstName;
                self.selectedLastName = item.LastName;
            }
        });
    }
    self.save = function () {
        testService.saveByBreeze();
    }
}
controller.$inject = ["$scope", "TestService", "NgTableParams", "$filter", "Upload", "Notification"];
app.controller("TestController", controller)

View :

            Customers:

            <select class=" form-control" ng-change="self.selectedCustomer()" name="Id" ng-model="self.selected" ng-options="item.Id as item.FullName for item in self.customers"></select>

        <fieldset data-bind="with: currentCustomer">
            <legend>Customer:</legend>
            Name:

            <input class="form-control" id="customerName" value="{{self.selectedFirstName}}" />
            Tell:

            <input id="customerPhone" class="form-control" value="{{self.selectedLastName}}"  />

            <button class=" btn btn-default" id="saveButton" ng-click="self.save()">Save</button>
        </fieldset>

I think EveryThing Is ok
but when I save it,nothing Saved

A: Your code creates a new empty EntityManager with each query and save operation.  Instead, you should create a single EntityManager in your TestService, and use it for all query and save operations.
var services = function (http) {
    breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
    var dataService = new breeze.DataService({
        serviceName: 'breeze/Zza',
        hasServerMetadata: false
    });
    var manager = new breeze.EntityManager(
    {
        dataService: dataService
    });

    this.getBybreeze = function (successed) {
        var entityQuery = breeze.EntityQuery;
        return entityQuery.from('Customers').using(manager).execute().then(successed);
    }

    this.saveByBreeze = function () {
        manager.saveChanges().catch(function (error) { alert("Failed save to server: " + error.message); });
    }
}

services.$inject = ["$http"];
app.service("TestService", services);


Q: Regex replace total string I have and XML file with items that contain this string:
<field name="itemid">xx</field>
Where xx = a number from 50 to 250.
I need to remove the entire string from the whole file.
How would I do this with a Regex replace?

A: you can use this:
str = str.replace(/<.*>/g,'');

See an example for match here

var str = "<field name='itemid'>xx</field>";
str = str.replace(/<.*>/g, 'replaced');
console.log(str)

Explanation:

*

*< matches the character < literally

*.* matches any character (except newline)

*

*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*> matches the character > literally

*g modifier: global. All matches (don't return on first match)

If you want to be more restrictive you can do this:
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, '');

See an example for match here

var str = '<field name="test">200</field>';
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, 'replaced');
console.log(str)

Explanation:

*

*<field name matches the characters

*\= matches the character = literally

*\" matches the character " literally

*\w* match any word character [a-zA-Z0-9_]

*

*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*\" matches the character " literally

*> matches the character > literally

*\d* match a digit [0-9]
      -  Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

*< matches the character < literally

*\/ matches the character / literally

*field> matches the characters field> literally (case sensitive)

*g modifier: global. All matches (don't return on first match)

A: When you replace a tag especially XML tag you must be sure that you capture everything from opening to closing tag. In this case RegExp should look back.
var re = /<(\S+)[^>]*>.*<\/\1>/g;
var m ='some text <ab id="aa">aa
qq
 aa</ab>test test
paragraph
'.replace(re,'');
console.log(m);//some text test test

\1 matches (\S+)
\S+ one or more non-white-space characters


Q: Soft delete in sails.js I'm trying to implement soft delete on a model in a sails.js project by I override the delete action in the respective controller to just update a boolean attribute called isDeleted.
The problem I'm facing is that, I need to override the find action for the respective controller so that it'll ignore the "deleted" records but I need to keep the rest of the original functionality. To do this I'm simply copying the code of the original find action into the override, but it depends on the actionUtil module, and, when doing the require for that module, no matter how I change the route it never manages to find the module.
So, this is what my controller looks like:
var actionUtil = require('/sails/lib/hooks/blueprints/actionUtil'),
_ = require('lodash');

module.exports = {

find: function(req, res){

    // Look up the model
    var Model = actionUtil.parseModel(req);

    if ( actionUtil.parsePk(req) ) {
        return require('./findOne')(req,res);
    }

    // Lookup for records that match the specified criteria
    var query = Model.find()
    .where( actionUtil.parseCriteria(req) )
    .limit( actionUtil.parseLimit(req) )
    .skip( actionUtil.parseSkip(req) )
    .sort( actionUtil.parseSort(req) );

    // TODO: .populateEach(req.options);
    query = actionUtil.populateEach(query, req);

    query.exec(function found(err, matchingRecords) {
        if (err) return res.serverError(err);

        // Only `.watch()` for new instances of the model if
        // `autoWatch` is enabled.
        if (req._sails.hooks.pubsub && req.isSocket) {
            Model.subscribe(req, matchingRecords);

            if (req.options.autoWatch)
                { Model.watch(req); }

            // Also subscribe to instances of all associated models
            _.each(matchingRecords, function (record) {
                actionUtil.subscribeDeep(req, record);
            });
        }

        res.ok(matchingRecords);
    });

},//End .find

destroy: function(req,res){

    console.log("Parametro: " + req.param('id') );
    Vendedor.update({ id_vendedor: req.param('id') }, { isDeleted: true })
    .exec(function (err, goal)
    {
        if (err)
            return res.status(400).json(err);

        return res.json(goal[0]);
    });

}
};

But, when starting the server I get an error, saying that the module actionUtil couldn't be found. Does anyone know how I could do this?


Q: Joining Tables For Find the Playlists without any track of the genres “Latin”, “Rock” or “Pop” I have a basic problem about create a query for Find the Playlists without any track of the genres “Latin”, “Rock” or “Pop”. I am really struggling with Joins some exercises I can do well but with this I can figure out.
I tried This:
SELECT p.PlaylistId as Playlist, p.Name
FROM Playlist p INNER JOIN PlaylistTrack pt ON p.PlaylistId = pt.PlaylistId
INNER JOIN Track t ON pt.TrackId = t.TrackId
JOIN Genre g ON g.GenreId = t.GenreId
WHERE g.Name <> "Latin " AND "Rock" AND "Pop"

My Output are returning 1 value: AC/DC, and null values when I use LEFT JOIN.
This is my DDL:
CREATE TABLE Genre (GenreId int PRIMARY KEY, `Name` CHAR(255) );
CREATE TABLE MediaType ( MediaTypeId int PRIMARY KEY, `Name` CHAR(30) );
CREATE TABLE Artist(ArtistId INT PRIMARY KEY, `Name` CHAR(255) ); -- LONG CHAR????
CREATE TABLE Album(AlbumId INT PRIMARY KEY, Title CHAR(120), ArtistId INT );
CREATE TABLE Track( TrackId int PRIMARY KEY, `Name` CHAR(255), AlbumId INT,
 MediaTypeId INT, GenreId INT, Composer CHAR(220), Milliseconds int, Bytes INT, UnitPrice decimal(8,2)); -- UnitPrice number
CREATE TABLE Playlist(PlaylistId int PRIMARY KEY, `Name` CHAR(30));

If you are more interested and want to test this database that I build check this link, is a little dirty and need to be improve but commenting some rows will work.

As I Said: My Output are returning 1 value: AC/DC, and null values when I use LEFT JOIN.

This is the expected value:

PlaylistId
Name

2,
Movies

5
TV Shows

6
Audiobooks

7
Audiobooks

8
Movies

9
Music Videos

10
TV Shows

11
Classical

12
Classical 101 - Deep Cuts

13
Classical 101 - Next Step

14
Classical 101 - The Basics

15
On-The-Go 1

I thought that this question was really easy. I dont understand why I can't figure out, can someone help me?

A: SELECT *
FROM Playlist
WHERE NOT EXISTS ( SELECT NULL
                   FROM PlaylistTrack
                   INNER JOIN Track USING (TrackId)
                   INNER JOIN Genre USING (GenreId)
                   WHERE Playlist.PlaylistId = PlaylistTrack.PlaylistId
                     AND Genre.Name IN ('Latin', 'Rock', 'Pop') )


Q: How to compress (resize?) >60k images on mac? There are >60k images 10KB-1MB size and i need them all weighing <80KB, how do i go about this? Can't open so many images with preview. I guess there is a solution for this in terminal

A: First install ImageMagick and GNU Parallel with homebrew:
brew install imagemagick
brew install parallel

Then go to the directory where the images are and create an output directory:
cd where/the/images/are
mkdir output

Now run ImageMagick from GNU Parallel
find . -name "*.jpg" -print0 | parallel -0 magick {} -define jpeg:extent=80kb output/{}


Q: ASP.net Recover JavaScript Created Attribute from PostBack I've create a control that derivates from a TextBox. On that class is added an call for a Javascript code that, when the content of the text changes, it adds a attribute called "post" with value "true" to the control. I wish to collect that value.
So far i have this:
ASP
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="CWEB.Web.UI.USR.DefPage" %>
<%@ Register TagPrefix="Controls" Namespace="CWEB.Web.Controls" Assembly="Web" %>
<html>
<head>
    <script type="text/javascript">
        function SetPost(element){if(!element.hasAttribute('post')){z=document.createAttribute('post');z.value='true';element.setAttributeNode(z);}else{element.setAttribute('post','true');}}
    </script>
</head>
<body>
    <Controls:TextBox runat="server" ID="abc" />
</body>
</html>

CodeBehind (and TextBox derivated class)
using SysWeb = global::System.Web.UI;
using CtrWeb = global::CWEB.Web.Controls;
namespace CWEB.Web
{
    internal static class Binder
    {
        internal const string PostableKey = "post";
        internal const string AuxFieldKey = "_ck";
        internal static bool GetCheck(string ck) { return (ck != null && ck != "" && (ck == global::CWEB.Data.Fields.Boolean.ValueTrue || ck.Contains("t") || ck.Contains("v"))); }

        private static bool GetCheckInput(CtrWeb.Controls.Generic.FieldControl Control, ref bool Found)
        {
            if (Control == null || Control.Page == null) { Found = false; }
            else
            {
                string value = Control.Page.Request.Form[Control.ClientID + CtrWeb.Binder.AuxFieldKey]; //If then it's child is null, it means it's unchecked.
                Found = (value != null && value != "");
                return ((Found) ? (value == "1" || value == "on" || value.Contains("t")) : false);
            }
            return false;
        }

        internal static bool GetCheck(CtrWeb.Controls.Generic.FieldControl Control, bool OutSideInput, string ViewStateKey = CtrWeb.Binder.CheckAttribute)
        {
            string value = Control.Page.Request.Form[Control.UniqueID]; //If the main control exists then it's child shal too.
            if (value == null || value == "") { return CtrWeb.Binder.GetCheck((string)Control.GetViewState()[ViewStateKey]); }
            else if (OutSideInput)
            {
                bool Found = false;
                return CtrWeb.Binder.GetCheckInput(Control, ref Found);
            } else { return CtrWeb.Binder.GetCheck((string)Control.GetAttributes()[ViewStateKey]); }
        }

        internal static void SetCheck(CtrWeb.Controls.Generic.FieldControl Control, bool OutSideInput, string ViewStateKey = CtrWeb.Binder.CheckAttribute)
        {
            bool FValue = CtrWeb.Binder.GetCheck(Control, OutSideInput, ViewStateKey: ViewStateKey);
            Control.GetViewState()[ViewStateKey] = ((FValue) ? "true" : "false");
        }
    }

    namespace Controls
    {
        public interface FieldControl
        {
            string ClientID { get; }
            string UniqueID { get; }
            SysWeb.Page Page { get; }
            SysWeb.AttributeCollection GetAttributes();
            SysWeb.StateBag GetViewState();
        }

        public class TextBox : SysWeb.WebControls.TextBox, CtrWeb.FieldControl
        {
            public bool Postable
            {
                get { return CtrWeb.Binder.GetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey); }
                set { CtrWeb.Binder.SetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey); }
            }

            protected override void LoadViewState(object savedState)
            {
                this.BaseLoadViewState(savedState);
                this.Postable = CtrWeb.Binder.GetCheck(this, false, ViewStateKey: CtrWeb.Binder.PostableKey);
            }

            protected override void OnInit(global::System.EventArgs e)
            {
                if (!this.Page.IsPostBack)
                {
                    this.Attributes.Add("onchange", "SetPost(this)");
                    this.Attributes.Add(MdWeb.Binder.PostableKey, "false");
                }
                base.OnInit(e);
            }
        }
    }

    namespace UI.USR
    {
        public class DefPage : SysWeb.Page { protected CtrWeb.TextBox abc; }
    }
}

Some codes were not copied here because they have nothing to do with the issue.

A: In order for that data to be posted to the server, you have to store it in a form value.
HTML elements in their entirety aren't posted to the server.  Only the key/value pairs of form elements are.  (WebForms is trying to trick you into thinking that the whole page is posted to the server, but it's a lie.)
Add a hidden form field to the page, something as simple as this:
<asp:Hidden id="someHiddenField" />

Then in the JavaScript, set the value of that field:
document.getElementById('<%= someHiddenField.ClientID %>').value = 'true';

Then when the page posts back to the server, the 'true' value will be in that hidden field:
someHiddenField.Value

A: asp:Hidden doesn't exist. only form elements can actually postback data. The server side will take the postback data and load it into the form element provided that the runat=server is set.
in markup or html:
<input type="hidden" runat="server" ID="txtHiddenDestControl" />

javascript:
document.getElementById('<%= txtHiddenDestControl.ClientID %>').value = '1';

code behind:
string postedVal = txtHiddenDestControl.Value.ToString();


Q: Failing to upload a local aar file to artifactory using gradle I have a simple problem which I have not been able to solve. I have downloaded an external .aar file that I want to upload to our in house Artifactory. But I havent been able to solve the problem at all. Here is my build.gradle file
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'digital.wup:android-maven-publish:3.6.2'
    }
}
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'digital.wup.android-maven-publish'

group 'com.hello'

def version = '3.1'
def groupA = 'com.hello'
def artifactA = 'world'
def intermediateDirName = 'outputs/aar'

def aarFileLocation = "${buildDir}/${intermediateDirName}/${artifactName}-${datadogVersion}.aar"

configurations {
    aarLocal
}

dependencies {

   aarLocal files('world-3.1.aar')

}

task copyFromLocal(type: Copy) {
    from configurations.aarLocal
    into "$buildDir/$intermediateDirName"
}

publishToMavenLocal.dependsOn copyFromLocal
publish.dependsOn copyFromLocal

publishing {
  publications {
    publishAarToArtifactory(MavenPublication) {
        groupId groupName
        artifactId artifactName
        version datadogVersion
        artifact "${buildDir}/${intermediateDirName}/${artifactName}-${version}.aar"
    }
  }
}

publishToMavenLocal works w/o any problems but the publish task gets skipped
Following is the error message I get Skipping task ':publish' as it has no actions. Any help?
Basically uploading a local aar to artifactory is all that i am trying to achieve.
NOTE : The repo credentials are in our CI/CD system for artifactory.

A: Both publishToMavenLocal and publish are aggregate tasks without actions. They are used to trigger a bunch of publishPubNamePublicationToMavenLocal tasks and publishPubNamePublicationToRepoNameRepository tasks respectively.
$ ./gradlew publishToMavenLocal --info
...
> Task :publishMavenPublicationToMavenLocal
...
> Task :publishToMavenLocal
Skipping task ':publishToMavenLocal' as it has no actions.
:publishToMavenLocal (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs.

$ ./gradlew publish --info
...
> Task :publishMavenPublicationToMavenRepository
...
> Task :publish
Skipping task ':publish' as it has no actions.
:publish (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs.

Reference: https://docs.gradle.org/current/userguide/publishing_maven.html#publishing_maven:tasks


Q: Best way of writing subroutines in 6502 Assembler? I'm new to assemblers, so here is a simple question:
My custom subroutines change the X, Y, and A registers. They manipulate these to produce the desired results. Is it a good idea to push these values to the stack when the routine starts and restore them before RTS?
I mean, this way I can write routines which can be called from anywhere without messing up the "state" or affecting other routines. But is it OK to use the stack this way? Or is there a better way to do this?

A:
But is it OK to use the stack this way? Or is there a better way to do this?

Absolutely; BASIC does it all the time, as do many routines in the kernal.
But, there is no right answer to this, it comes down to at least speed, portability, and style.

*

*If you use the stack a lot, there are some speed considerations.  Your typical pha txa pha tya pha at the start, and then the reverse (pla tay pla tax pla) eats up 3 bytes of your stack, and adds in some cycle time due to the 2 x 5 operations

*You could use zero page, but that takes away some portability between different machines; VIC-20, C64, C128, the free zero page addresses may not be the same across platforms.  And your routine can't be called "more than once" without exiting first (e.g. no recursion) because if it is called while it is active, it will overwrite zero page with new values.  But, you don't need to use zero page...

*...because you can just create your own memory locations as part of your code:
myroutine = *
    ; do some stuff..
    rts

mymem =*
    .byt 0, 0, 0

*the downside to this is that your routine can only be called "once", otherwise subsequent calls will overwrite your storage areas (e.g. no recursion allowed!!, same problem as before!)

*You could write your own mini-stack
  put_registers =*
     sei ; turn off interrupts so we make this atomic
     sty temp
     ldy index
     sta a_reg,y
     stx x_reg,y
     lda temp
     sta y_reg,y
     inc index
     cli
     rts

  get_registers =*
     sei ; turn off interrupts so we make this atomic
     dec index
     ldy index
     lda y_reg,y
     sta temp
     lda a_reg,y
     ldx x_reg,y
     ldy temp
     cli
     rts

  a_reg .buf 256
  x_reg .buf 256
  y_reg .buf 256
  index .byt 0
  temp  .byt 0

*This has the added benefit that you now have 3 virtual stacks (one for each of .A, .X, .Y), but at a cost (not exactly a quick routine).  And because we are using SEI and CLI, you may need to re-think this if doing it from an interrupt handler.  But this also keeps the "true" stack clean and more than triples your available space.


Q: Running multpe containers without composer? Hey all I have three containers that I am currently running in compose
version: '2'

services:

  web:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/web.dockerfile
    ports:
      - "9000:9000"
    links:
      - redis:redis
    volumes:
      - /usr/src/app
      - /usr/src/app/source/static
    env_file:
      - .env
    environment:
      - 'DEBUG=true'
      - 'DOCKER_COMPOSE_MODE=true'
      - 'APP_ENV=local'

  nginx:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/nginx.dockerfile
    ports:
      - "80:80"
    volumes:
      - /www/static
    volumes_from:
      - web
    env_file:
      - .env
    links:
      - web:web
    environment:
      - "BACKEND_ADDR=web:9000"
      - 'DOCKER_COMPOSE_MODE=true'
      - 'APP_ENV=local'

  redis:
    restart: always
    build:
      context: ./
      dockerfile: deploy-1w/cache.dockerfile
    ports:
      - "6379:6379"
    volumes:
      - ./redisdata:/data

I am trying to run these without using compose (more for debugging purposes and understanding of what composer is actually DOING more than anything) but due to the links etc i am not able to get them running (nginx is using proxy pass and looking for an upstream of web)
Here's the Dockerfile for web
FROM python:2-onbuild

WORKDIR /usr/src/app/

RUN cp -rf /usr/src/app/src/* /usr/src/app/

# build dependencies
RUN apt-get update && apt-get install -y git-core rubygems ruby-dev gettext nano  \
    && wget nodejs.org/dist/v6.10.0/node-v6.10.0-linux-x64.tar.gz                 \
    && tar -C /usr/local --strip-components 1 -xzf node-v6.10.0-linux-x64.tar.gz

RUN pip install -r requirements.txt

RUN apt-get install nodejs-legacy -y                                              \
    && gem install sass compass                                                   \
    && npm install -g grunt-cli bower

# Bad command?
#RUN npm install -g

RUN npm install grunt@0.4.5 -g --save-dev                                         \
    && npm install                                                                \
    && bower install --allow-root

RUN grunt buildcss                                                                \
    && grunt buildjs --force

# Add the local settings file
COPY ./deploy-1w/config/local_settings.py /usr/src/app/source/source/local_settings.py

# copy the bootstrap script
COPY ./deploy-1w/web-bootstrap.sh  /usr/local/bin/web-bootstrap.sh
RUN chmod 775 /usr/local/bin/web-bootstrap.sh

WORKDIR /usr/src/app/source

# run bootstrap script
CMD ["/usr/local/bin/web-bootstrap.sh"]

Nginx
FROM tutum/nginx

# backend web address
ENV BACKEND_ADDR 0.0.0.0:0

# build dependencies
RUN apt-get update && apt-get install -y gettext

# copy config template
COPY ./deploy-1w/config/nginx.conf /etc/nginx/nginx.conf.template

# copy static file to use as a health check
COPY ./deploy-1w/config/nginx-health-check /var/www/html/public/health-check

# copy the bootstrap script
COPY ./deploy-1w/nginx-bootstrap.sh  /usr/local/bin/nginx-bootstrap.sh
RUN chmod 775 /usr/local/bin/nginx-bootstrap.sh

# run bootstrap script
CMD ["/usr/local/bin/nginx-bootstrap.sh"]

and Redis
FROM debian:jessie

ENV REDIS_MAJOR_MINOR_VERSION 4.0
ENV REDIS_VERSION 4.0.10
ENV REDIS_TARBALL_SHA1 d2738d9b93a3220eecc83e89a7c28593b58e4909
ENV BACKEND_ADDR 0.0.0.0:0

RUN apt-get -q update && \
  DEBIAN_FRONTEND=noninteractive apt-get -qy --no-install-recommends install \
    build-essential \
    curl && \
  curl -O http://download.redis.io/releases/redis-$REDIS_VERSION.tar.gz && \
  [ $(shasum redis-$REDIS_VERSION.tar.gz | awk '{ print $1 }') = $REDIS_TARBALL_SHA1 ] && \
  tar zxf redis-$REDIS_VERSION.tar.gz && \
  cd redis-$REDIS_VERSION && \
  make -j$(nproc) && \
  cd src && \
  cp \
    redis-benchmark \
    redis-check-aof \
    redis-check-rdb \
    redis-cli \
    redis-sentinel \
    redis-server \
    /usr/local/bin && \
  cd ../.. && \
  rm -rf redis-$REDIS_VERSION redis-$REDIS_VERSION.tar.gz /tmp/* /var/tmp/* && \
  apt-get -qy purge build-essential curl && \
  apt-get -qy clean autoclean autoremove && \
  rm -rf /var/lib/{apt,dpkg,cache,log}/

COPY ./deploy-1w/config/redis.conf /etc/redis.conf

VOLUME /var/lib/redis

CMD ["/usr/local/bin/redis-server", "/etc/redis.conf"]

I am literally trying to do what i'm doing in composer... without composer...
What i'm doing is this, and it's failing
docker build -t redis-test -f deploy-1w/cache.dockerfile .
docker build -t nginx-test -f deploy-1w/nginx.dockerfile .
docker build -t web-test -f deploy-1w/web.dockerfile .

docker network create test-network

docker run -d -it -p --network test-network '6379:6379' redis-test
docker run -d -it -p --network test-network '9000:9000' --link $(docker ps -a | grep redis-test |awk '{print$1}') web-test
docker run -d -it -p --network test-network '80:80' -e 'BACKEND_ADDR=web:9000' --link $(docker ps -a | grep web-test |awk '{print$1}') nginx-test

The above give me an error...
bash-4.4$ docker logs bc28bcd28653
nginx: [emerg] host not found in upstream "web" in /etc/nginx/nginx.conf:35

Here's the pertinent part of the nginx conf
location / {
  proxy_pass http://${BACKEND_ADDR};    <-- Line 35
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

A: I use to have so many issues with docker and nginx because I didn't understand everything very well.
So here is my recommendation:
Quick fix :
Add
nginx:
    restart: always
    ....
    depends_on:
        - web

Explanation :
Nginx with upstream can be useful but if the upstream doesn't exist, then nginx will never start.
And in the docker case, you have to say that web should run before nginx using depends_on parameter.
But after upgrading my stack to docker swarm, I discovered that depends_on can't be used anymore across multiple instances
for a reason I don't remember.
So I wanted to start nginx even if my web server is not running and the easy way to do it is to use variable
in nginx like this :
      set $server_1 web;
      proxy_pass http://$server_1:8080;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header HOST $host;
      proxy_set_header X-NginX-Proxy true;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

I definitly advise you to use the last docker-compose version because you have so much better feature.
Also, using link is quite deprecated, I recommend you to create an internal network using docker network command.
It's very useful to add or remove an instance to it and you save time and maintainability.
Running multiple containers without composer
You need to use docker run command for each container
docker run -d --name web -p 9000:9000 ....
docker run -d --name nginx -p 80:80 ....


Q: Copy data from excel to excel with openpyxl Couldn't find answers I can understand. So I've decided to ask.
I'm learning Python. And now I'm trying to solve a problem with collecting data from active spreadsheet in one excel file and paste it to another excel file. The first file contains table and a few cells with information to the right of it. I'm trying to fully copy the spreadsheet data.
import openpyxl, os
from openpyxl.cell import get_column_letter

os.chdir('D:\\Python')
wb = openpyxl.load_workbook('auto.xlsx')
ws = wb.active

# Create new workbook and chose active worksheet.
wbNew = openpyxl.Workbook()
wsNew = wbNew.active

# Loop through all cells (rows, then columns) in the first file
# and fill in the second one.
for allObj in ws['A1':get_column_letter(ws.max_column) + str(ws.max_row)]:
    for cellObj in allObj:
        for allNewObj in wsNew:
            for newCellObj in allNewObj:
               wsNew[cellObj.coordinate].value = cellObj.value
wbNew.save('example.xlsx')

Finally it works.


Q: Files last modification date This seems like such a simple thing that I'm convinced I must be just missing it somewhere.
Is there a setting or a plugin that will display the last modification date/timestamp of the file you are working on?  Perhaps in the status bar or something similar?

A: No, as far as I can tell this feature isn't implemented and no plugins exist for it.
You can suggest it at Sublime Text's UserEcho forum or, if you're feeling ambitious, make a plugin that adds this functionality.

A: The SideBarEnhancements package has a statusbar_modified_time option which displays the current file's last modification datetime in the status bar.
The datetime display format can be customised using the statusbar_modified_time_format setting.


Q: Are usings guarding for all eventualities? I've found the following passage.
using (TextWriter w1 = new StringWriter(...))
using (XmlWriter w2 = new XmlTextWriter(w1))
using (StringReader r1 = new StringReader(...))
using (XmlTextReader r2 = new XmlTextReader(r1))
{
  _xslt.Transform(r2, w2);
  ...
  FileOperations.LockFiles();

  w1.Close();
  w2.Close();
  r1.Close();
  r2.Close();
}

My suggestion is (besides renaming, of course) that we could remove the last four statements, since those are declared using using and will be closed and disposed properly when the framework feels like it.
However, one of the developers questioned me and asked a very disturbing question. "Are you entirely sure?". Then I got chicken feet and postponed the answer. Is there anything I could be missing?

A: Yes, the using blocks will always dispose the objects, no matter what. (Well, short of events like a power outage...)
Also, the disposing of the objects is very predictable, that will always happen at the end of the using block. (Once the objects are disposed, they are removed from the finalizer queue and are just regular managed objects that can be garbage collected, which happens when the garbage collector finds it convenient.)
In contrast, the Close calls will only be called if there are no unhandled exceptions inside the block. If you wanted them to surely be executed you would place them in finally blocks so that they are exected even if there is an exception. (That's what the using blocks are using to make sure that they can always dispose the objects.)

A: There are plenty of circumstances in which a using won't dispose of the resource in question.  For example, if you pull the plug on the machine while the using is running, the finally block (which the using is translated to) won't run.
There is no situation in which the finally block wouldn't get run in which duplicating the same cleanup steps inside the using would be any better suited to handle.

A: If disputes like this ever come up, just fire up ILSpy (http://ilspy.net/) and peek inside the framework to see what it is actually doing on the Dispose that gets called from the end of the using statement.
In this case, you are right and all four of StringWriter, StringReader, XmlTextReader, and XmlTextWriter do their disposal work in the Dispose method and Close simply calls Dispose, so those four lines are redundant. (But note that StringWriter and StringReader don't seem to do anything interesting in their Dispose methods.)


Q: Not sure what I am doing wrong - getting is not a function errors I am not sure what I am doing wrong, but I have a few functions inside my component.  However, I'm not able to pass one of those functions down as a prop, I receive a this.nextScene is not a function.
Here's a snippet from my component, and I have commented out where I am having the issue:
  nextScene() {
    this.refs.navigator.push('browse');
  }

  renderNavigationView() {
    return (
      <View style={styles.drawer}>
        <Touchable
          onPress={this.nextScene()}     //issue here, "this.nextScene is not a function"
        >
          <View style={styles.container}>
            <Text style={styles.title}>Browse</Text>
          </View>
        </Touchable>
        <Touchable>
          <View style={styles.container}>
            <Text style={styles.title}>Button</Text>
          </View>
        </Touchable>
      </View>
    );
  }

  render() {
    return (
      <DrawerLayoutAndroid
        ref="drawer"
        drawerWidth={300}
        drawerPosition={DrawerLayoutAndroid.positions.Left}
        renderNavigationView={this.renderNavigationView}>
        <Navigator
          ref="navigator"
          configureScene={(route) => {
            if (Platform.OS === 'android') {
              return Navigator.SceneConfigs.FloatFromBottomAndroid;
            }
          } }
          initialRoute={{}}
          renderScene={this.renderScene}
          />
      </DrawerLayoutAndroid>
    );
  }

Thanks!

A: If you take a look at the component you are rendering, and at the renderNavigationView prop:
renderNavigationView={this.renderNavigationView}

It seems fine, but since the this context in functions is window by default, this refers to window in renderNavigationView. Consider your onPress event handler:
onPress={this.nextScene()}

Since you use this.nextScene() and this refers to window in a function, you're effectively trying to do window.nextScene which does not exist, thus throwing the error. (Also note that that is an invocation - not a reference. Remove the parentheses).

So if I try this.nextScene.bind(this), I get a cannot read property 'bind' of undefined

This is because the function is undefined because window.nextScene doesn't exist. To fix this, use Function.prototype.bind to bind the this correctly on both renderNavigationView and nextScene:
renderNavigationView={this.renderNavigationView.bind(this)}

What bind does in this situation is set the this context in the function. Since this here refers to the class, the class will be used to execute the nextScene method which should work correctly. You must also use bind on nextScene because inside nextScene we want this to refer to the class, not window:
onPress={this.nextScene.bind(this)}

A: Another alternative to using the bind method that winter pointed out in his answer is to use arrow functions which automatically bind this to the parent context for you.
class MyComponent extends React.Component {
  clickHandler = (e) => {
    // do stuff here
  }

  render() {
    return (
      <button onClick={this.clickHandler}></button>
    )
  }
}


Q: A class extending Ext.Window ignores constructor parameters I am trying to create a popup window by extending Ext.Window class:
Ext.define('mine.nameCreationPopup',{
extend: 'Ext.Window',
alias: 'nameCreationPopup',

config:{
    title: 'aTitle', //default value
    width: 700 //default value
},

constructor: function(config){
    this.initConfig(config);
    this.superclass.constructor.call
    (this, {
        title: config.title,
        width: config.width,
        height: 300, //ignored from now on
        layout: 'fit',
        bodyStyle: 'padding:5px;',
        modal: true,
        resizable: false
    });
}

Now, creation:
var pops = Ext.create('nameCreationPopup',{title:'Dunno'});
pops.show();
pops.center();

Width and title are currectly set (title is Dunno, while width is 700 as default value) anyway height and the rest of window attributes are just ignored.
How come?

A: That is not the way how Ext.define should look like. Either configure the window directly (inline) or use initComponent. Inline configuration:
Ext.define('mine.nameCreationPopup',{
    extend: 'Ext.Window',
    alias: 'widget.nameCreationPopup',
    title: 'aTitle',
    width: 700,
    height: 300, //ignored from now on
    layout: 'fit',
    bodyStyle: 'padding:5px;',
    modal: true,
    resizable: false
});

initComponent:
Ext.define('mine.nameCreationPopup',{
    extend: 'Ext.Window',
    alias: 'widget.nameCreationPopup',
    initComponent:function() {
        Ext.applyIf(this, {
            title: 'aTitle',
            width: 700,
            height: 300, //ignored from now on
            layout: 'fit',
            bodyStyle: 'padding:5px;',
            modal: true,
            resizable: false
        });
        this.callParent(arguments);
    }
});


Q: xstream.fromXML returns a Class Using XStream 1.2.2
The XML document:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" protocol="OCI" xmlns="C">
<sessionId xmlns="">192.168.1.19,299365097130,1517884537</sessionId>
  <command xsi:type="AuthenticationRequest" xmlns="">
    <userId>me@somewhere.com</userId>
  </command>
</Document>

I'm trying to parse into to a Document;
public class Document {
    private String sessionId;
    public Command command;
    public Command getCommand() {
        return this.command;
    }
    public void setCommand(Command command) {
        this.command = command;
    }
    public String getSessionId() {
        return sessionId;
    }
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
}

Parsing code is:
    XStream xstream = new XStream();
    xstream.alias("Document", Document.class);
    xstream.alias("sessionId", String.class);
    xstream.alias("command", Command.class);
    xstream.alias("userId", String.class);

    Document doc = (Document) xstream.fromXML(theInput, Document.class);

but this throws:

java.lang.ClassCastException: java.lang.Class cannot be cast to com.mycompany.ocip.server.model.Document

because the returned object from fromXml is of type: Class<com.mycompany.ocip.server.model.Document>
Shouldn't I expect it to return a com.mycompany.ocip.server.model.Document instance?

A: That needs to be:
Document doc = (Document) xstream.fromXML(theInput);

If you pass in a second parameter, XStream will try to populate that with the values from the XML. Since in your code, you're passing in a class object, XStream will try to populate the class object and return it.
The JavaDoc has the details.


Q: changing slice colour of a pie chart in excel VBA Initially I wrote a function which changes the appearance of a series of pie-charts according to predefined colour themes
    Function GetColorScheme(i As Long) As String
Const thmColor1 As String = "C:\Program Files\Microsoft Office\Document Themes 14\Theme Colors\Blue Green.xml"
Const thmColor2 As String = "C:\Program Files\Microsoft Office\Document Themes 14\Theme Colors\Orange Red.xml"
    Select Case i Mod 2
        Case 0
            GetColorScheme = thmColor1
        Case 1
            GetColorScheme = thmColor2
    End Select
End Function

However, the paths are not constant and I would like to define each Pie chart slice on its own by an rgb colour.
I found here on stackoverflow in a previosu topic (How to use VBA to colour pie chart)  a way to change the colour of each slice of a pie chart
but I don't knwo how to implement the code into the function mentioned above. Could I potentially write
    Function GetColorScheme(i As Long) As String

    Select Case i Mod 2
        Case 0
            Dim clr As Long, x As Long

For x = 1 To 3
    clr = RGB(0, x * 8, 0)
    With ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Points(x)
        .Format.Fill.ForeColor.RGB = clr
    End With
Next x
        Case 1
            Dim clr As Long, x As Long

For x = 1 To 3
    clr = RGB(0, x * 8, 0)
    With ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Points(x)
        .Format.Fill.ForeColor.RGB = clr
    End With
Next x
    End Select
End Function

The function is linked to the main part of the script (which is)
For Each rngRow In Range("PieChartValues").Rows
chtMarker.SeriesCollection(1).Values = rngRow
ThisWorkbook.Theme.ThemeColorScheme.Load GetColorScheme(thmColor)
chtMarker.Parent.CopyPicture xlScreen, xlPicture
lngPointIndex = lngPointIndex + 1
chtMain.SeriesCollection(1).Points(lngPointIndex).Paste
thmColor = thmColor + 1

where the line
 ThisWorkbook.Theme.ThemeColorScheme.Load GetColorScheme(thmColor)

gets the value of the function  (see first bit of code - the original function) but now I don#t longer have the thmColor variable defined and don't knwo how to best implement the code into the function part

A: Something like this (you'll need to adjust the colors to suit your needs)
http://www.rapidtables.com/web/color/RGB_Color.htm
Sub ApplyColorScheme(cht As Chart, i As Long)

    Dim arrColors

    Select Case i Mod 2
        Case 0
            arrColors = Array(RGB(50, 50, 50), _
                              RGB(100, 100, 100), _
                              RGB(200, 200, 200))
        Case 1
            arrColors = Array(RGB(150, 50, 50), _
                              RGB(150, 100, 100), _
                              RGB(250, 200, 200))
    End Select

    With cht.SeriesCollection(1)
        .Points(1).Format.Fill.ForeColor.RGB = arrColors(0)
        .Points(2).Format.Fill.ForeColor.RGB = arrColors(1)
        .Points(3).Format.Fill.ForeColor.RGB = arrColors(2)
    End With

End Sub

Example usage:
chtMarker.SeriesCollection(1).Values = rngRow
ApplyColorScheme chtMarker, thmColor
chtMarker.Parent.CopyPicture xlScreen, xlPicture


Q: Screen Tearing Nvidia/Intel I just installed Ubuntu on my laptop (GTX 960M / I7-6700HQ - Intel HD530) and it would not let me past the lockscreen until I re-installed the nvidia driver (it installed driver 370, I just used ubuntu-drivers autoinstall).
After installing the nvidia driver my system now works but I have some awful screen tearing even when just moving windows around and when scrolling through web pages it's even worse.
Things I've tried so far:

*

*Changing GPU to use in NVidia XServer settings

*Adding "TearFree" "true" to xorg.conf for the intel device

What else can I try?

A: I have coded a script which switches between Intel and NVIDIA's video card. Besides switching between them it also FIXES video/screen tearing when using INTEL video card. NVIDIA video card still showing video/screen tearing problems to which I haven't found a solution so far.
Here's the script on GitHub
#!/bin/bash
# -------------------------------------------------------
# A shell script that fixes screen tearing on intel video cards and switches between nvidia and intel graphic cards
# Written by: Bruno Assis
# Created on: 25/03/2017
# -------------------------------------------------------

#asks for sudo if the user uid != 0 then calls the script again with the current user name
(( EUID != 0 )) && exec sudo -- "$0" "$@$USER"

#-----------------
#----Settings-----
#-----------------

PREVIOUS_USER=$1
SCRIPT_NAME="20-intel.conf"
CONF_BASE_PATH="/etc/X11/"
CONF_BASE_DIR="xorg.conf.d"
CONF_PATH="/etc/X11/$CONF_BASE_DIR/"
CONF_FILE_PATH="$CONF_PATH$SCRIPT_NAME"
CURRENT_VIDEO_CARD=""

#-----------------
#----Functions----
#-----------------

#creates the config file.
function CreateTearingFreeFile {
    echo 'Section "Device"' >> $1
    echo '   Identifier  "Intel Graphics"' >> $1
    echo '   Driver      "intel"' >> $1
    echo '   Option      "TearFree"    "true"' >> $1
    echo "EndSection" >> $1
}

#switches the environment to use nvidia graphics card
function SwitchToNvdia {
    echo -e "\n Switching to nvidia."
    rm $CONF_FILE_PATH
    prime-select nvidia
}

#switches the environment to use intel's graphics card
function SwitchToIntel {
    echo -e "\n Switching to Intel."
    cd $CONF_PATH
    CreateTearingFreeFile $SCRIPT_NAME
    prime-select intel
}

function LogoutFromCurrentSession {
    echo -e "\n You'll need to logout in order to changes take effect."
    echo -e "\n Do you wish to logout now? (y | n)"
    read -n 1 option
    if [[ "$option" = "y" || "$option" = "Y" ]]; then
        #log out from the current session for the current user
        su -c "kill -9 -1" "$PREVIOUS_USER"
    fi
}

function SetupEnvironment {

    if [ ! -d "$CONF_BASE_PATH" ]; then
        echo -e "\n error: could not find $CONF_BASE_PATH."
        exit 1
    else
        if [ ! -d "$CONF_PATH" ]; then
            echo -e "\n could not find $CONF_BASE_DIR."
            echo -e "\n trying to create it."
            cd $CONF_BASE_PATH
            mkdir $CONF_BASE_DIR
            if [ ! -d "$CONF_PATH" ]; then
                echo -e "\n could not create $CONF_BASE_DIR folder."
                exit 1
            else
                echo -e "\n $CONF_BASE_DIR folder created successfully."
            fi
        fi
    fi
}

function CheckForCurrentVideoCardInUse {
    local _VIDEO_CARD=`glxinfo|egrep "OpenGL vendor|OpenGL renderer*"`
    if [[ $_VIDEO_CARD == *"NVIDIA"* && $_VIDEO_CARD == *"GeForce"* ]]; then
        CURRENT_VIDEO_CARD="NVIDIA"
    elif [[ $_VIDEO_CARD == *"Intel"* && $_VIDEO_CARD == *"Intel"* ]]; then
        CURRENT_VIDEO_CARD="INTEL"
    else
        ErrorHandler
    fi
}

function ErrorHandler {
        echo -e "\n Could not find your video card"
        echo -e "\n Please use glxinfo to check if the name is correct or if you are using NVIDIA's or Intel's card"
        exit 1
}

#------------------
#--Program Flow ---
#------------------

#Setups the environment if it hasn't already been set.

CheckForCurrentVideoCardInUse
SetupEnvironment

echo -e " current video card in use: $CURRENT_VIDEO_CARD"

#If the file exists then we should delete it and start nvidia

if [ $CURRENT_VIDEO_CARD == "INTEL" ]; then
    echo -e "\n Switch graphics card to NVIDIA? (y | n)"
    read -n 1 option
    if [[ "$option" == "y" || "$option" == "Y" ]]; then
        SwitchToNvdia
        LogoutFromCurrentSession
    fi
elif [ $CURRENT_VIDEO_CARD == "NVIDIA" ]; then
    echo -e "\n Switch graphics card to INTEL? (y | n)"
    read -n 1 option
    if [[ "$option" == "y" || "$option" == "Y" ]]; then
        SwitchToIntel
        LogoutFromCurrentSession
    fi
else
    ErrorHandler
fi


Q: SQL Query to get the Result in One Scan without using analytical function I have a table named Employee Which has 3 columns EmployeeID Award Date and Award
| EMPOYEEID | AwardDate | Award
|1          | 10-03-2018| EOY
|1          | 14-08-2018| EBF
|2          | 10-03-2017| EOY
|3          | 10-03-2016| EOY
|2          | 31-12-2017| COINS
|1          | 31-08-2017| COINS

Using SQL query in oracle, What i want is without using analytical function i want to get the first award and last award date for each employee in one scan.
Below is and example
ID|LastDate  | FirstAward
  1|10-03-2018|31-08-2017
  2|31-12-2017|10-03-2017

A: use aggregate function
select EMPOYEEID, max(AwardDate) LastDate, min(AwardDate) FirstAward
from table_name t1
group by EMPOYEEID


Q: Some images on a page is not shown through Varnish Cache-304 Not modified I am using varnish to speed up a customer's website load time. I have a problem with the images on a page. The Images on a page are not shown on the page. here is the chrome output headers when I hit Ctrl+f5:
Request URL:https://DOMAINNAME/wp-content/uploads/2017/12/telegram-768x255.png
Request Method:GET
Status Code:200 OK
Remote Address:IPADDRESS:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Accept-Ranges:bytes
Age:28
Connection:keep-alive
Content-Length:96169
Content-Type:image/png
Date:Sat, 30 Dec 2017 14:38:40 GMT
Last-Modified:Sat, 16 Dec 2017 11:06:23 GMT
Server:Litespeed
Strict-Transport-Security:max-age=31536000
X-Cache:HIT
X-Configured-By:ServerSetup.co
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
AlexaToolbar-ALX_NS_PH:AlexaToolbar/alx-4.0.1
Cache-Control:no-cache
Connection:keep-alive
Cookie:_ga=GA1.2.1062445401.1514382767; _gid=GA1.2.498856688.1514639806
Host:HOSTNAME
Pragma:no-cache
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36

and here's the output when I hit Enter on the address bar:
Request URL:https://DOMAINNAME/wp-content/uploads/2017/12/telegram-768x255.png
Request Method:GET
Status Code:304 Not Modified
Remote Address:IPADDRESS:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Age:271
Connection:keep-alive
Content-Type:image/png
Date:Sat, 30 Dec 2017 14:42:43 GMT
Last-Modified:Sat, 16 Dec 2017 11:06:23 GMT
Server:Litespeed
Strict-Transport-Security:max-age=31536000
X-Cache:HIT
X-Configured-By:ServerSetup.co
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
AlexaToolbar-ALX_NS_PH:AlexaToolbar/alx-4.0.1
Cache-Control:max-age=0
Connection:keep-alive
Cookie:_ga=GA1.2.1062445401.1514382767; _gid=GA1.2.498856688.1514639806
Host:HOSTNAME
If-Modified-Since:Sat, 16 Dec 2017 11:06:23 GMT
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36

and here's is the varnishlog for the image url:
varnishlog -g request -q "ReqUrl ~ 'wp-content/uploads/2017/12/telegram-768x255.png'"

*   << Request  >> 870337886
-   Begin          req 870337885 rxreq
-   Timestamp      Start: 1514645156.766974 0.000000 0.000000
-   Timestamp      Req: 1514645156.766974 0.000000 0.000000
-   ReqStart       192.168.1.106 42860
-   ReqMethod      GET
-   ReqURL         /wp-content/uploads/2017/12/telegram-768x255.png
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Real-IP: 192.168.1.104
-   ReqHeader      X-Forwarded-For: 46.225.112.57
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      X-Nginx: on
-   ReqHeader      Host: HOSTNAME
-   ReqHeader      Connection: close
-   ReqHeader      Pragma: no-cache
-   ReqHeader      Cache-Control: no-cache
-   ReqHeader      User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36
-   ReqHeader      Accept: image/webp,image/apng,image/*,*/*;q=0.8
-   ReqHeader      Referer: https://DOMAINNAME/contactus/
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: en-US,en;q=0.9
-   ReqHeader      Cookie: _ga=GA1.2.1062445401.1514382767; _gid=GA1.2.498856688.1514639806; _gat=1
-   ReqUnset       X-Forwarded-For: 46.225.112.57
-   ReqHeader      X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   VCL_call       RECV
-   ReqUnset       Cookie: _ga=GA1.2.1062445401.1514382767; _gid=GA1.2.498856688.1514639806; _gat=1
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Encoding: gzip
-   ReqUnset       X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   ReqHeader      X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   ReqUnset       Accept-Language: en-US,en;q=0.9
-   ReqUnset       User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36
-   ReqHeader      cookie:
-   ReqUnset       cookie:
-   ReqHeader      cookie:
-   VCL_return     hash
-   VCL_call       HASH
-   VCL_return     lookup
-   Hit            870337573
-   VCL_call       HIT
-   VCL_return     deliver
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Date: Sat, 30 Dec 2017 14:37:35 GMT
-   RespHeader     Server: Apache/2.2.15 (CentOS)
-   RespHeader     Last-Modified: Sat, 16 Dec 2017 11:06:23 GMT
-   RespHeader     Content-Length: 96169
-   RespHeader     Content-Type: image/png
-   RespHeader     X-Varnish: 870337886 870337573
-   RespHeader     Age: 464
-   RespHeader     Via: 1.1 varnish-v4
-   VCL_call       DELIVER
-   RespHeader     X-Cache: HIT
-   RespUnset      X-Varnish: 870337886 870337573
-   RespUnset      Via: 1.1 varnish-v4
-   RespHeader     X-Configured-By: ServerSetup.co
-   RespUnset      Server: Apache/2.2.15 (CentOS)
-   RespHeader     Server: Apache
-   VCL_return     deliver
-   Timestamp      Process: 1514645156.767049 0.000075 0.000075
-   Debug          "RES_MODE 2"
-   RespHeader     Connection: close
-   RespHeader     Accept-Ranges: bytes
-   Timestamp      Resp: 1514645156.767130 0.000156 0.000081
-   Debug          "XXX REF 2"
-   ReqAcct        631 0 631 267 96169 96436
-   End

The problem is that the image is not shown on the page, but it is shown in preview section of the chrome developer panel. Moreover if I open the image in a new tab in browser it is shown properly.
Varnish version is 4.0.4. and the web server is Apache 2.2.
Edit: When I load the page through varnish I get the following errors on the console tab (chrome):
(index):1820 Uncaught ReferenceError: tinymce is not defined
    at HTMLDocument.<anonymous> ((index):1820)
    at HTMLDocument.dispatch (jquery.js:3)
    at HTMLDocument.r.handle (jquery.js:3)
    at Object.trigger (jquery.js:3)
    at Object.a.event.trigger (jquery-migrate.min.js:2)
    at HTMLDocument.<anonymous> (jquery.js:3)
    at Function.each (jquery.js:2)
    at a.fn.init.each (jquery.js:2)
    at a.fn.init.trigger (jquery.js:3)
    at HTMLDocument.<anonymous> ((index):1316)

But when I load the page directly from backend server, there is no errors and the images are shown properly!!
Edit:
varnish log for 304 Not Modified
*   << Request  >> 885566068
-   Begin          req 885566067 rxreq
-   Timestamp      Start: 1515309410.697993 0.000000 0.000000
-   Timestamp      Req: 1515309410.697993 0.000000 0.000000
-   ReqStart       192.168.1.106 33782
-   ReqMethod      GET
-   ReqURL         /wp-content/uploads/2017/12/Untitled-1.png
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Real-IP: 192.168.1.104
-   ReqHeader      X-Forwarded-For: 46.225.112.57
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      X-Nginx: on
-   ReqHeader      Host: bigtheme.ir
-   ReqHeader      Connection: close
-   ReqHeader      Cache-Control: max-age=0
-   ReqHeader      User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36
-   ReqHeader      Upgrade-Insecure-Requests: 1
-   ReqHeader      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: en-US,en;q=0.9
-   ReqHeader      Cookie: _ga=GA1.2.1062445401.1514382767; _gid=GA1.2.1237154839.1515307013
-   ReqHeader      If-None-Match: "9a2989-38271-560731bc13e20"
-   ReqHeader      If-Modified-Since: Sat, 16 Dec 2017 11:06:26 GMT
-   ReqUnset       X-Forwarded-For: 46.225.112.57
-   ReqHeader      X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   VCL_call       RECV
-   ReqUnset       Cookie: _ga=GA1.2.1062445401.1514382767; _gid=GA1.2.1237154839.1515307013
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqHeader      Cookie:
-   ReqUnset       Cookie:
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqUnset       X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   ReqHeader      X-Forwarded-For: 46.225.112.57, 192.168.1.106
-   ReqUnset       Accept-Language: en-US,en;q=0.9
-   ReqUnset       User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36
-   ReqHeader      cookie:
-   ReqUnset       cookie:
-   ReqHeader      cookie:
-   VCL_return     hash
-   VCL_call       HASH
-   VCL_return     lookup
-   Hit            885027311
-   VCL_call       HIT
-   VCL_return     deliver
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Date: Sun, 07 Jan 2018 07:15:40 GMT
-   RespHeader     Server: Apache/2.2.15 (CentOS)
-   RespHeader     Last-Modified: Sat, 16 Dec 2017 11:06:26 GMT
-   RespHeader     Content-Length: 230001
-   RespHeader     Content-Type: image/png
-   RespHeader     X-Varnish: 885566068 885027311
-   RespHeader     Age: 33
-   RespHeader     Via: 1.1 varnish-v4
-   VCL_call       DELIVER
-   RespHeader     X-Cache: HIT
-   RespUnset      X-Varnish: 885566068 885027311
-   RespUnset      Via: 1.1 varnish-v4
-   RespHeader     X-Configured-By: ServerSetup.co
-   RespUnset      Server: Apache/2.2.15 (CentOS)
-   RespHeader     Server: Litespeed
-   VCL_return     deliver
-   Timestamp      Process: 1515309410.698046 0.000053 0.000053
-   RespProtocol   HTTP/1.1
-   RespStatus     304
-   RespReason     Not Modified
-   RespReason     Not Modified
-   RespUnset      Content-Length: 230001
-   Debug          "RES_MODE 0"
-   RespHeader     Connection: close
-   Timestamp      Resp: 1515309410.698061 0.000068 0.000015
-   Debug          "XXX REF 2"
-   ReqAcct        731 0 731 231 0 231
-   End

A: As your console tab shows, the problem is with a HTML document or Javascript (jquery), not with the image itself.
Moreover, why isn't your varnishlog showing the second request?   What server is returning the "304 Not Modified"?   There's something in between Chrome and Varnish.  A Chrome plugin?


Q: Add a property in the dam metadata in touch ui AEM 6.2 I have a use case.
While going to DAM Asset Dialog in AEM 6.2,I want to add a property rootPath: /etc/tags/geometrixx to the tags field.
I am using the concept of overlay and resourceMerger.
My dialog is under this

/libs/dam/content/schemaeditors/forms/default/items/tabs/items/tab1/items/col1/items/tags.

While Overlaying it in apps and add the property in it,it doesn't show anything.
Can anyone help me?

A: Just for testing i have replicated, and it works fine as expected

A: Actually you can't do that by overlaying the dialog, you'll need to rely in DAM Metadata Schemas to achieve that - https://experienceleague.adobe.com/docs/experience-manager-64/assets/administer/metadata-schemas.html?lang=en
From there, and if you want to persist these definitions in your code baseline, you can refer to the location where it gets stored - /conf/global/settings/dam/adminui-extension/metadataschema
Hope it helps


Q: Want to avoid "failed" message trying to install .NET 4.6.2 on Windows 10 Our Installshield package for our product has .NET 4.6.2 as a prerequisite.  It installs that correctly when needed on Windows 7.  On a Windows 10 machine it cannot install it and shows the user a failure message.
From my understanding, .NET is already part of Windows 10 and thus doesn't need to be installed, but Installshield seems to try to do it anyway.  How can we stop Installshield from even trying? or at least hide the error message?


Q: Javascript only validates the first input field I've been trying to validate this form using Javascript, however for some weird reason only the first input field seems to be doing what it is supposed to do. Here's the relevant snippet of code:

<form method="post" name="myform" action="www.google.com" onsubmit="return validateForm(this);">

Your details:

              First Name
                  <input type="text" id="name" name="name"  onblur="validateName(name)" />
              Please enter your name, you can only use alphabetic characters

              Surname
                  <input type="text" id="surname" name="surname" onblur="validateSurname(surname)" />

<input type="reset" value="Reset Form">
<input type="submit" value="Submit">
</form>

Javascript:
function validateName(x)
    {
      var re = /^[A-Za-z]{2,25}$/;

      if(re.test(document.getElementById(x).value)){  /* This checks the input's value corresponds with the regular expression (re) */
        document.getElementById(x).style.background ='#ccffcc'; /* If it does it changes the background colour of the field to green*/
        document.getElementById(x).style.border="4px solid #ccffcc";
        document.getElementById(x + 'Error').style.display = "none"; /* This hides the error message because the function returned as true */
        return true;
      }
      else{ /* If the function doesn't return as true this is what happens */
        document.getElementById(x).style.background ='#e35152'; /* The background colour of the field changes to red */
        document.getElementById(x).style.border="4px solid #e35152";
        document.getElementById(x + 'Error').style.display = "block"; /* This displays the error message */
        return false;
      }
    }

function validateSurname(x)
    {
      var re = /^[A-Za-z]{2,25}$/;

      if(re.test(document.getElementById(x).value)){
        document.getElementById(x).style.background ='#ccffcc';
        document.getElementById(x + 'Error').style.display = "none";
        return true;
        }
      else{
        document.getElementById(x).style.background ='#e35152';
        document.getElementById(x + 'Error').style.display = "block";
        return false;
        }
    }

function validateForm()
{
    var error = 0;
    if(!validateName('name'))
     {
       document.getElementById('nameError').style.display = "block";
       error++;
     }

     if(!validateSurname('surname'))
     {
       document.getElementById('surnameError').style.display = "block";
       error++;
     }

    if(error > 0)
      {
        return false;
      }
      else if(error < 0) {
        return true;
      }
}

A: Maybe these changes will help you:
1) Add the error message you want to show when surname is wrong:
Surname
<input type="text" id="surname" name="surname" onblur="validateSurname('surname')" />

Please enter your surname, you can only use alphabetic characters

2) Pass a string to the parameter instead of a javascript var (e.g. do validateSurname('surname') instead of validateSurname(surname)), as the function you've defined is expecting a string as a parameter.
Fiddle demo: http://jsfiddle.net/uzyLogc1/1/


Q: Select suppliers for each contract that have all codes required by the contract I have a table of contracts that have "requirement codes" (COXA) and a table of suppliers that have "approval codes" (VNDAPP). Contracts can have any number of requirements and suppliers can have any number of approvals.
Example data:
Contract Requirement (COXA):
CONTR   REQMT
7736    1
7736    10
7737    1
7737    4
7737    6
7738    5
7739    1

Supplier Approval (VNDAPP):
VNDNO   REQMT
10019   1
10020   1
10020   2
10020   10
10021   1
10021   4
10021   5
10021   6

Desired Result:
CONTR   VNDNO
7736    10020
7737    10021
7738    10021
7739    10019
7739    10020
7739    10021

In another question I have received a response that works when I specify the contract number in the query:
select sa.supplierid
from supplier_approval sa
    where sa.approvalid IN (
    select cr.requirementid
    from contracts_requirement cr
    where cr.contractid = 7736
 )
group by sa.supplierid
having count(distinct sa.approvalid) = (
    select count(*)
    from contracts_requirement cr
    where cr.contractid = 7736
)

The problem is I need to have matching suppliers for every contract number.
Thanks in advance!

A: You can use CROSS JOIN to generate tuples of (contracts, suppliers, contract requirement), then use LEFT JOIN to match contract requirements with supplier approvals:
SELECT
    contract_requirement.contr,
    suppliers.vndno,
    COUNT(contract_requirement.reqmt) AS req_count,
    COUNT(supplier_approval.reqmt) AS app_count
FROM contract_requirement
CROSS JOIN (
    SELECT DISTINCT vndno
    FROM supplier_approval
) AS suppliers
LEFT JOIN supplier_approval ON suppliers.vndno = supplier_approval.vndno AND contract_requirement.reqmt = supplier_approval.reqmt
GROUP BY contract_requirement.contr, suppliers.vndno
HAVING COUNT(contract_requirement.reqmt) = COUNT(supplier_approval.reqmt)

A: You can use a join and group by and then having to be sure that you have all requirements:
select cr.contr
from (select cr.*, count(*) over (partition by cr.contr) as cnt
      from contract_requirement cr
     ) cr join
     supplier_approval sa
     on sa.approvalid = cr.requirementid
group by cr.contr, cr.cnt
having cr.cnt = count(*)


Q: Within an interface specified by a core component, should it request IReadOnlyCollection or IEnumerable? In thinking about the principle of "be conservative in what you send and liberal in what you accept", I generally try to make my methods receive IEnumerable parameters, but emit a IReadOnlyCollection (except where deferred execution is truly valuable, then I do emit an IEnumerable).
However, I just realized that when specifying methods in an interface, this may be reversed. Is that true?
Should my interface specifications be telling any implementers "I'll give you an IReadOnlyCollection, but you can just give me any old IEnumerable back"? (Again, if deferred execution makes sense, I would provide an IEnumerable as a parameter type instead.) This makes those methods the reverse, accepting a narrow/conservative set but emitting a broad/liberal one. However, this seems right to me because with the dependency inversion, in reality the input arguments when the method is called are really the output arguments of the core system (specifying the interface).
I'm just wondering if my thinking is right on this or not. It seems that making the implementer side as easy as possible is really where the benefit is.
I'm realizing that part of the issue comes from my concern about not requiring implementers to think deeply about whether deferred execution makes sense or not. Knowing when an enumerable will be enumerated can be very important in a system, and with the separation of concerns that an interface can help bring to code, I wouldn't want to be so liberal in what the interface method outputs (which is ultimately an input to the core system) that improperly-deferred IEnumerables get thrown around...
This is not about speed. Not sure why this was raised, but please do not even think for a second about performance implications here. That is not the question.

A: I have similar concerns as you. Technically, you can't guarantee anything about IEnumerable other than that you can enumerate over it once. That may be a benefit--for instance, reading out of a buffered stream. Because the framework didn't support anything less specific than ICollection, I think this became the default for developers who didn't want to expose the ability to add elements to the enumeration. With the advent of .NET 4.5, we finally got the interface that express more properly what's being returned.
Returning IEnumerable for a List isn't wrong, but I do think that returning IReadOnlyCollection is a better choice when you can anticipate the data will be iterated over multiple times. ReSharper, for instance, will warn about multiple iterations over IEnumerable. As a library developer, I think that's more valid than a developer worrying about whether an implementation is deferred or not.


Q: Jquery javascript html label modify value I want to hide a field and show it and also change the value of a variable depending on a checkbox value using jquery.
$(document).ready(function(){
    $('#CompanyName').hide();
    $('#inlineCheckbox1').click(function() {
       var $this = $(this);
       // $this will contain a reference to the checkbox
       if ($this.is(':checked')) {
          $('#CompanyName').show();
          $("label[for='AdresseName']").text('Adresse Name');
       } else {
          $('#CompanyName').hide();
          $("label[for='AdresseName']").text('Name');
       }
   });
});

it shows and hides the textfield fine, but the label text change does not work for me... it's like if the label change line of code is not being executed. What's going on? My HTML is this:
<form class="form-horizontal" role="form">

    It's a company

          <input type="checkbox" id="inlineCheckbox1" value="option1">

        Company Name

          <input type="text" class="form-control" id="companyName" placeholder="Company">

      Name

          <input type="text" class="form-control" id="AdresseName" placeholder="Name">

      <button type="submit" class="btn btn-default">Save</button>

</form>