text:
Q: Huge variance in JNDI lookup times We're experiencing huge variance in response times on a legacy J2EE web application running on Weblogic 10.3. The system consists of two Weblogic server instances (frontend and backend) which run on the same physical server machine and an Oracle database running on a separate host. External measurement tool alerts us every time a login to the system takes more than four seconds. Lately these warnings have been frequent. Looking at the log written by the servlet handling the login requests reveals that the time is spent on an EJB call from the frontend to the backend.
Example of the measured times:
time    ms
8:40:43 25
8:42:14 26
8:44:04 26
8:44:25 26
8:44:47 26
8:46:06 26
8:46:41 7744
8:47:00 27
8:47:37 27
8:49:00 26
8:49:37 26
8:50:03 8213
8:50:57 27
8:51:04 26
8:51:06 25
8:57:26 2545
8:58:13 26
9:00:06 5195

As can be seen, most of the requests (70%, taken from a larger sample) complete in timely fashion but a significant portion of them take a very long time to complete.
The steps performed during the measured time are the following:

*

*JNDI lookup of the session bean offering the authentication interface (frontend)

*Calling the authentication method of the session bean (frontend->backend)

*Reserving a JDBC connection from the connection pool (backend)

*Making a query to the user database (table size is very moderate and the table should be properly indexed) (backend)

*Reading the result set, creating the POJO user object (backend)

*Returning the POJO user object (backend->frontend)

The load on the server machine is very small (99% idle) and the number of users is very moderate. Amount of free memory reported by Weblogic varies between 60% and 90% on both servers. Garbage collection is logged. Major collections are rare and complete in 2-3 seconds when they do occur. Further, the major GC occurances seem not to happen at the same time when long response times are seen. Long response times occur on both busy and non-busy hours. The JDBC connection pool max size is currently set to 80 which is more than the number of concurrent users.
Update:
Got a permission to reboot the system with some more performance logging added. The log clearly shows that the JNDI lookup is the part where the time is spent:
03:01:23.977 PERFORMANCE: looking up foo.bar.Bar from JNDI took 6 ms
03:14:47.179 PERFORMANCE: looking up foo.bar.Bar from JNDI took 2332 ms
03:15:55.040 PERFORMANCE: looking up foo.bar.Bar from JNDI took 1585 ms
03:29:25.548 PERFORMANCE: looking up foo.bar.Bar from JNDI took 7 ms
03:31:09.010 PERFORMANCE: looking up foo.bar.Bar from JNDI took 6 ms
03:44:25.587 PERFORMANCE: looking up foo.bar.Bar from JNDI took 6 ms
03:46:00.289 PERFORMANCE: looking up foo.bar.Bar from JNDI took 7 ms
03:59:28.028 PERFORMANCE: looking up foo.bar.Bar from JNDI took 2052 ms

Looking at the GC logs of the frontend and backend shows that GC is not done when the slow JNDI lookups occur.
The context is got the following way when a session is created:
Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL, url);
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
jndiContext = new InitialContext(ht);

where url is a t3 url pointing to the DNS name and port of the backend server. This should be ok, right?
First thing to pop into mind is to cache the references got from JNDI, at least this was the preferred way to go 10 years ago... But shouldn't Weblogic's InitialContext implementation already do this caching, or does it really fetch the reference from the backend server on each call?
What could be causing the frequent slow JNDI lookups? Is there a workaround for this (e.g. would caching the references help)?

A:
So what could be causing this rather erratic behavior?

Anything we say is likely to be a guess.  Rather than playing that game, here are some suggestions for investigating the problem:

*

*Try using a profiler to see where the time is being spent.

*Try using a network tool (like WireShark) to see if there is anomalous network traffic.

*Add some logging / tracing at key points to see where the time is going.

*Look for Thread.sleep(...) calls.  (Ooops ... that's a guess.)

A: As a first step, I would to try and isolate which part of those steps performed caused the problem by logging the amount of time each of them take. That way you can eliminate things that are irrelevant and focus on the right area, any may be post here again when you figure that out so that people can give specific advice.

A: As StephenC says, some of this is guesswork without adequate logging statements in between. You have clearly listed each element in the transaction, but I assume you don't have a logger.debug which you can switch on which has timestamps on it.
Some questions to look at:
How many beans in pool for each of the front end and backend beans - it should be the max-beans-in-free-pool element of the weblogic-ejb-jar.xml
If you have more requests to the backend EJB than beans available, then there will be a waiting pileup.
Similarly on the JDBC front, you can use the Weblogic console to monitor any contention with getting connections - are you hitting High Counts and Waits in the JDBC Monitoring tab? That should be the next thing to check.


text:
Q: Mongoengine - selecting error I am making an API which uses Mongoengine (MongoDB) and Flask.
I have a problem. I have a mongodb collection - schema:
class Word(EmbeddedDocument):
    word_id = IntField()
    word = StringField()
    translation = StringField()
    strength = IntField()
    meta = {'collection': 'users'}

    def to_dict(self):
        return mongo_to_dict(self)

class User(Document):
    user_id = IntField()
    username = StringField()
    email = EmailField()
    password = StringField()
    words = ListField(EmbeddedDocumentField(Word))
    meta = {'collection': 'users',
    'ordering': ['-user_id']

i can show word with word_id with url api/users/xxx/words/
when i delete word with id 5, and collection will look like this
[
    {
        "username": "xxx",
        "password": "yyy",
        "words": [
            {
                "translation": "ajlkjbc",
                "strength": 1,
                "word": "abjlkc",
                "word_id": 1
            },
            {
                "translation": "ajlkjbc",
                "strength": 1,
                "word": "ahkjc",
                "word_id": 2
            },
            {
                "translation": "aklbc",
                "strength": 5,
                "word": "jklc",
                "word_id": 3
            },
            {
                "translation": "afdfsc",
                "strength": 1,
                "word": "acjj",
                "word_id": 4
            },
            {
                "translation": "dsadf",
                "strength": 1,
                "word": "dvdsf",
                "word_id": 6
            }
        ]
    }
]

The problem is when i go to url api/users/xxx/words/6
It doesn't work.
My code for this url is
@app.route('/api/users/<username>/words/<int:word_id>', methods=['GET'])
def get_words(username):
     user = User.objects(username=username)
     l_user = user.to_json()
     decoded = json.loads(l_user)
     return Response(json.dumps(decoded[0]["words"][word_id-1], sort_keys=False, indent=4),
                mimetype='application/json')

It doesn't work if I delete some word in the middle.

A: A better approach would be to filter out the matching item by id or returning a 404 if not existing eg:
@app.route('/api/users/<username>/words/<int:word_id>', methods=['GET'])
def get_words(username):
     user = User.objects(username=username)
     word = [word for word user.words if word.word_id == word_id]
     if not word:
        return abort(404)
     return Response(word[0].to_json(sort_keys=False, indent=4),
                     mimetype='application/json')

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the time complexity of Collections#sort method in Java? What is the time complexity of Collections#sort method in Java? Which algorithm is used?
Is Collection#sort a good method for sorting an ArrayList of 10^6?

A: This depends on the version of Java you use. But in the end, the Big-O time complexity is still O(N*log(N)).
For Java 6, it's a modified version of mergesort. Check the description here: Collections#sort for Java 6

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.

For Java 7, it was improved: Collections#sort for Java 7 due to enhancement. Note that TimSort has a best case of O(N) and proves to be faster than the previous implementation.

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techiques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.

Is this a good method for sorting an ArrayList of 10^6?

In theory, it is enough to use. But this makes me wonder why would you have to sort the data in memory. If the data comes from a database, then sort it there using an indexed column/field, otherwise check if you know some characteristics of the field you will use for sorting and if you may use a O(N) time complexity algorithm like Bucket Sort or Radix Sort. When there's no other way, use Collections#sort.

A: The time complexity of Collections.sort() is O(n*log(n)) and a list sorted with Collections.sort() will only be sorted after the call to sort().
Information present in collections documentation -

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element
in the low sublist is less than the lowest element in the high sublist).
This algorithm offers guaranteed n log(n) performance.


text:
Q: How to set some part of the registry back to standard in a company? After migration to new domain some registry setting got scrambled.
The standard programm are not working correctly anymore everytime jpg gets opened you get the list with all avaible programms.
Our research so far resulted in finding out that this happened because the setting in the registry are not correct anymore.
One way we got one PC working again was importing the default registry downloaded from this site: https://www.eightforums.com/threads/default-file-associations-restore-in-windows-8.8486/
Sadly its not an official site so we are hesistant using these files company wide.
Is there some other possible solution? Some way to do it with the GPO so that we don't have to do it for every user?
Thank you for your help

A: So only solution seems to be:
- Open regedit as the user not as a admin!

*

*Go to: HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/

*Here open each file extension that makes problem and delete the folder UserChoice

*User has to redefine standards once afterswards it works without problems.
In theory the user could do it themself because no admin is needed.


text:
Q: Why do you not have to create an object in Java? I'm learning Java and one of the things that suprised me is you don't create an object from a class. For example:
class helloworld{
  public static void main(String[] args){
    System.out.println("Hello world!");
  }
}

What I don't understand is that, I have always thought of a class as a blueprint for objects, whereas here you don't create an object and the program simply runs from the class. Is the creation of an object to run themain method from implicit? I haven't exactly phrased this very well and assume that I am missing some piece of understanding - could someone explain?

A: "A class as a blueprint for objects" is a Java 101 way of describing the reality. It helps to  teach you what classes and objects are, but it is not the whole truth.
A class is also a holder of static code and data, which exist on their own, independent of any class instances. You can view it as a kind of namespaced global data.
In your example, the main method itself is such a static method, which can be executed with no existing objects, and System.out refers to an object which exists on its own, attached to a static variable in the System class.

A: If you are using only static methods and variables in java then all the object of that class share the same variables and methods, you dont have to create an object and call.
Also the main method is the entry point for the code to run

A: You do create objects in java. The static keyword shows that the variable, method or nested class belongs to the class/superclass, and not to an object. The main method is declared static so that it can be accessed at runtime; it is not part of an object, it is part of the class. The JVM looks for the main method at runtime.

A: *

*public mean it can be access from any class static

*static mean you don't have to create object or in other word no need of
the new and that what you are asking about

*mean it will not return a value


text:
Q: Get the size of a resource I'm using getClass().getResourceAsStream(path) to read from bundle resources.
How can I know the file size before reading the entire stream?
I can't access them with getClass().getResource(path).toURI() when it's packaged, so that won't work.

A: I tried answer to this post Ask for length of a file read from Classpath in java but they marked it as duplicated of your question so i give my answer here!
It's possible to get the size of a simple file using:
File file = new File("C:/Users/roberto/Desktop/bar/file.txt");
long length = file.length();
System.out.println("Length: " + length);

When file.txt is packaged in a jar the .length() will return always 0.
So we need to use JarFile:
JarFile jarFile = new JarFile("C:/Users/roberto/Desktop/bar/foo.jar");
Object size = jarFile.getEntry("file.txt").getSize();
System.out.println("Size: " + size.toString())

You can get the compressed size too:
JarFile jarFile = new JarFile("C:/Users/roberto/Desktop/bar/foo.jar");
Object compressedSize = jarFile.getEntry("file.txt").getCompressedSize();
System.out.println("CompressedSize: " + compressedSize);

It's still possible getting the size of a file packaged in a jar using the jar command:
jar tvf Desktop\bar\foo.jar file.txt

Output will be: 5 Thu Jun 27 17:36:10 CEST 2019 file.txt
where 5 is the size.
You can use it in the code:
Process p = Runtime.getRuntime().exec("jar tvf C:/Users/roberto/Desktop/bar/foo.jar file.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(p.getInputStream(), writer, Charset.defaultCharset());
String jarOutput = writer.toString();

but jdk is required to run the jar command.

A: This question has some specific solutions: How do I list the files inside a JAR file?, specifically, using a FileSystem API since Java 7.
It should work for files in a JAR and unpacked files. I'm not sure it will work for a JAR packed in a WAR, for instance.

A: Naturally you cannot query the total size of a stream, since by definition it does not make the whole file available to you. Think of popping your hand in a river. You have a piece of the stream,but you have to put the entire river in your hand to know the total volume.
In this case, you have to read the entire file as a stream and count the size. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of compressed resource. The classloader does not have to provide a file handle to the resource in this case


text:
Q: iOS background task detect screen is on or off I am developing an app that logs down the screen on/off events. It's a kind of smartphone usage analysis app. All the app does is to write down a log like this:
2015 July 25 at 03:54:12 PM - Screen on
2015 July 25 at 03:59:38 PM - Screen off
2015 July 25 at 04:20:52 PM - Screen on
2015 July 25 at 04:22:32 PM - Screen off
...
2015 July 26 at 10:20:32 AM - Screen on
2015 July 26 at 10:22:11 AM - Screen off
2015 July 26 at 11:30:38 AM - Screen on
2015 July 26 at 10:31:02 AM - Screen off
...

*

*"Screen on": user press home button (or power button) and enter passcode/unlock password if there is any.

*"Screen off": user press power button  to turn off the screen.

I was able to find some way to do this this on Android using the broadcast receiver to capture the events sent by the system. But in iOS there seems to be a problem since iOS only allows background services to run several minutes, I am not even sure if I can detect the "screen on/off" event on iOS.
I did some researches on this and found some articles, but those weren't help much:

*

*http://www.macworld.com/article/1164616/how_ios_multitasking_really_works.html

*Lock Unlock events iphone
My question is "Is it possible to make an app like this in iOS (latest version - 8.4) ?"
Thanks.

A: It may not be possible to meet all your requirements within the published, non jail broken iOS device using the background service.  I can see the notifications come across, I'm just not sure about the backgrounding.
Since others have been saying it's not possible, I'm digging a little deeper here to see just how much can be done.
Because iOS is currently restricted to a small number of background modes (situations where events are delivered in the background), or a mode where your app is granted a few minutes of time after the user navigates away from your app, the primary issue is going to be tricking the system into allowing your app to get time in the background when needed.
There are several background modes, described in the Programming Guide to Background Execution.  If you can, for example, send push notifications periodically to awaken the app to "download content", you may be able to get some time periodically as the system sees fit to do so.
The background Daemon is a possible solution, but only for your own use, but not via the App Store.  The official take on this is in the App Store Review Guidelines -- the relevant section is 2.8 (presumably you'd get your daemon on by having the app install it "behind the scenes"):

2.8 Apps that install or launch other executable code will be rejected

There may be some system logs that iOS keeps for itself; if you can gain access to those, you'd have your data.  I doubt, however, that this is available programmatically from a non jail broken phone.
I was able to test out some Swift (2.0) code that uses the Darwin Notifications mentioned in one of the Stack Overflow discussions that your original question led to: Lock / Unlock Events for iPhone.  I didn't actually run in the background, but I did verify that the events are eventually delivered, even if the app isn't running when the actual lock event takes place.  When my app is switched in, the notification gets called.  So, if you were able to get time from the system, you'd get the (delayed) notification when Apple's algorithms decide to give you time.
The code snippet (I stuffed it into some random app) that allows the listening is as follows:
import UIKit
import CoreFoundation

class MainViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // CoreFoundation compatible types
        var cfstr: CFString = "com.apple.iokit.hid.displayStatus" as NSString
        var notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()

        CFNotificationCenterAddObserver(notificationCenter, nil,
            { (noti: CFNotificationCenter!, aPtr: UnsafeMutablePointer<Void>, aStr: CFString!, bPtr: UnsafePointer<Void>, aDict: CFDictionary!) -> () in
                print("got notification") }, cfstr, nil, CFNotificationSuspensionBehavior.DeliverImmediately)

    }
    // [... more stuff ...]
}

A: If you can use the C or objective C code i guess this code might help you.
   notify_register_dispatch("com.apple.iokit.hid.displayStatus", &notify_token, dispatch_get_main_queue(), ^(int token) {
    uint64_t state = UINT64_MAX;
    notify_get_state(token, &state);
    //notify_cancel(token);
    debug("com.apple.iokit.hid.displayStatus = %llu", state);
});

Provided that you are able to run your app in background modes.
State will provide the screen on off status


text:
Q: Printing list of enums in a particular namespace C# Is there a way to print all the enums in C# class library or namespace? I want the name to be printed with its values.
For example if I have the namespace as below:
namespace MyCompany.SystemLib
{
    public enum ItemStatus
    {
        None = 0,
        Active = 1,
        Inactive = 2
    }

    public enum MyEnum
    {
        EnumVal1 = 1,
        EnumVal2 = 2,
        EnumVal3 = 3,

    }
}

I would like to print them delimited as below (to a textfile) Bullet given for clarity here not needed in output.

*

*ItemStatus,None=0,Active=1,Inactive=1

*MyEnum,EnumVal1=1,EnumVal2=2,EnumVal3
I don't know where to start. Any help is appreciated.

A: Reflection to the rescue!
List<string> allEnums = new List<string>();
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes());

foreach (Type type in allTypes)
{
    if (type.Namespace == "MyCompany.SystemLib" && type.IsEnum)
    {
        string enumLine = type.Name + ",";
        foreach (var enumValue in Enum.GetValues(type))
        {
            enumLine += enumValue + "=" + ((int)enumValue).ToString() + ",";
        }

        allEnums.Add(enumLine);
    }
}

The first line goes over all assemblies currently loaded in memory (because a namespace can be scattered over many DLLs and EXEs) and filters out those in the right namespace, and that are enums. This can be streamlined into a LINQ query if you'd like.
The inner loop goes over the values of the enum, and uses GetName to match the string to the value.

A: Try using the Enum.GetNames() method.

A: It can be done using LINQ and Reflection ofcourse.
var asm = Assembly.LoadFrom("path of the assembly");
var enums = asm.GetTypes().Where(x => x.IsEnum).ToList();

var result = enums
            .Select(
                x =>
                    string.Format("{0},{1}", x.Name,
                        string.Join(",",Enum.GetNames(x)
                        .Select(e => string.Format("{0}={1}", e, (int)Enum.Parse(x, e))))));

File.WriteAllLines("path", result);


text:
Q: Get records only if consecutive days per user is 30 or greater I have the following data being returned from a query. Essentially I am putting this in a temp table so it is now in a temp table that I can query off of(Obviously a lot more data in real life, I am just showing an example):
EmpId      Date
1        2011-01-01
1        2011-01-02
1        2011-01-03
2        2011-02-03
3        2011-03-01
4        2011-03-02
5        2011-01-02

I need to return only EmpId's that have 30 or more consecutive days in the date column. I also need to return the day count for these employees that have 30 or more consecutive days. There could potentially be 2 or more sets of different consecutive days that are 30 or more days. iIn this instance I would like to return multiple rows. So if an employee has a date from 2011-01-01 to 2011-02-20 then return this and the count in one row. Then if this same employee has dates of 2011-05-01 to 2011-07-01 then return this in another row. Essentially all breaks in consecutive days are treated as a seperate record.

A: Using DENSE_RANK should do the trick:
;WITH sampledata
    AS (SELECT 1 AS id, DATEADD(day, -0, GETDATE())AS somedate
        UNION ALL SELECT 1, DATEADD(day, -1, GETDATE())
        UNION ALL SELECT 1, DATEADD(day, -2, GETDATE())
        UNION ALL SELECT 1, DATEADD(day, -3, GETDATE())
        UNION ALL SELECT 1, DATEADD(day, -4, GETDATE())
        UNION ALL SELECT 1, DATEADD(day, -5, GETDATE())
        UNION ALL SELECT 1, DATEADD(day, -10, GETDATE())
        UNION ALL SELECT 1, '2011-01-01 00:00:00'
        UNION ALL SELECT 1, '2010-12-31 00:00:00'
        UNION ALL SELECT 1, '2011-02-01 00:00:00'
        UNION ALL SELECT 1, DATEADD(day, -10, GETDATE())
        UNION ALL SELECT 2, DATEADD(day, 0, GETDATE())
        UNION ALL SELECT 2, DATEADD(day, -1, GETDATE())
        UNION ALL SELECT 2, DATEADD(day, -2, GETDATE())
        UNION ALL SELECT 2, DATEADD(day, -6, GETDATE())
        UNION ALL SELECT 3, DATEADD(day, 0, GETDATE())
        UNION ALL SELECT 4, DATEADD(day, 0, GETDATE())
        UNION ALL SELECT 5, DATEADD(day, 0, GETDATE()))
   , ranking
    AS (SELECT *, DENSE_RANK()OVER(PARTITION BY id ORDER BY DATEDIFF(day, 0, somedate)) - DATEDIFF(day, 0, somedate)AS dategroup
          FROM sampledata)
    SELECT id
         , MIN(somedate)AS range_start
         , MAX(somedate)AS range_end
         , DATEDIFF(day, MIN(somedate), MAX(somedate)) + 1 AS consecutive_days
      FROM ranking
     GROUP BY id, dategroup
     --HAVING DATEDIFF(day, MIN(somedate), MAX(somedate)) + 1 >= 30 --change as needed
     ORDER BY id, range_start

A: Something like this should do the trick, haven't tested it though.
SELECT
  a.empid
  , count(*) as consecutive_count
  , min(a.mydate) as startdate
FROM (SELECT * FROM logins ORDER BY mydate) a
INNER JOIN (SELECT * FROM logins ORDER BY mydate) b
  ON (a.empid = b.empid AND datediff(day,a.mydate,b.mydate) = 1
GROUP BY a.empid, startdate
HAVING consecutive_count > 30

A: This is a good case for a recursive CTE.  I stole the data table from @Davin:
with data AS --sample data
( SELECT 1 as id ,DATEADD(DD,-0,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-1,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-2,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-3,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-4,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-5,GETDATE()) as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-10,GETDATE()) as date UNION ALL
SELECT 1 as id ,'2011-01-01 00:00:00.000' as date UNION ALL
SELECT 1 as id ,'2010-12-31 00:00:00.000' as date UNION ALL
SELECT 1 as id ,'2011-02-01 00:00:00.000' as date UNION ALL
SELECT 1 as id ,DATEADD(DD,-10,GETDATE()) as date UNION ALL
SELECT 2 as id ,DATEADD(DD,0,GETDATE()) as date UNION ALL
SELECT 2 as id ,DATEADD(DD,-1,GETDATE()) as date UNION ALL
SELECT 2 as id ,DATEADD(DD,-2,GETDATE()) as date UNION ALL
SELECT 2 as id ,DATEADD(DD,-6,GETDATE()) as date UNION ALL
SELECT 3 as id ,DATEADD(DD,0,GETDATE()) as date UNION ALL
SELECT 4 as id ,DATEADD(DD,0,GETDATE()) as date UNION ALL
SELECT 5 as id ,DATEADD(DD,0,GETDATE()) as date   )
,CTE AS
(
    SELECT id, CAST(date as date) Date, Consec = 1
    FROM data
    UNION ALL
    SELECT t.id, CAST(t.date as DATE) Date, Consec = (c.Consec + 1)
    FROM data T
    INNER JOIN CTE c
        ON T.id = c.id
        AND CAST(t.date as date) = CAST(DATEADD(day, 1, c.date) as date)

)

SELECT id, MAX(consec)
FROM CTE
GROUP BY id
ORDER BY id

Basically this generates a lot of rows per person, and measures how many days in a row each date represents.

A: Assuming there are no duplicate dates for the same employee:
;WITH ranged AS (
  SELECT
    EmpId,
    Date,
    RangeId = DATEDIFF(DAY, 0, Date)
            - ROW_NUMBER() OVER (PARTITION BY EmpId ORDER BY Date)
  FROM atable
)
SELECT
  EmpId,
  StartDate = MIN(Date),
  EndDate   = MAX(Date),
  DayCount  = DATEDIFF(DAY, MIN(Date), MAX(Date)) + 1
FROM ranged
GROUP BY EmpId, RangeId
HAVING DATEDIFF(DAY, MIN(Date), MAX(Date)) + 1 >= 30
ORDER BY EmpId, MIN(Date)

DATEDIFF turns the dates into integers (the difference of days between the 0 date (1900-01-01) and Date). If the dates are consecutive, the integers are consecutive too. Using the data sample in the question as an example, the DATEDIFF results will be:
EmpId  Date        DATEDIFF
-----  ----------  --------
1      2011-01-01  40542
1      2011-01-02  40543
1      2011-01-03  40544
2      2011-02-03  40575
3      2011-03-01  40601
4      2011-03-02  40602
5      2011-01-02  40543

Now, if you take each employee's rows, assign row numbers to them in the order of dates, and get the difference between the numeric representations and row numbers, you will find that the difference stays the same for consecutive numbers (and, therefore, consecutive dates). Using a slightly different sample for better illustration, it will look like this:
Date        DATEDIFF  RowNum  RangeId
----------  --------  ------  -------
2011-01-01  40542     1       40541
2011-01-02  40543     2       40541
2011-01-03  40544     3       40541
2011-01-05  40546     4       40542
2011-01-07  40548     5       40543
2011-01-08  40549     6       40543
2011-01-09  40550     7       40543

The specific value of RangeId is not important, only the fact that it remains the same for consecutive dates matters. Based on that fact, you can use it as a grouping criterion to count the dates in the group and get the range bounds.
The above query uses DATEDIFF(DAY, MIN(Date), MAX(Date)) + 1 to count the days, but you could also simply use COUNT(*) instead.


text:
Q: correct way of binding data user_model
public function rating_data()
{
    $recipe_id = 1;

    $this->db->select('recipe_id');
    $this->db->from('rate');
    $this->db->where('recipe_id', $recipe_id);
    $count_user = $this->db->count_all_results();
    return $count_user;
}

main
public function get_rating_data()
{
    $postdata = json_decode(file_get_contents("php://input"));
    $rate = $this->User_model->rating_data($postdata);
    echo json_encode($rate);
}

service
get: function() {
    return $http.post("http://localhost/admin-recipick/api/Main/get_rating_data").then(function(result){
        return result.data;
    })
}

view
<div ng-repeat="rate in ratingdata">
    {{rate}}
</div>

I tried using console.log to view the output and it displays what i am looking for but i don't know how to bind datas
controller
RatingList.get().then(function(payload) {
    $scope.ratingdata = payload.data;
    console.log(payload);
});

A: Change your function by this
  public function get_rating_data()
  {
   $postdata = json_decode(file_get_contents("php://input"));
   $rate = $this->User_model->rating_data($postdata);
   echo json_encode($rate);
    $scope.resultdata=$rate;
  }


text:
Q: Switching stylesheet with Javascript based on browser I'm currently trying to edit a website for a client which uses Adobe Contribute so it uses a different stylesheet if the user is browsing from a mobile phone. The mobile phone stylesheet is much simpler and strips out background images and styles to reduce load time. I understand it would be better practice to have a completely seperate website for the mobile, but this is not practical for the client as he needs to be able to update his websites content using Contribute.
This is working in some devices already such as the iPhone (last time I tested!) but on my Android phone I have a strange problem. When I visit the URL or click on a link, it displays the website using the default stylesheet. If I refresh the page it then decides to show the site rendered with the mobile stylesheet. It is almost as though the UserAgent is not being picked up by my code until I click refresh.
Here is the code I am using:
<link href="css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    var userAgent = navigator.userAgent;

    if(userAgent.search("Mobile")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";

    if(userAgent.search("Nokia")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";

    if(userAgent.search("SymbianOS")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";
</script>

The script only shows for a few devices but you get the general idea.
My User Agent string is as follows:

Mozilla/5.0 (Linux; U; Android
  2.1-update1; en-gb; T-Mobile_G2_Touch Build/ERE27) AppleWebKit/530.17
  (KHTML, like Gecko) Version/4.0 Mobile
  Safari/530.17

EDIT:
I should add that I have tried to use media queries but this does not work at all on either the iPhone or Android. The code above works a treat on the iPhone. Below is the code I am using when trying to have this work with media queries.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link href="../css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="../css/style_mob.css" />

A: Can´t you use media queries to determine what stylesheet the browser must use? Checking for individual user agents seems the wrong way to go about it.
Edit: I just noticed the media queries code you are using and I noticed you are using a different path: css/style_mob.css when using the javascript and ../css/style_mob.css. Is that a typo or could it be the reason it's not working?

A: Phone browsers cache pages just like desktop browsers do. Before you spend too much time looking into the problem, make sure it's not a caching issue.
Clear the cache on your phone and visit the URL again. Since the CSS loads correctly after a refresh, I wouldn't be surprised if this solved everything.
Also, you mention in your question that it's better to have a separate domain altogether. I say not necessarily. There are many reasons why you would only want to have 1 domain for every platform. @media queries and responsive web design can go great ways.
If you are interested in the subject, you should definitely check out this article from A list apart. It could give you an idea of what the possibilities are.
EDIT:
If it still doesn't work (which it doesn't seem to) then perhaps you should test your user agent code.
Instead of loading your style.css style for everyone, remove that statement, and make it conditional to a browser not being android :
Remove the css line from your html :
<link href="css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />

And then in your javascript :
var normalCss = document.createElement('<link href="css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />');
var mobileCss = document.createElement('<link href="css/mobile.css" id="stylesheet" rel="stylesheet" type="text/css" />');

if(userAgent.search("Android")>=0){
    document.getElementsByTagName("head")[0].appendChild(mobileCss);
}
else {
    document.getElementsByTagName("head")[0].appendChild(normalCss);
}

Clear your cache and test it. Does it load a css the first time or does it load a page without styles?
If it doesn't load the first time, this might mean that the javascript code isn't run on time. How are you calling it? Is it in the head section? Are you using jQuery with $(document).ready or something like that?

A: I have found a workaround for the problem of the android browser not loading a mobile css stylesheet unless you refresh the page.  I call this a work around and not a permanent solution because I have one website where android loads the mobile css on the first try without a problem using:
<link media="handheld, only screen and (max-device-width: 480px)" href="mobile.css" type="text/css" rel="stylesheet" />

But I have another website that uses the same code above to load the css and the android browser refuses to use it unless I refresh the page.  I have tried changing many parts of the html to match the website that does work but all to no avail.  So here is the workaround code:
<link media="handheld, only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="mobile.css" type="text/css" rel="stylesheet" />

"handheld" allows older mobile phones to load mobile.css
"only screen and (max-width: 480px)" forces android devices to load mobile.css on the first try if they have a width of 480px or less.
"only screen and (max-device-width: 480px)" allows new blackberry phones, iphones and USUALLY android devices to load mobile.css if they have a width of 480px or less
Windows mobile 7 phones with IE do not use the new media tags so you have to use this code to get them to load mobile.css:
<!--[if IEMobile 7]>
<link rel="stylesheet" type="text/css" href="mobile.css" media="screen" />
<![endif]-->


text:
Q: Conditional menu mouseout using jQuery Background-Position plugin I currently have a drop-line horizontal menu using an unordered list with the following HTML markup:

Top Link 1

        Top Link 2

Sub Link 1

Sub Link 2

Sub Link 3

Top Link 3

The CSS is far too lengthy to paste in here, but it follows the same structure that I've been using for ages here from CSS Menu Maker - the only difference is that for the sub-menu list items, I have them displayed "inline" with their widths set to "auto" and a bit of left and right padding, and every Top Link menu item with a class of "tier1" uses CSS Sprites. The jQuery is where I am having an issue. Ordinarily, this would be the approach to take:
function animateMenu() {
  $('.menu li a.tier1').css({backgroundPosition:'0 -60px'});
  $('.menu li a.tier1').hover(
     function() {
        $(this).stop(true, true).animate({backgroundPosition:'0 0'},{duration:400})
        .next('ul').css({display:'none'}).stop(true, true).delay(200).slideDown(400);
     },
     function() {
        $(this).stop(true, true).animate({backgroundPosition:'0 -60px'},{duration:250})
        .next('ul').stop(true, true).slideUp(400);
     }
  );
}

Whilst this method works, and visually does what I want it to do, the SubMenu obviously slides back up when I mouseout off the Top Link items. My only workaround for this was to break it into two separate functions:
function animateTopMenu() {
    $('.menu li a.tier1').css({backgroundPosition:'0 -60px'});
    $('.menu li a.tier1').hover(
            function() {
                $(this).stop(true, true).animate({backgroundPosition:'0 0'},{duration:400});
            },
            function() {
                $(this).stop(true, true).animate({backgroundPosition:'0 -60px'},{duration:250});
            }
    );
}

function animateSubMenu(){
    $('.menu li').hover(
            function() {
                $(this).find('ul:first').css({display:'none'}).stop(true, true).delay(200).slideDown(400);
            },
            function() {
                $(this).find('ul:first').stop(true, true).slideUp(400);
            }
    );
}

This helps me keep my SubMenu items hover-able when I mouseout off the Top Link, but what I would ideally like to do is retain the hovered background appearance of the Top Links when I hover over the submenu items, and only revert (and animate) to the normal state once the mouse has moved off either the submenu or the top Link itme itself. This is where I am having difficulties.  I could add and remove a class with CSS "background-positon: 0 0 !important" but then the animation effect is lost.
I'm sorry for the lengthy question, but just wanted to provide as much as possible to get your help!
Thank you!!
-Shalan

A: problem sorted! :D
I should've figured from the start, but anyway, here is what I had to change:

*

*change the CSS such that the top-level List Item gets the background-image, and not its child hyperlink like how I had it.

*change the target element in the Javascript to match with what I did in the CSS.

It makes perfect sense due to the hierarchy of HTML elements - when you hover over the top-level list item, the nested unordered list is made visible allowing the space (using the term loosely) that the top-level list item occupies to "expand" to include its childrens' dimensions. So when you hover over any items in the child list, the parent list item is still 'active', and the hover function works as it should.
I will come back to this post in a few days time to update with the working code, should anyone need.  For now, I just need to finish the remainder of the project!
cheers!


text:
Q: View not displaying for childViewController of another ChildViewController I'm having an issue with a multi-level hierarchy of childViewControllers in iOS/Swift. There are three layers to the current setup from lowest-to-highest:

*

*InfoViewController

*SelectionViewController

*MainViewController
The InfoViewController has a view that is loaded from XIB.
SelectionViewController contains a UIStackView with an InfoViewController and a UIButton.
MainViewController is the top-level VC which is usually embedded in a UINavigationController.
The Problem
When I add the InfoViewController and it's view directly to the MainViewController everything works great.
func setupInfoViewControllerDirectlyOnMainVC () {
    addChildViewController(infoViewController)
    infoViewController.view.embedInside(otherView: infoContainerView)
    infoViewController.didMove(toParentViewController: self)
}

However, if I add the SelectionViewController to the MainViewController using the same method, the embedded InfoViewController doesn't update it's UI - it always looks like the untouched XIB file that it is controlling. When it is NOT embedded in this SelectionViewController is behaves as expected.
As shown below, the UI is visible, but any changes made to it via asking it's ViewController do not show up - it looks exactly like the XIB file it was created from.

Below is the class setup starting with the BasicInfoView followed by the three viewControllers listed above.
BasicInfoView
class PLBasicInfoView: PLDesignableViewFromXib {

    //
    // MARK: Outlets
    //
    //

    @IBOutlet weak var photoView: PFRoundImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var subtitleLabel: UILabel!

    var imageFile:PFFile? {
        didSet {
            photoView.file = imageFile
            photoView.loadInBackground()
        }
    }

    //
    // MARK: Initialization
    //
    //

    override var nameOfXib: String {
        return "PLBasicInfoView"
    }

    override var intrinsicContentSize: CGSize {
        return CGSize(width: super.intrinsicContentSize.width, height: 56)
    }

}

BasicInfoViewController
class PLBasicInfoViewController: UIViewController {

    /**
     The BasicInfoView which will be managed by this controller.
     */
    var basicInfoView = PLBasicInfoView()

    /**
     This is the master stack view which contains all subviews.
     */
    var stackView = UIStackView()

    /**
     PFFile representing the image to be displayed in the imageView. Setting a valid imageFile object automatically laods the image from the server. If set to nil, the defaultImage is displayed instead.
     */
    var imageFile: PFFile? {
        didSet {
            if imageFile != nil {
                basicInfoView.imageFile = imageFile
            } else {
                basicInfoView.photoView.image = defaultImage
            }
        }
    }

    /**
     Default UIImage to be displayed in the imageView if there is no imageFile assigned.
     */
    var defaultImage: UIImage! {
        return #imageLiteral(resourceName: "ios7-camera-outline")
    }

    /**
     Main text of the infoView
     */
    var titleText:String? {
        didSet {
            basicInfoView.titleLabel.isHidden = (titleText == nil)
            basicInfoView.titleLabel.text = titleText
        }
    }

    /**
     Secondary text of the infoView. Displays under titleText.
     */
    var subtitleText:String? {
        didSet {
            basicInfoView.subtitleLabel.isHidden = (subtitleText == nil)
            basicInfoView.subtitleLabel.text = subtitleText
        }
    }

    /**
     Embed our stackView into main view. The custom embedInsider(otherView:UIView) method (UIView extension) will take care of the subview additional as well as all layout constraints.
     */
    func setupStackView () {
        stackView.embedInside(otherView: view)
        stackView.axis = .vertical
        stackView.addArrangedSubview(basicInfoView)
    }

    override
    func viewDidLoad() {
        super.viewDidLoad()
        setupStackView()
    }

}

SelectionViewController
class PLSelectableInfoViewController: UIViewController {

    /**
     If true, the info view will be shown and the selection button will be hidden.
     */
    var isAssigned = false {
        didSet {
            selectionButton.isHidden = isAssigned
            infoView.isHidden = !isAssigned
        }
    }

    /**
     The View controller dispaying the object in question.
     */
    var infoViewController: PLBasicInfoViewController! {
        return PLBasicInfoViewController()
    }

    private
    var infoView: UIView!

    /**
     Button on bottom of stack. Intended to allow user to assign a new value to the contact property.
     */
    var selectionButton = PLButton()

    /**
     Stack view containing all subviews.
     */
    var stackView = UIStackView()

    //
    // MARK: UIViewController Overrides
    //
    //

    override
    func viewDidLoad() {
        super.viewDidLoad()
        setupStackView()
        addInfoView()
    }

    private
    func setupStackView () {
        stackView.embedInside(otherView: view)
        stackView.axis = .vertical
    }

    private
    func addInfoView () {
        addChildViewController(infoViewController)
        infoView = infoViewController.view
        stackView.addArrangedSubview(infoView)
        infoViewController.didMove(toParentViewController: self)
    }

}

Some non-relevant code has been removed
Notes
Please note that in practice, both BasicInfoViewController and SelectionViewController are subclassed. For example, I have a ContactInfoViewController which can be passed a Contact object and display full name, company name and photo (as explained above, this works fine). There is also a subclass of SelectionViewController to complement this: ContactSelectionViewController. ContactSelectionViewController also has a Contact object property which can be assigned and is then passed to the embedded ContactInfoViewController - this is the point at which the data is not displayed. I have included these subclasses below for additional reference.
ContactInfoViewController
Again, this works perfectly when placed directly into the MainViewController.
class PLContactInfoViewController: PLBasicInfoViewController {

    /**
     Contact object managed by this controller.
     */
    var contact: PLContact? {
        didSet {
            if contact == nil {
                titleText = "Not Set"
                subtitleText = nil
                return
            }
            contact?.fetchIfNeededInBackground(block: { (object, error) in
                if let _ = object as? PLContact {
                    self.updateWithContact()
                }
            })
        }
    }

    override
    var defaultImage: UIImage! {
        return #imageLiteral(resourceName: "ios7-contact-outline")
    }

    private
    func updateWithContact () {
        if let c = contact {
            titleText = c.fullName
            imageFile = c.photo
            c.company?.fetchIfNeededInBackground(block: { (object, error) in
                if let comp = object as? PLCompany {
                    self.subtitleText = comp.name
                } else {
                    self.subtitleText = nil
                }
            })
        }
    }

}

ContactSelectionViewController
This VC functions properly, but the embedded ContactInfoViewController does not display data. For some reason, the view from the ContactInfoViewController is not being updated with data when it is embedded inside this controller.
class PLContactAssignmentViewController: PLSelectableInfoViewController {

    /**
     The contact currently selected by this contorller
     */
    var selectedContact: PLContact? {
        didSet {
            isAssigned = !(selectedContact == nil)
            contactInfoViewController.contact = selectedContact
        }
    }

    override
    var infoViewController: PLBasicInfoViewController! {
        return PLContactInfoViewController()
    }

    private
    var contactInfoViewController: PLContactInfoViewController {
        return infoViewController as! PLContactInfoViewController
    }

}

A: Try
    var _infoViewController: PLBasicInfoViewController?
    var infoViewController: PLBasicInfoViewController! {
        if let vc = _infoViewController {
            return vc
        }
        _infoViewController = PLBasicInfoViewController()
        return _infoViewController!
    }

or
lazy var infoViewController: PLBasicInfoViewController = {
        return PLBasicInfoViewController()
    }()

It might be because you are initiating PLBasicInfoViewController every time when you try to access.


text:
Q: Setting a generic ArrayList to zeros I have an ArrayList. I would like to set each element of it to 0. Right now I have:
ArrayList <T extends Number> arr = new ArrayList();

for(int i = 0; i < some_other_array.size(); i++)
{
    arr.add(0)
}

The compiler complains that
error: no suitable method found for set(int,int)
            arr.add(0);
               ^
    method ArrayList.set(int,T) is not applicable
      (actual argument int cannot be converted to T by method invocation conversion)
  where T is a type-variable:
    T extends Number

A: It cannot be done. The method signature for  is
 public T ArrayList<T>.set(int index, T element)

Even though the constraint on T is that it extends Number, it does not mean that it can be constructed from a number.
Consider, for example,
class FortyTwo extends Number {
      public byteValue() { return 42; }
      public intValue()  { return 42; }
      // etc
}

What would you expect the initialization routine to do to an ArrayList<FortyTwo> ?

A: Just change your list declaration to
ArrayList<Number> arr = new ArrayList<Number>();

arr will be capable of holding anything extending Number (which is what you want, I assume).
Now, when you do
arr.set(i, 0)

that 0 will be autoboxed to an Integer. (See for yourself, add 0 and print arr.get(0) instanceof Integer.)
If you wanted to add doubles or longs for instance, you could use the literals 0d and 0L, respectively.

A: This should work for your case: arr.set(i, Integer.valueof(0));
Or you can reuse this handy standard API: Collections.fill(arr, Integer.valueof(0));

A: Try changing the declaration of your ArrayList to
ArrayList<Integer> arr = new ArrayList<Integer>();

The Integer class supports auto-boxing, while the Number class does not. Also, the add() method may be more applicable.

A: Why you want to set the value to 0, it will be automaticaly zero as ArrayList object will be instantiated. So the code will be useless as the size will be zero at the time so loop will not be executed.

A: Well, I think you're a little confused about how ArrayList actually works. When you create an ArrayList, it's always empty. Even if you specify a size:
ArrayList<Integer> arr = new ArrayList<Integer>(20);

That 20 just means "initial capacity", not "starting number of elements". As a result, set will never work  because there are simply no elements. Even if you fix your compiler issue like this:
arr.set(i, Integer.valueOf(0));

Or like this:
ArrayList<Number> arr = new ArrayList<Number>();

It's not even going to do anything because arr.size() is zero, so the for loop won't even run.
The key here is that ArrayList is not an actual array. It wraps an array, and will expand its inner array when it has too many elements. In other words, I can't do this:
ArrayList<Integer> arr = new ArrayList<Integer>(20);
arr.get(0); // Throws an out of bounds exception

Now, that being said, if you want to start with 20 zeroes in your ArrayList, you can use the add method in your loop and i < 20 instead:
for(int i = 0; i < 20; i++) {
    arr.add(Integer.valueOf(0));
}

This will add 20 zeroes to arr. Your code, even after fixing the error, will not.

A: You can try this (to the best of my knowledge, you cannot add primitive types to ArrayList):
ArrayList<Integer> arr = new ArrayList<Integer>();

for(int i = 0; i < someNumber; i++)
{
   arr.add(0);
}

Remember that when size is 0 because it does not have any default values and the capacity is what you should be looking at (You can set the capacity in the constructor.)


text:
Q: bluetooth low energy advertising packet and topology I want to advertise a single id lets say "stackoverflow1" on a ble device. So people close to the sensor can get this message (welcome to wwdc2012) as popups on the iPhone. That's it! meaning that there is no update on the value or anything else in other words I just want to know which room I came in. In another room there's another sensor adversing "stackoverflow2".
Now the question is, should I put the rooms' sensor (advertiser) as Peripherals and visitors' iPhones as Centrals?
If your answer is yes, can I send this Id in advertising packet? i.e. can I skip connection to the room's peripheral? Please guide me a little but on this
Thanks

A: Yes, the iPhones should be centrals and the in-room device should be a peripheral. It's perfectly fine to put enough data in the advertisement that the iOS app can do something useful after simply seeing the peripheral advertised without actually connecting to it. That way, multiple centrals/phones can detect proximity at once without a single phone tying up an exclusive connection to the device. Instead of specifying the room in the service name, you should be able to put it in the advertisement data for the device, giving them all the same service name. That way the iOS app doesn't need to know the completely list of rooms (i.e. services) in advance and they can be added to without changing the app.
In short, the gist of what you described should work fine, and seems like a sound approach to me.

A: You can include information in the advertisement from the peripheral as "Manufacturer Specific" data.  Then the iOS application can get it from the advertisement data dictionary using the CBAdvertisementDataManufacturerDataKey.


text:
Q: Sorting 1 million numbers with only 100k memory cells In C++, is it possible to sort 1 million numbers, assuming we know the range of the numbers, with using only 100,000 memory cells?
Specifically, a .bin file contains a million numbers within a given range, and need to sort these numbers in descending order into another .bin file, but I am only allowed to use an array of size 100,000 for sorting. Any ideas?

A: I think I read it somewhere on SO or Quora about map-reduce:
Divide 1 mil. numbers into 10 blocks. Read in the first block of 100k numbers, sort it using quicksort, then write it back to the original file. Do the same procedure for the remaining 9 blocks. Then perform a 10-way merge on 10 sorted blocks in the original file (you only need 10 cells for this) and write the merged output to another file. You can write to a ~100k buffer then flush it to output file for faster write.

A: Assuming that the range of numbers has 100,000 values or fewer, you can use Counting Sort.
The idea is to use memory cells as counts for the numbers in the range. For example, if the range is 0..99999, inclusive, make an array int count[100000], and run through the file incrementing the counts:
count[itemFromFile]++;

Once you went through the whole file, go through the range again. For each count[x] that is not zero output x the corresponding number of times. The result will be the original array sorted in ascending order.

A: You can implement a version of the quick-sort algorithm that works on files instead than on vectors.
So, recursively split the file in lower-than pivot/higer-than pivot, sort those files, and recombine them. When the size gets under the available memory, just start to work in memory than with files.


text:
Q: MIME message structure parsing and analysis I am looking for an existing library or code samples, to extract the relevant parts from a mime message structure in order to perform analysis on the textual content of those parts.
I will explain:
I am writing a library (in Python) that is part of a project that needs to iterate over very large amount of email messages through IMAP. For each message, it needs to determine what are the mime parts it will need in order to analyze the textual content of the message that require the least amount of parsing (e.g. prefer text/plain over text/html or rich text) and without duplicates (i.e. if text/plain exists, ignore the matching text/html). It also needs to address nested parts (text attachments, forwarded messages, etc) and all this without downloading the entire message body (takes too much time and bandwidth). The end goal is later to retrieve only those parts in order to perform some statistical and pattern analysis on the text content of those messages (excluding any markup, meta data, binary data, etc).
The libraries and examples I've seen, require the full message body in order to assemble the message structure and understand the content of the message. I am trying to achieve this using the response from the IMAP FETCH command with the BODYSTRUCTURE data item.
BODYSTRUCTURE should contain enough information to achieve my goal but although the structure and returned data are officially documented in the relevant RFCs (3501, 2822, 2045), the amount of nesting, combinations and various quirks all add up to make the task very tedious and error prune.
Does anyone know any libraries that can help to achieve this or any code samples (preferably in Python but any language will do)?

A: Is there something that you can not do with module email and the submodule email.mime ?
http://docs.python.org/library/email.html#module-email

A: Answering my own question for the sake of completeness and to close this question.
I couldn't find any existing library that answers the requirements. I ended up writing my own code to fetch BODYSTRUCTURE tree, parse it and store it in an internal structure. This gives me the control I need to decide which exact parts of the message I need to actually download and take into account various cases like attachments, forwards, redundant parts (plain text vs html) etc.


text:
Q: What database would be advisable for a Java program that should operate on a db file of some sort and...? My 5 primary goals are:

*

*export to file (preferably including csv)

*import from file

*perform operations on a database file rather than an internal database or a database located in a fixed location on the computer

*add attributes and tables to any file (a big table with an entry for every file, and several tables per file) [including adding columns to the tables dynamically]

*operate well on any system without much hassle

I'm not sure what database is out there to let me use a DB in Java without having to install a Database system directly.  However, this will also be my first time using a database to organize files rather than a homebrew!  So I could be completely off base.
Is there a database solution that addresses all the above well and that's pretty quick to learn?  Would MySQL or SQLite be good choices?  I want to avoid messing with passwords and stuff and would like users to be able to exchange databases as a single file without any hassle.
Thanks!

A: I'd suggest one of the pure Java databases. They are generally lightweight, fast, and because they don't have any native code dependencies it will be much easier to build and deploy your application.
They are typically used in an embedded mode which brings quite a few benefits: you just import the right .jar file into your application and then your application gains the capability to act as a databse server (i.e. your application will access the database files on the disk directly, there is no separate server process to configure and manage).
Ones to look at probably include:

*

*H2 - http://www.h2database.com/html/main.html

*Derby - http://db.apache.org/derby/

*SQLJet - Pure Java version of SQLite - http://sqljet.com/
See also:

*

*Java Embedded Databases Comparison

*Lightest Database to be packed with an application

A: For MySql, you need to do an installation. If application doesn't need any big database then SQL Lite looks like a better choice considering you want to exchange database as a single file.
Although I found that MySql is so good documented and its importing/exporting DB operations are just one line command, it shouldn't be any real learning curve if you are already familiar with SQL.


text:
Q: Custom filename extension (eg: www.mysite.com/test.custom/) I pay for a webhost service running a LAMP combo and I was wondering if I could have a custom extension for my documents such as:
www.mysite.com/custom.extension

instead of:
www.mysite.com/custom.php

It works on my local XAMPP computer (without modifying anything) and I can name my files whatever I want, but I can't on my paid webhost; it just shows me the HTML as plain text.

A: You need to setup Apache for that. Add a line like the following to your httpd.conf:
AddType application/x-httpd-php .extension

and it should work.


text:
Q: Cannot find a differ supporting object '[object Object]' of type 'object'. angularfire2 I'm new using angularfire2. Let's say, I want to list every item, but I also want to get the profile' name using *ngFor. however, I have this error :
 Cannot find a differ supporting object '[object Object]' of type
 'object'. NgFor only supports binding to Iterables such as Arrays.

I have this kind of data
- items
  - id
    - name: string
    - type : string
    - userId: string

- profile
  - id
    - username: string

this is my code
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Item } from '../../models/item';
import { profile } from '../../models/profile';
import { AngularFireDatabase } from 'angularfire2/database';

@IonicPage()
@Component({
  selector: 'page-timeline',
  templateUrl: 'timeline.html',
})
export class TimelinePage {
  item = {} as Item ;
  userId : string;
  profile  = {} as Profile;
  items: Observable<any[]>;
  profile: Observable<any[]>;

  constructor(
    private afDatabase : AngularFireDatabase,
    public navCtrl: NavController,
    public navParams: NavParams) {
    this.afDatabase.object(`profile/${c.payload.val().userId}`)
    this.dataItem = this.afDatabase.list('items' );
    this.dataProfile = this.afDatabase.list('profile/');

  }

ngOnInit(){
    this.items = this.dataItem.snapshotChanges().map(items => {
        return this.items.map(item => {
          this.item.userId.map(profile => {
            this.dataProfile.subscribe(c => {
              profile = c;
              //console.log(profile);
              });
          });
          return this.items;
        });
      });
      console.log(this.items)
  }

}

my html code
<ion-list color="primary">
  <ion-item *ngFor="let item of items | async">

{{item.name}}

{{item.type}}

{{item.username}}

    <button ion-button clear item-end>View</button>
  </ion-item>
</ion-list>

thank you


text:
Q: Rails country_select for locale name - 'en-GB' not 'gb' I'm currently using the country_select gem for users profiles. With the locales you can have :en, :en-Us, :en-GB and I see to change the current locale you can do I18n.locale =. So lets say I need to select 'United Kingdom' from the country_select, this will save gb into the database. Now I would like to change the locale to the users selected country but this will change it to gb which won't work as it needs to be 'en-GB' and this include the uppercase.
How would I go about doing this? This could also be the same for all the es locales.

A: In the end I created a helper method, which has a 'case' statement and returning the right result.
def prefix_locale(locale)
  case locale
    when 'gb'
      'en-GB'
    else
      locale
    end
end


text:
Q: Logically grouped interfaces have circular dependencies in call graph, tight coupling. Leave as is, break up CRUD interfaces, something else? The problem I have relates to an existing system in a specific business domain. I've simplified it into a very similar 'Library/Book' relationship to articulate the problem. Answers such as 'why would you do it that way' are not helpful, as this is very similar to what I have, and need to solve for. Help that reflects that is very much appreciated.
I am using a no-sql database, which isn't particularly relevant to the question but the relationships cannot be modeled in SQL or use features like fk drop cascades.
Suppose I have a monolithic library service that I want to incrementally rewrite into a new service with newer libraries. Upgrade in place is not feasible. Part of this service that is tightly coupled includes:

*

*A table of Libraries

*A table of Books

*A table of LibraryBooks to represent the meta data of a book as it relates to a specific library (such as quantity, stock) with a partition key of library id and a clustering key of book id

*A table of LibrariesByBook that contains a denormalized Library entity with a partition key of book id and clustering key of library id

*When a Book, LibraryBook or Library is updated in any way, there's a hold list for that library that needs to be 'recalculated.' (this may not make sense, but this is close to what I have)

*When a LibraryBook is added (a book is added to a library) we need to verify that book and library exist.

*When a Library is updated, the LibrariesByBook table needs to be updated with the Library record.

The call graph ends up looking like this:

There aren't any cycles between method calls, however there is between the interfaces and the interfaces are very tightly coupled. For example, if we want to move the interfaces without decomposing a specific interface, all of the interfaces must be moved together.
Since the cycles are only on the read method, having the read interfaces separated would reduce the coupling and have tighter scoped interfaces with fewer collaborators. This means that the interfaces themselves are easier to understand for someone unfamiliar with the code, easier to test, easier to modify, etc.
However, breaking up entity/crud interfaces is very unusual. I've never actually seen any API or class hierarchy that does that, and it's not intuitive where the entity crud interfaces are. Breaking up the interfaces is going to be a hard sell to other developers, and some developers don't have problems with circular dependencies between interfaces.
Should the CRUD interfaces be broken up, leave the call cycles or is there another solution I'm not seeing?

A: How About...
createLibraryBook and deleteLibraryBook are on the wrong entity. I doubt that a LibraryBook should be responsible for such activities (beyond filling out its own properties). Library feels like a better scoping for such actions.
LibrariesByBook is an index, is it possible to push that down into the data layer as one, it could probably be over the LibraryBook backing store as it knows about libraries, and books. Surfacing the lookup methods on the Book (or if it must LibraryBook) to list Libraries?

A: You should have a repository object for you database and not expose librarybook and booklibrary at all. They are not enties just relationships.
repo.UpdateBook(book)
Can then do all the nessesary work and maintain all the relationships and calculated waitlists etc

A: I think the problem is a lack of top-down "ownership".  Logically a Library references a number of LibraryBooks.  A LibraryBook references one book.
So if you want to add a book to a library, you tell Library to add a book.  It creates a LibraryBook, which adds a reference to the Book.  If you want to edit a book, again tell the Library which book to edit, so it all ends up being done top-down.
LibrariesByBook is a bit of an oddity.  It could be maintained by the Libraries, in cooperation with each other.  Or create another "AllLibraries" above Library.


text:
Q: Java Array help Exception in thread "main" Beginner here and I need help with this Exception out of bounds error. I am really Stuck !
Trying to multiply matrices. Please help
package arrayPractice1;

import java.util.Arrays;
import java.util.Scanner;

public class Array {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type how much rows will matrix A have");
        int rowA = in.nextInt();
        System.out.println("Type how much columns will matrix A have");
        int colA = in.nextInt();
        System.out.println("Type how much rows will matrix B have");
        int rowB = in.nextInt();
        System.out.println("Type how much columns will matrix B have");
        int colB = in.nextInt();

        int[][] matrixA = new int[rowA][colA];
        int[][] matrixB = new int[rowB][colB];

        for (int i = 0; i < matrixA.length; i++) {
            for (int j = 0; j < matrixA[i].length; j++) {
                System.out.println("Enter value for row " + i + " and column " + j);
                matrixA[i][j] = in.nextInt();
            }
        }

        for (int i = 0; i < matrixB.length; i++) {
            for (int j = 0; j < matrixB[i].length; j++) {
                System.out.println("Enter value for row " + i + " and column " + j);
                matrixB[i][j] = in.nextInt();
            }
        }

        in.close();

        int[][] multiply = new int[colA][rowB];
        int sum = 0;

        System.out.println("Mult. of matrixA and matrixB");

        for (int i = 0; i < rowA; i++) {
            for (int j = 0; i < colB; j++) {
                for (int k = 0; k < rowA; k++) {
                    sum = sum + matrixA[i][k] * matrixB[k][j];
                }
                multiply[i][j] = sum;
                sum = 0;
            }
        }

        System.out.println(Arrays.deepToString(multiply));

    }

}

A: for (int i = 0; i < rowA; i++) {
        for (int j = 0; i < collB; j++) {
            for (int k = 0; k < rowA; k++) {
                sum = sum + matrixA[i][k] * matrixB[k][j];
            }
            multiply[i][j] = sum;
            sum = 0;
        }
    }

here you are checking if i is less than collB and while this is true you are making j larger than the matrix[k][j] allows causing the index out of bounds error.


text:
Q: Calculate the energy in a circuit containing a resistor A voltage peak in a circuit is caused by a current through a resistor.

The energy E which is dissipated by the resistor is:

 Calculate E if

Can anyone please give me some suggestions where to start ? What is the formula to use ?

A: Hint :
Use the Euler formula :
$$
sin(x)=\frac{exp(j\cdot x)-exp(-j\cdot x)}{2j}\\
$$
where $j^2=-1$
EDIT :
$$
E = \int_{0}^{\infty} R I_{0}^{2}\cdot e^{-2t/t_{0}}\cdot sin^{2}(2t/t_{0}) \ dt
$$
$$
E = \int_{0}^{\infty} R I_{0}^{2} e^{-2t/t_{0}}\cdot \frac{-2+exp(j4t/t_{0})+exp(-j4t/t_{0})}{-4} \ dt
$$
$$
E = \frac{R I_{0}^{2}t_{0}}{-4}\cdot (-1 + \frac{1}{2-4j} + \frac{1}{2+4j})
$$
$$
E = \frac{R I_{0}^{2}t_{0}}{5}
$$
By the way, downvoting without saying why is childish.

A: Since $R$ is a constant then the energy is seen to be
\begin{align}
E = R \int_{0}^{\infty} I^{2}(t) \ dt = I_{0}^{2} R \int_{0}^{\infty} e^{-2t/t_{0}} \ \sin^{2}(2t/t_{0}) \ dt
\end{align}
By making the substitution $x = 2t/t_{0}$ the integral becomes
\begin{align}
E &=  \frac{I_{0}^{2} t_{0} R}{2} \int_{0}^{\infty} e^{-x} \ \sin^{2}(x) \ dx \\
&= \frac{I_{0}^{2} t_{0} R}{4} \int_{0}^{\infty} e^{-x} (1 - \cos(2x)) \ dx \\
&= \frac{I_{0}^{2} t_{0} R}{4} \left[ [- e^{-x} ]_{0}^{\infty} - \int_{0}^{\infty} e^{-x} \ \cos(2x) \ dx \right] \\
&= \frac{I_{0}^{2} t_{0} R}{4} \left[ 1 - \int_{0}^{\infty} e^{-x} \ \cos(2x) \ dx \right] \\
&= \frac{I_{0}^{2} t_{0} R}{4} \left( 1 - \frac{1}{5} \right) \\
E &= \frac{I_{0}^{2} t_{0} R}{5}
\end{align}


text:
Q: Building third party library as part of CMake project I have a top level CMakeLists.txt file which builds a library called Camellia and several executables in subdirectories which link with Camellia. I would like to add a third party library called XDMF as a dependency for Camellia under Camellia/TPL/Xdmf. Luckily, XDMF is already on a CMake build system, but when I use
add_subdirectory(TPL/Xdmf)

and then
add_library(Camellia ${LIB_SOURCES} ${HEADERS})

it builds Camellia in the build/TPL/Xdmf/bin directory rather than build as it does without the add_subdirectory(TPL/Xdmf). Why does adding a subdirectory change the build directory for Camellia, and how do I fix it? Also how do I make sure Camellia is linking with Xdmf once I get that figured out?

A: I think that ExternalProject_Add(...) is what you want.
Please see CMake: How to build external projects and include their targets which describes a similar issue.


text:
Q: TextBox in Model Popup is not getting a value of Country triggered by an update-click? When I click on an update button, the model-pop-up appears with the same value for all countries. It's always showing India.
I want the country name here:
<input type="text" value='. $row['country_name'] .'>

A: You are printing out a modal for each row you have in the database and they all have the same id "myModal", that's the last thing you want to do.
Instead what you need is to have the modal html printed out once and pass the name of the country to it when the user presses the update button using a javascript function.

A: You need to give a class to td
example
<td class='country'>

you need to give class to the button
<button class="update">Update</button>

remove the modal popup code on each echo place it in the footer
give a common id to textbox in the popup

$(".update").change(function(){
  $('#myModal').modal('show');
  var value= $(this).closest("tr").find(".country").text();
  $("countryUpdate").val(value);
});


text:
Q: why my alert shows undefined in javascript var database = require('../../db');
var rightponame = '1';
var rightdevname = '';
var rightpopassword = '';
var rightdevpassword = '';
database.db.once('open', function() {
  console.log('success');

  var cursor = database.db.collection('user').find({}, {
    _id: 0
  });
  cursor.each(function(err, doc) {
    if (doc != null) {
      rightponame = doc.productOwner;
      rightdevname = doc.developer;
      rightpopassword = doc.popassword;
      rightdevpassword = doc.devpassword;
      console.log(rightponame);
      console.log(rightdevname);
      console.log(rightpopassword);
      console.log(rightdevpassword);
    } else {
      console.log('o');
    }
  });

});

function login() {
  var getusername = document.getElementById("username").value;
  var getpassword = document.getElementById("password").value;

  alert(rightponame);

}

Finally, I get rightponame, rightdevname, rightpopassword and rightdevpassword value. But in the login function, I get undefined in the alert.
Why?

A: In JavaScript, alert is only available in the browser. It appears you're using node.js or the like. Try console.log instead, as you're doing on db open.
Then when you check the terminal window where the process is running, you should see the value of console.log.
Since console.log takes multiple values, it's helpful to prefix with something distinguishable like:
console.log('<<<<<<<', rightponame)


text:
Q: Error calling GetFilterVersion on Apache to Tomcat Redirector ISAPI Filter - 32bit W2K8 SP2 Standard I am getting an error trying to use the Apache ISAPI Redirector from IIS 7 to Tomcat but only on the 32 bit W2K8 SP2 Standard Edition.
It works fine on 64 bit W2K8 R2 and 32 bit W2K3.
I have verified that I have the correct 32 bit library (release 1.2.32 or 1.2.37). In fact the exact same library works on 32 bit W2K3. The filter is enabled and allowed and has permission to the library folder and registry entry.
When I rename the library, I get a different error: "Calling LoadLibraryEx on ISAPI Filter …. Failed" - Error Code 0x8007007e. I doesn't look like a permission issue.
The exact error text is "Calling GetFilterVersion on ISAPI Filter "….\isapi_redirector_1.0.dll" failed" - Error Code 0x80070002
The error log shows: The HTTP Filter DLL …\isapi_redirector_1.0.dll failed to load. Source=IIS-W3SVC-WP. The error code is 02 00 00 00
All pointers would be appreciated.

A: There could be multiple reasons for this. Some most common being:

*

*Some dependencies are not being resolved for the 32-bit DLL. Open this DLL with Dependency walker and check for any errors in it (Skip the warnings in it). In most cases all dependent libraries are present, in such cases LoadLibraryEx error may come up because of the VC redistributables of specific version not present (If the DLL was built from VS 2010, the VC 2010 redistributables are needed).

*Read permission for this DLL is not available to the application pool in which your website is running. Check properties of your website to see the user and make sure this user has permissions to the DLL.


text:
Q: Unable to connect to google APi server using python Am using the below code to test the google API connectivity using python code.Imported the modules pip install --upgrade google-api-python-client.
But still getting the error.Would like somebody to help on this
   from __future__ import print_function
    from apiclient import discovery
    import apiclient.discovery

    TMPL = '''
        User: %s
        Date: %s
        Post: %s
    '''

    API_KEY = "my key" # copied from project credentials page
    print (type (API_KEY))

    GPLUS = apiclient.discovery.build('plus', 'v1', developerKey=API_KEY)

    items = GPLUS.activities().search(query='python').execute().get('items', [])
    for data in items:
        post = ' '.join(data['title'].strip().split())
        if post:
            print(TMPL % (data['actor']['displayName'],
                          data['published'], post))

Getting the below error ,
     File "", line 1, in
        runfile('D:/Mohana/Python/scripts/Google_PlusTest1.py', wdir='D:/Mohana/Python/scripts')
  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/Mohana/Python/scripts/Google_PlusTest1.py", line 21, in <module>
    GPLUS = apiclient.discovery.build('plus', 'v1', developerKey=API_KEY)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\googleapiclient\discovery.py", line 229, in build
    requested_url, discovery_http, cache_discovery, cache)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\googleapiclient\discovery.py", line 276, in _retrieve_discovery_doc
    resp, content = http.request(actual_url)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\httplib2\__init__.py", line 1322, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\httplib2\__init__.py", line 1072, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)

  File "C:\Users\1234\AppData\Local\Continuum\anaconda3\lib\site-packages\httplib2\__init__.py", line 1002, in _conn_request
    raise ServerNotFoundError("Unable to find the server at %s" % conn.host)

ServerNotFoundError: Unable to find the server at www.googleapis.com


text:
Q: How to change all the guid in posts table? Recently I have transferred my WordPress from development server to live server. I noticed that I have to change all the "guid" with live domain url. Is there any mysql query or simple function available to change it easily.

A: To improve the previous answers you should update all relevant tables such as (here table prefix is wp_):
UPDATE `wp_posts` SET guid = REPLACE(guid, 'oldsiteurl', 'newsiteurl') WHERE guid LIKE 'oldsiteurl%';

UPDATE `wp_postmeta` SET meta_value = REPLACE(meta_value, 'oldsiteurl', 'newsiteurl') WHERE meta_value LIKE 'oldsiteurl%';

UPDATE `wp_options` SET option_value = REPLACE(option_value, 'oldsiteurl', 'newsiteurl') WHERE option_value LIKE 'oldsiteurl%';

If you got any plugins that do redirections you should also change the permalinks there:
UPDATE `wp_redirection_404` SET url = REPLACE(url, 'oldsiteurl', 'newsiteurl') WHERE url LIKE 'oldsiteurl%';

A: It should be something like:
UPDATE wp_posts SET guid = REPLACE(guid, 'oldurl.com', 'newurl.com') WHERE guid LIKE 'http://oldurl.com/%';

*

*oldurl.com - Previous URL shown in wordpress settings > general options

*newurl.com - New URL

A: Use the WP-CLI to search and replace. The plugin MigrateDB also has a find and replace on export for the next time you transition.

A: I had forgotten that I wrote a SQL generator a few years back for this precise task:
https://farinspace.github.io/wp-migrate-gen/
Essentially the relevant SQL is as follows:
UPDATE `wp_options` SET `option_value` = REPLACE(`option_value`, 'a', 'b') WHERE `option_value` NOT REGEXP '^([adObis]:|N;)';
UPDATE `wp_posts` SET `post_content` = REPLACE(`post_content`, 'a', 'b');
UPDATE `wp_posts` SET `post_excerpt` = REPLACE(`post_excerpt`, 'a', 'b');
UPDATE `wp_posts` SET `guid` = REPLACE(`guid`, 'a', 'b');
UPDATE `wp_comments` SET `comment_author_url` = REPLACE(`comment_author_url`, 'a', 'b');
UPDATE `wp_comments` SET `comment_content` = REPLACE(`comment_content`, 'a', 'b');
UPDATE `wp_links` SET `link_url` = REPLACE(`link_url`, 'a', 'b');
UPDATE `wp_postmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';
UPDATE `wp_usermeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';
UPDATE `wp_termmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';
UPDATE `wp_commentmeta` SET `meta_value` = REPLACE(`meta_value`, 'a', 'b') WHERE `meta_value` NOT REGEXP '^([adObis]:|N;)';

The queries above will check for and skip PHP serialized data.
Using the generator, you can turn off "skip serialized data" if the old and new string lengths match.
WARNING: I would recommend that you always create a backup of your data before running any queries that add/remove/update content.

A: WordPress documentation warns about changing guid entries in the WP database: "It is critical that you do NOT change the contents of this field."
https://wordpress.org/support/article/changing-the-site-url/#important-guid-note

A: As you mentioned, there are a few variables that need to be changed in order for you to update to the new URL on your WordPress site.

*

*Go and download Interconnect IT's Database Search & Replace Script here

*Unzip the file and drop the folder in your live server where your WordPress is installed (the root) and rename the folder to replace (screenshot)

*Navigate to the new folder you created in your browser (ex: http://web.site/replace) and you will see the search/replace tool

*It should be pretty self-explanatory up to this point: enter your old URL in the search for… field and the new URL in the replace with… field

You can click the dry run button under actions to see what it will be replacing before you execute the script. Once you're done be sure to remove the /replace/ folder.


text:
Q: Why Gradle's wrapper in Linux has to be started in this way? I have a Gradle project with this structure:
ls -alh

drwxr-xr-x 9 Xelian 4.0K Aug  5 22:39 .
drwxrwxr-x 3 Xelian 4.0K Aug  5 16:19 ..
-rw-rw-r-- 1 Xelian  465 Aug  5 16:19 build.gradle
drwxrwxr-x 8 Xelian 4.0K Aug  5 16:38 buildSrc
drwxrwxr-x 3 Xelian 4.0K Aug  5 16:19 gradle
drwxrwxr-x 3 Xelian 4.0K Aug  5 16:45 .gradle
-rwxrwxrwx 1 Xelian 5.0K Aug  5 17:29 gradlew
-rw-rw-r-- 1 Xelian 2.3K Aug  5 16:19 gradlew.bat
-rw-rw-r-- 1 Xelian 17K Aug  5 16:19 README.md
-rw-rw-r-- 1 Xelian   30 Aug  5 16:19 settings.gradle

And to execute the gradlew bash file I write:
gradlew -v

Output:
No command 'gradlew' found, did you mean:
 Command 'gradle' from package 'gradle' (universe)
gradlew: command not found

If I write :
 ./gradlew -v

Everything works fine.
Does ./ mean current directory?

A: When you type:
command

Your shell will search all the directories listed in your $PATH environment variable, in order, for an executable with the name "command".
When you type:
./command

The ./ part explicitly tells your shell that you want to execute the file named "command" in the current directory (. is interpreted as the current directory).
If you want to be able to run it with just command, you will have to add the current directory to your PATH, or move the executable to somewhere already on your PATH


text:
Q: How to filter data based on selected value from dropdown menu and search query in input field using reactjs? i want to filter data based on the search query entered in input field from the values selected in dropdown menu.
What i am trying to do?
Consider the image below

From the select dropdown option user can select both messages and info or either of the options. Based on the option selected from dropdown menu and search query entered in the search input field it should filter data.
Suppose if user selected messages and entered search query "hello" it should retrieve messages containing text "hello" and similarly with info and messages option as well.
I am not sure how to do this. Could someone help me solve this?
Below is the code,

        {!state.expanded && <Svgsearch/>}
                {state.expanded && props.active &&
<Svgsearch/>
}
                {state.expanded &&

                        <input type="text" placeholder="search query" />

}

                    <FieldDropdown on_dropdown_toggle=
                        {this.handle_dropdown_toggle} />

);

export default class FieldDropdown extends react.component {
    render = () => {
    return (
        <Dropdown className="category_dropdown" on_dropdown_open=
            {this.handle_dropdown_open} on_dropdown_close=
            {this.handle_dropdown_close}>

                    <button>{dropdown_text}</button>

            {state.options.map((option, i) => {
                return (
                    <DropdownItem key={i} on_select=
                        {this.handle_option_selection} value={i}>
                        <input type="checkbox" value={option.value}
                            checked="true" readOnly />

                            {option.text}
                    </DropdownItem>)
            })}
        </Dropdown>);
};

Consider i  have messages and info in an array of objects.
How can i write a method to filter data based on option selected from dropdown.
Thanks.

A: Html for query field
 <input
            id="searchId"
            type="text"
            value={this.state.queryValue}
            onChange={this.handleTextChange}
          />

State
 state = { data: [], filteredData:[],queryValue: '' ,value:'' };

Event Handling Method
     handleTextChange = event => {
//read the value of the textbox with event.target.value
        const filteredData = this.state.data.filter(d =>
        //  object where condition based on value(options value) & queryValue
        );
        this.setState({ queryValue: event.target.value, filteredData});
      };

and bind UI to the filteredData.


text:
Q: Зафиксировать блок внутри кастомного скролла? Есть блок с кастомным скроллом, внутри этого блока есть плашка, которая должна быть зафиксирована, причем снизу этого блока. К тому же ещё каким-то чудом, она не должна контент перекрывать когда сам блок скролится.
Есть какие-нибудь идеи хотя бы в каком направлении двигаться ?
ЗЫ. Плашка должна быть частью блока со скролом, если на нее навести и скролить, должен скролиться блок, а не вся страница.
https://codepen.io/brezze/pen/QPNybm

sticky

https://manos.malihu.gr/jquery-custom-content-scroller/

https://manos.malihu.gr/jquery-custom-content-scroller/

https://manos.malihu.gr/jquery-custom-content-scroller/

https://manos.malihu.gr/jquery-custom-content-scroller/

A:

//это просто что-бы нагенерить контент, ответ в css.
let appNode = '
manos.malihu.gr/jquery-custom-content-scroller
';
function generateNode (sel, appNode, qty = 1) {
  let $container = $(sel);
  for (let i = 1; i < qty; i++) {
    $container.append(appNode);
  }
}
generateNode('.container span', appNode, 20);
::-webkit-scrollbar{width:10px}
::-webkit-scrollbar-track{box-shadow:inset 0 0 5px grey}
::-webkit-scrollbar-button{height:5px;background-color:grey}
::-webkit-scrollbar-thumb{width:10px;height:10px;background-color:green}
.container{height:150px;width:250px;border:1px solid black;overflow-y:scroll;position:relative}
.sticky{position:sticky;background-color:yellow;left:0;right:10px}
.sticky.top{top:0}
.sticky.bottom{bottom:0}

sticky top

sticky bottom


text:
Q: Update openshift env var while server is running and get the latest value of the same On openshift I have set env X=20. In my nodejs module I am reading this value but whenever I update the value for X I am not able to get the updated value. I have to restart the server in order to get the latest one.
Is there a way with which I can get the latest value of env variable without restarting the app?
While googling I have found following API which can help me..
https://access.redhat.com/documentation/en-US/OpenShift_Online/2.0/html/REST_API_Guide/chap-Environment_Variables.html

A: Unfortunately what you are trying to do is not possible.  The environment variables are set at the system level, and the application server (apache, etc) needs to be restarted to reload them.  As has been suggested in the comments, you should use a database or text file to store the information that you need to update & retrieve on the fly.


text:
Q: How to re-render an included component on click function? I have a list component and in it a dialog which contains a form component that I am using for editing and creating new data. The component is separate (within the same module) and is called inside a dialog like this:
<p-dialog header="Header" width="700" [resizable]="false"
[(visible)]="displayDialog"modal="true">
   <app-detail [id]="id"></app-detail>
</p-dialog>

Create and edit buttons are in the list component html and when I click the edit button an id is supposed to be passed to the detail component and load the data and fill the form for me. But it seems that the detail component is getting rendered just once when the list html renders, and when I click the edit button there's no response, no new id is being passed into the detail component.
What should I do?

A: Judging from the [(visible)] dialog databinding, it does not destroy/create the <app-detail> component, but simply hides and shows it. So it makes sense that the <app-detail> component is rendered just once.
If you want to recreate the <app-detail> component every time displayDialog changes, just add *ngIf directive to the component.
Like this:
<p-dialog header="Header" width="700" [resizable]="false"
  [(visible)]="displayDialog" modal="true">
   <app-detail [id]="id" *ngIf="displayDialog"></app-detail>
</p-dialog>


text:
Q: Opencart get current layout_id I have created a custom layout and i planned to hide products only for those custom layout assigned pages.
Is there any way to get current layout id ?
For example, Let's say my custom layout_id is 10, I planned to use some looping like below to hide/show products
if (current_layout_id != 10) {
  // Display products
}else {
  // Hide Products
}

A: find layout id of current displayed module page
if (isset($this->request->get['route'])) {
        $route = $this->request->get['route'];
    } else {
        $route = 'common/home';
    }
    $layout_id = 0;
    if (substr($route, 0, 16) == 'product/category' && isset($this->request->get['path'])) {
        $path = explode('_', (string)$this->request->get['path']);
        $layout_id = $this->model_catalog_category->getCategoryLayoutId(end($path));
    }
    if (substr($route, 0, 16) == 'product/product' && isset($this->request->get['product_id'])) {
        $layout_id = $this->model_catalog_product->getProductLayoutId($this->request->get['product_id']);
    }
    if (substr($route, 0, 16) == 'product/information' && isset($this->request->get['information_id'])) {
        $layout_id = $this->model_catalog_information->getInformationLayoutId($this->request->get['information_id']);
    }
    if (!$layout_id) { $layout_id = $this->model_design_layout->getLayout($route); }
    if (!$layout_id) { $layout_id = $this->config->get('config_layout_id'); }

end of layout id finding


text:
Q: how to multiply a matrix by itself transposed in R The first matrix
M1=structure(list(X1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
    X0 = c(0.5, 0.5, 0, 0, 0, 0.5, 0.5, 1, -0.5, 1, -0.5, 0,
    1, 0, -4, 0, 0.5, 1, 0, 0.5, 0, -2, 0.5, 0, 0), X0.1 = c(1.2,
    0, 0, 0.5, 0, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, -2, 1, 0.5, 0,
    0.5, 0, 2.5, -1, 0.5, -3, 0), X0.2 = c(2.8, 0, 0, 0.8, 0.2,
    0, 0.5, 0.5, 0.5, -0.5, 0, 0.5, -0.5, 0.7, -3.7, 2, 0, 0,
    1.5, 0.5, 0, 0, 0, -2.5, 0), X0.3 = c(0, 0, 0, 0, 0, 1, -1,
    1, 0, -1, 0.5, 0, -0.5, 0.5, -1.5, 0, 1, -1, 0, 0, -1, 1,
    1, -2.5, 0), X0.4 = c(0.5, 1, 0, 0, 1, 0, 0, 0, 2, 0, -1,
    1, 1, -1.5, 4.5, 1, -1, 0.5, 1.5, 0, 4, 0, -2, 6, 0), X0.5 = c(0L,
    2L, 0L, 0L, 2L, -10L, 10L, -10L, 14L, 0L, 0L, 1L, 2L, -3L,
    8L, 2L, -12L, 0L, 0L, 0L, 22L, 0L, -4L, 8L, 0L), X0.6 = c(0L,
    2L, 0L, 0L, 2L, -12L, 14L, -12L, 13L, 1L, 0L, 0L, 2L, -2L,
    8L, 4L, -14L, 0L, 0L, 0L, 20L, 2L, -4L, 10L, 0L)), class = "data.frame", row.names = c(NA,
-25L))

The second (transposed intself the first matrix)
structure(list(X1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L), X1.1 = c(0.5,
1.2, 2.8, 0, 0.5, 0, 0), X1.2 = c(0.5, 0, 0, 0, 1, 2, 2), X1.3 = c(0L,
0L, 0L, 0L, 0L, 0L, 0L), X1.4 = c(0, 0.5, 0.8, 0, 0, 0, 0), X1.5 = c(0,
0, 0.2, 0, 1, 2, 2), X1.6 = c(0.5, 0.5, 0, 1, 0, -10, -12), X1.7 = c(0.5,
0, 0.5, -1, 0, 10, 14), X1.8 = c(1, 0, 0.5, 1, 0, -10, -12),
    X1.9 = c(-0.5, 0, 0.5, 0, 2, 14, 13), X1.10 = c(1, 0, -0.5,
    -1, 0, 0, 1), X1.11 = c(-0.5, 0, 0, 0.5, -1, 0, 0), X1.12 = c(0,
    0, 0.5, 0, 1, 1, 0), X1.13 = c(1, 0, -0.5, -0.5, 1, 2, 2),
    X1.14 = c(0, 0, 0.7, 0.5, -1.5, -3, -2), X1.15 = c(-4, -2,
    -3.7, -1.5, 4.5, 8, 8), X1.16 = c(0L, 1L, 2L, 0L, 1L, 2L,
    4L), X1.17 = c(0.5, 0.5, 0, 1, -1, -12, -14), X1.18 = c(1,
    0, 0, -1, 0.5, 0, 0), X1.19 = c(0, 0.5, 1.5, 0, 1.5, 0, 0
    ), X1.20 = c(0.5, 0, 0.5, 0, 0, 0, 0), X1.21 = c(0, 2.5,
    0, -1, 4, 22, 20), X1.22 = c(-2L, -1L, 0L, 1L, 0L, 0L, 2L
    ), X1.23 = c(0.5, 0.5, 0, 1, -2, -4, -4), X1.24 = c(0, -3,
    -2.5, -2.5, 6, 8, 10), X1.25 = c(0L, 0L, 0L, 0L, 0L, 0L,
    0L)), class = "data.frame", row.names = c(NA, -7L))

How to multiply a matrix by itself transposed. What the way There is?
The result must be some like on this picture

A: R can handle matrix and its manipulation very well. You can use the code below to convert your ordinary dataframe to matrix, find transpose and then to multiply them:
# first convert dataframe to matrix
M1Matrix<-data.matrix(M1)
M1Transpose<-t(M1Matrix)
MProd<-M1Matrix %*%  M1Transpose

MProd being the product of the matrix and its transpose which comes out to be below:


text:
Q: Hugo site favicon shows locally, but cannot be found in deployment This is my first time using Hugo. I am using the Bento theme for my Hugo site which did not come with favicon support out of the box (I searched the entire code base and it is nowhere to be found). Consequently, I added the necessary HTML tags to the partials > head.html. When I run locally with hugo server -D or npm run dev, the favicon shows up fine.
I think there is an issue with how my relative href is written, however, whenever I change it, it breaks it locally. I am using AWS Amplify for deployment with auto cloudfront invalidation so that is not the issue.
When I inspect the page source of the deployed site, I get this for the favicons:
<link rel="apple-touch-icon" sizes="180x180" href="favicon%20not%20found%25!%28EXTRA%20string=apple-touch-icon.png%29">

You can see the issue in the href= field
Here is how my favicons are implemented in partial/head.html:
<link rel="icon" type="image/png" sizes="32x32" href="{{ "/img/favicon-32x32.png" | relURL }}">
<link rel="icon" type="image/png" sizes="16x16" href="{{ "/img/favicon-16x16.png" | relURL }}">
<link rel="apple-touch-icon" sizes="180x180" href="{{ "/img/apple-touch-icon.png" | relURL }}">

I also tried to implement this by adding the links in the config.toml and using Site.Params, but no luck with that either.

A: The below is how you would do it:
<link ... href="/img/favicon-32x32.png">
<link ... href="/img/favicon-16x16.png">
<link ... href="/img/apple-touch-icon.png">

So you don't have to use the hugo/Go {{}} tag (that would be for a site variable like {{.section }} - you can just put in the relative url which would simply be "/img/favicon-32x32...etc" Just make sure your image is in the corresponding folder.
I tested on my install of hugo and as long as your favicon is in the right place - that handles your problem.

*

*Also note: If you would like to use a site variable {{ $.Site.Params etc...}} such as a href="{{ #.Site.Params etc...}} you would add the variable name and value to your config file. See below for reference on this from hugodocs:
Site Variables