text:
Q: Does WordPress have some hook when we open editor? I am wondering is there some kind of hook when we open post/page editor in WordPress?
I want to make a function which will grab the content from the editor and add some pieces of code in to it automatically.

A: You can set the default editor content or change current content using "the_editor_content" filter.
Ex: set default editor content for "Add new" post.
add_filter( 'the_editor_content', 'set_default_editor_content', 1000, 2 );

function set_default_editor_content( $content, $default_editor ) {
        global $pagenow;
        if ( 'post-new.php' === $pagenow ) {
            ob_start();
            ?>
Default content here...
<?php
            return ob_get_clean();
        }
        return $content;
    }


text:
Q: Errors setting printer settings I am on a Server 2012 R2 system, I am working to migrate from a print server 2008 R2 environment over to my 2012 environment.
I have scripted the printer read from the old server and creation on the new server, but among other things I need to query certain settings and properties of the printer in the old environment and replicate it in the new.
For example - some of my queues on the old server are pointed to specific trays on a given printer - how do I query the old printer queue on the old server to get this information and set it in the new environment?
Additionally - Most of my printers are using the HP Universal Driver, some of them are color and we have manually set the "Device Type" to "Color". I can do a
$mysettings = get-printerproperty -computername <oldserver> -printername <queuename> -propertyname config:dynamicrender

and get the appropriate setting.  Yet, when I do a
set-printerproperty -computername <newserver> -printername <queuename> -propertyname config:dynamicrender -value $mysettings.value** - it doesn't work.

I get:

I've even tried some simple stuff like setting duplex unit to being installed - as seen in this example from TechNet

A: I had the same issue and found that the PropertyName is case sensitive.  It worked when I capitalized the letters (C,D & R) shown below.
Set-PrinterProperty -PrinterName $Printer -PropertyName "Config:DynamicRender" -Value $DeviceType

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python on my Mac is broken; How do I start from scratch? After updating to Lion a few months ago, I noticed that any Python-based apps/tools stopped working. After some research, I solved the problem by re-installing the official Python installer, and correcting my PATH variable.
Now though, I'm not so sure everything is working the way it should, because when I try to use Sublime Text 2, I get an error report dialog with:
....

Dyld Error Message:
Library not loaded: /System/Library/Frameworks/Python.framework/Versions/2.6/Python
Referenced from: /Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2
Reason: image not found

....

Upon inspection, my /System/Library/Frameworks/Python.framework/Versions/2.6 folder contains:
2.6/
  Extras/
  Headers/ --(symlink)--> include
  include/
  lib/

Not Python like expected.
Curious, I did a little digging, and find that I have
/Library/Frameworks/Python.framework
/System/Library/Frameworks/Python.framework
/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework
/Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks/Python.framework
/Developer-3.2.6/SDKs/MacOSX10.5.sdk/System/Library/Frameworks/Python.framework
/Developer-3.2.6/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework

Along with several application-specific distributions, but I'm not concerned about those.
Am I supposed to have Python frameworks in both /Library/Frameworks and /System/Library/Frameworks? What's the difference between the two?
At this point, I feel like things would just be cleaner to start from scratch with Python, but how can I do that without screwing up my existing tools/apps? Would I need to delete my Python frameworks? Should I use the official installer, or perhaps homebrew's python package?

A: I think the standard python, that comes with Lion, is python 2.7.
Your best chance to get the default setup is probably to copy the relevant files from a different Lion install on a friends machine.
I took a quick look at my Lion System and this is how my pyhton install looks like:
ls -lah /System/Library/Frameworks/Python.framework/Versions/2.7/

total 2296
drwxr-xr-x  11 root  wheel   374B Aug 18 15:22 .
drwxr-xr-x   7 root  wheel   238B Jul 11  2011 ..
drwxr-xr-x   6 root  wheel   204B Jul 11  2011 Extras
lrwxr-xr-x   1 root  wheel    17B Aug 18 15:20 Headers -> include/python2.7
drwxr-xr-x   3 root  wheel   102B Jun 17  2011 Mac
-rwxr-xr-x   1 root  wheel   2.7M Jul 11  2011 Python
drwxr-xr-x   7 root  wheel   238B Jul 11  2011 Resources
drwxr-xr-x   3 root  wheel   102B Jun 17  2011 _CodeSignature
drwxr-xr-x  17 root  wheel   578B Jul 11  2011 bin
drwxr-xr-x   3 root  wheel   102B Jun 17  2011 include
drwxr-xr-x   5 root  wheel   170B Jul 11  2011 lib

And:
ls -lah /System/Library/Frameworks/Python.framework/Versions/2.7/lib/
total 8
drwxr-xr-x    5 root  wheel   170B Jul 11  2011 .
drwxr-xr-x   11 root  wheel   374B Aug 18 15:22 ..
lrwxr-xr-x    1 root  wheel     9B Jul 11  2011 libpython2.7.dylib -> ../Python
drwxr-xr-x    4 root  wheel   136B Jul 11  2011 pkgconfig
drwxr-xr-x  643 root  wheel    21K Oct 14 08:46 python2.7

And /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ contains all the stuff in the python standard lib like for example:
total 13672
drwxr-xr-x   643 root  wheel    21K Oct 14 08:46 .
drwxr-xr-x     5 root  wheel   170B Jul 11  2011 ..
-rw-r--r--     1 root  wheel    22K Jun 17  2011 BaseHTTPServer.py
-rw-r--r--     1 root  wheel    22K Jul 11  2011 BaseHTTPServer.pyc
-rw-r--r--     1 root  wheel    22K Jul 11  2011 BaseHTTPServer.pyo
-rw-r--r--     1 root  wheel   5.6K Jun 17  2011 Bastion.py
-rw-r--r--     1 root  wheel   7.2K Jul 11  2011 Bastion.pyc
-rw-r--r--     1 root  wheel   7.2K Jul 11  2011 Bastion.pyo
-rw-r--r--     1 root  wheel    13K Jun 17  2011 CGIHTTPServer.py
-rw-r--r--     1 root  wheel    11K Jul 11  2011 CGIHTTPServer.pyc
-rw-r--r--     1 root  wheel    11K Jul 11  2011 CGIHTTPServer.pyo
-rw-r--r--     1 root  wheel    26K Jun 17  2011 ConfigParser.py
....


text:
Q: Setting a custom height for a view with a CenterX constraint I have a child view being programmatically being presented by its parent view. I want to set the CenterXAnchor for the child view to be constrained to the parent's CenterXAnchor, but I want the child view to have a specific height and width.
childViewController.view.centerXAnchor.constraint(equalTo:
    parentViewController.view.centerXAnchor)

How do I go about doing this?
I have tried setting a frame for the childViewController but that messes with the anchor.

A: You can use a Height and Width Anchor to set it to a certain height/width. It can also be relative height to another view.
In your example:
childViewController.view.heightAnchor.constraint(equalToConstant: 50)
childViewController.view.widthAnchor.constraint(equalToConstant: 50)

EDIT: Also remember to use '.isActive = true' to activate the constraint.
This makes your view a height and width of 50.
You can read more on it here:
https://developer.apple.com/documentation/uikit/uiview/1622590-heightanchor
https://developer.apple.com/documentation/uikit/uiview/1622605-widthanchor

A: Overview
Given below is an example showing how to do the following:

*

*Add a child view controller

*Setup constraints (layout anchors) for the child view

Code
private func showChildView() {

    let childViewController = UIViewController()
    let parentViewController = self

    childViewController.view.backgroundColor = .brown

    parentViewController.addChildViewController(childViewController)

    let parentView = parentViewController.view!
    let childView = childViewController.view!

    //For programatically created view set the translatesAutoresizingMaskIntoConstraints = false
    childView.translatesAutoresizingMaskIntoConstraints = false

    parentView.addSubview(childView)

    childView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
    childView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true
    childView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    childView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    childViewController.didMove(toParentViewController: parentViewController)
}

Further reading:

*

*Please read about AutoLayout. Refer - https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/

*When you use the autolayout you must not set the frame directly.

*Autolayout is like a set of rules / constraints, so the frame would be determined based on the rules you set.

A: Please Refer sample code
    //Intiallising Child ViewController
    let controller = UIViewController()
    controller.view.frame = CGRect.init(x: 0, y: 0, width: 150, height: 150)
    controller.view.backgroundColor = UIColor.red
    addChildViewController(controller)
    controller.didMove(toParentViewController: self)
    view.addSubview(controller.view)

    //Setting Constrains programattically
    controller.view.translatesAutoresizingMaskIntoConstraints = false
    let widthConstraint = NSLayoutConstraint(item: controller.view, attribute: .width, relatedBy: .equal,
                                             toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 150)

    let heightConstraint = NSLayoutConstraint(item: controller.view, attribute: .height, relatedBy: .equal,
                                              toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 150)

    let xConstraint = NSLayoutConstraint(item: controller.view, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: controller.view, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)

    NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])**strong text**

Sample output


text:
Q: How to mathematically obtain camera trace path from video I have an aerial video of some (approximately flat) view (no depth maps required).
I want to obtain the shape of the ground path the camera center passed upon.
The path does not have to be correct with correspondence to the worl'd north, or have any world coordinates. just have approximately the same shape, even if affine transformed.
I have already for each frame, the matrix that represents the affine transformation between that frame and the previous frame, at a good accuracy, meaning i have a matrix that for each pixel in a frame, gives the location of that pixel in the consecutive frame.
Given that the camera is moving, how can I obtain the SHAPE (over time) of the ground path of the spot on the ground that is in the center of the frames (=the trace)?
More generally, the question is actually only about knowing the relative center of the frame, for each frame, with correspondence to the first frame.
Any leads, as well as answers would benefit me a great deal.

A: Let's call the transformation between frame i and i+1 T.
Let's look at a point P[i] = (Xi,Yi) in frame i. If we want to know were this point will be in frame i+1 we will just need to apply the transformation T on the point P[i] and get a new point P[i+1] = T(P).
In order to get a path the camera did we start from frame 1 with the center point of the image P1 = (row/2,col/2) and calculate P2 = T(P1). The path the camera did between the frame 1 and 2 was approximately the line that connects between the center of frame 2 and P2. We can keep doing this for frame 2 by calculating P3 = T(P2) and so on... The problem is that the points are in in image coordinates and not world coordinate.
To solve this we just decide that our "World coordinate system" PW1 = (0,0) is the center of the first frame. The center of the camera in the second frame in our new "World coordinate system" will be PW2 = ((row/2,col/2) - P2) - PW1. For the third frame the center will be PW3 = ((row/2,col/2) - P3) - PW2 and for the i-th frame PWi+1 = ((row/2,col/2) - Pi+1) - PWi.
The idea is PW_new = movement_of_the_camera_between_frames - last_location.
In the end you will have a set of points PW1,PW2,..,PWn which are the path the camera center did. Fit a spline or something and get the SHAPE of the path.


text:
Q: named explicit & implicit transactions I have encountered a small bug(feature) in the SQL Server 2008.
I have a stored procedure where I begin explicit transaction with the name @tran
....
declare @tran varchar(30) = 'exp_trans';
BEGIN TRAN @tran
IF @p_param is null
 ROLLBACK TRAN @tran
....
The problem is, when I set IMPLICIT_TRANSACTIONS ON and invoke the stored procedure, the flow hits the rollback section, I will receive the error
"Msg 6401, Level 16, State 1, Line 10
Cannot roll back exp_tran. No transaction or savepoint of that name was found."
Is this some sort of feature, or what is actually happening?
Thank you in advance

A: I believe this is happening because of nested transactions and SQL Server 2008 does not support rolling back to an inner transaction when transactions are nested:

Naming multiple transactions in a series of nested transactions with a
  transaction name has little effect on the transaction. Only the first
  (outermost) transaction name is registered with the system. A rollback
  to any other name (other than a valid savepoint name) generates an
  error. None of the statements executed before the rollback is, in
  fact, rolled back at the time this error occurs. The statements are
  rolled back only when the outer transaction is rolled back.

Your transactions are nested because the implicit transactions setting starts one, the begin trans starts the second (nested) transaction. And that makes the rollback to the named transaction fail.


text:
Q: How to map a String to an int according to a mapping structure This question is probably basic but I am still struggling to solve this.
I need to implement a method that gets a String and gives back the according int according to a list.
For example:
Christmas = 10
Holiday = 11

..
String text = {Christmas Holiday}

public static int StringtoInt (String text) shall be able to scan through the String and map the strings according to the provided list.
Could someone provide me with a hint how to solve this.

A: You can use a HashMap<String, Integer> for this purpose:
Map<String, Integer> myMap = new HashMap<String, Integer>();

myMap.put("Christmas", 10);
myMap.put("Holyday", 11);

and you can retrieve the int mapped to a String via
myMap.get("Christmas");

See more here and here.


text:
Q: java split strings function I'm trying to build a program which reads a certain String after using the Split function
import java.util.Scanner;

   public class Lexa2 {

public void doit() {
    String str = "( 5 + 4 ) * 2";
    String [] temp = null;
    temp = str.split(" ");
    dump(temp);
}
public void dump(String []s) {
    for (int i = 0 ; i < s.length ; i++) {
        if (s[i] == "(") {
            System.out.println("This is the left paren");
        } else if (s[i] == ")"){
            System.out.println("This is the right paren");
        }else  if (s[i] == "+"){
            System.out.println("This is the add");
        }else  if (s[i] == "-"){
            System.out.println("This is the sub");
        }else  if (s[i] == "*"){
            System.out.println("This is the mult");
        }else  if (s[i] == "/"){
            System.out.println("This is the div");
        }else
            System.out.println("This is a number");
    }
}

     public static void main(String args[]) throws Exception{
       Lexa2 ss = new Lexa2();
         ss.doit();
 }
    }

The output should be something like this:
This is the left paren
this is a number
this is the add
this is the right paren
this is a number

A: you're pretty close, just replace (s[i] == "?") with (s[i].equals("?"))

A: Don't use s[i] == ")" to compare strings. In this way, you're not checking if the string in s[i] is equal to ).
Use the equals method. Then you can compare the strings using:
if (s[i].equals("("))

Replace equals in the other if statements.
UPDATE
P.S. I think the best way to compare strings, looking to your code, is to use the switch/case statements. But, this feature is only available in Java 7. I think this will avoid the continuous checking with if statements, and the code will be more readable. If you have Java 7, use this feature, otherwise, in case of Java 6 or lower, follow @pstanton suggestion. ;-)


text:
Q: Hosting site on different containers on same docker host I am trying to setup multiple containers listening on different ports hosting sites.
Example:
example1.com 8080 -> 80 container1 (apache)
example2.com 8081 -> 80 container2 (apache)

What is the correct way to do it?
I have tried http redirects/rewrites (inside containers) but cannot get it to work..

A: You need a reverse proxy on the server. I'd go with nginx and configure it similar to here to forward traffic to example1.com to its own port 8080. In Apache this can be done as well. It's called virtual hosts


text:
Q: Algorithm to find number of palindromes in interval I'm currently tasked with writing a program that calculates amount of palindromes in any base from interval of <2;36>. The problem is that my solution has time complexity of O(n^2) at best and that is, if I was frank, really slow.
So far I've tried naive solutions such as converting all numbers from the interval to the base that is required, saving the conversion of the number to array and then checking each of the elements one by one.
This is what I've got so far :
int isTrue = 1;
int arr[64];

while(n > 0)
{
   arr[counter] = n % base;
   n = n / base;
   counter++;
}

for(int i = 0; i < counter; i ++)
{
   if(arr[i] != arr[counter - i - 1])
   {
      isTrue = 0;
      break;
   }
}

It is not good by any stretch, but it does work for the basic test. The problem is that I'm currently trying to solve bonus one which works with much bigger numbers.
By much bigger numbers I mean intervals that span billions of numbers, one of the inputs is for example this:
c 15 62103360044 155888062462
Result : 123502

Where c is task that the program is supposed to do (there was option of l which listed all palindromes which doesn't occur in the bonus tests), 15 is base and the two other numbers are the limits of the interval.
I'm supposed to count palindromes of five such intervals under one second and honestly, I'm pretty stuck.
I would appreciate any help, I'm sorry if I formatted my question wrongly or if it was too drawn out - This is the first time I've asked a question here.

A: *

*Doing a palindrome check faster is a minor optimisation.
Initially I would even use java's number to String conversion.

*What you want is to step through the interval in larger leaps.

*You can use recursion for simplification in the initial version of your algorithm.
Let's look for base 10:
 62_103_360_044
155_888_062_462

 6 ...        6 (recursion on the middle part)
 7 ...        7
 8 ...        8
 9 ...        9
1 ...         1

You need:

*

*Number of digits (your counter)

*First most significant digit

*Parameters start and end

For this step you only need to increment one digit, which even may be done as char.
Notice also that the recursive call on ... gives the same result for 7, 8 and 9 with start 000..000 and end 999..999.
This will be tremendously faster. Happy coding.

Usage of recursion:
I am not giving a clean answer, as that would defeat the task's challenge.
public BigInteger palindromesInInterval(int base, BigInteger from, BigInteger to) {
    return palindromesRec(base, from.toString(base), to.toString(base));
}

private BigInteger palindromesRec(int base, String from, String to) {
    // Do the simple work:
    if (from.length() > to.length()) {
        return BigInteger.ZERO;
    }
    if (from.length() == to.length() && from.compareTo(to) > 0) {
        return BigInteger.ZERO;
    }
    if (from.length() == 1) {
        ...
    }
    // Do a step:
    int highDigit = Integer.parseInt(from.substring(0, 1), base);
    int lowDigit = Integer.parseInt(from.substring(from.length() - 1), base);

    BigInteger sum = BigInteger.ZERO;
    int digit = Math.max(highDigit, lowDigit);
    String from2 = from.substring(1, from.length() - 2); // Can start with 0
    String to2 = "1000...000" -1; // Niners so to say.
    while (digit < base) {
         ...
         sum = sum.add(palidromesRec(base, from2, to2)); // RECURSION
         from2 = "000...000";
    }
    ...
    return sum;
}

Recursion calling oneself, here only once, without extra parameters, which often are used. For instance it is much easier to split the work in:
from  6 2_103_360_04 4
  to  9 9 ..       9 9

from 1 00 ..       0 1
  to 1 55_888_062_46 2

And calculate for every X
from X 000 X   (n zeroes)
  to X 999 X   (n time (base-1))

as base(n+1)/2.
For that you need a level of abstraction/simplification. Keep-it-simple.


text:
Q: Converting month column data to row I have a dataset for time series analysis that looks like:
    Year    Jan Feb March   April   May  June   July    Aug Sep Oct Nev Dec
    2014    0   0   0       0       0    4      0       118 0   0   137 29
    2015    0   19  135     312     0    78     67      0   0   0   132 0
    2016    0   0   0       0       0    0      0       0   100 194 0   114
    2017    0   0   127     4       199  293    0       0   0   23  0   0
    2018    252 0   0       0       0    0      287     0   2   0   0   143
    2019    0   10  0       0       176  205    51      0   0   0   0   0
    2020    0   0   310     0       0    0      0       0   0   0   0   0

I want the data looks like below:
    Date        Value

    2014-01     0
    2014-02     0
    2014-03     0
    2014-04     0
    2014-05     0
    2014-06     4
    .. .. ..   ..
    2020-12     0

How could I convert the dataframe and shrink the columns into rows ?

A: Let us check melt
df.columns = df.columns[[0]].tolist() + list(range(1,13))
s = df.melt('Year')
s['Year-month'] = s[['Year','variable']].astype(str).agg('-'.join, 1)
s
Out[39]:
    Year variable  value Year-month
0   2014        1      0     2014-1
1   2015        1      0     2015-1
2   2016        1      0     2016-1
3   2017        1      0     2017-1
4   2018        1    252     2018-1
..   ...      ...    ...        ...
79  2016       12    114    2016-12
80  2017       12      0    2017-12
81  2018       12    143    2018-12
82  2019       12      0    2019-12
83  2020       12      0    2020-12
[84 rows x 4 columns]


text:
Q: Save to session - Does a cache mean the back end code doesn't always run? So for a bit of background, I am creating a website with the Zend Framework.  There is a page where I am using AJAX to save a rating to my database.  I obvious need the key for the store in order to know what store the rating is to be saved for.
In order to access the store for the page, the URL is MYSTORE.com/stores/2.  The 2 is the store key, so it could be 13, 10, whatever.  What my PHP script currently does is when it loads the page, it stores the store_id as a session.  Then if they rate the store (all in JS), it will snag the store_id value from session, and combine them to send an insert to my database.  So here's my problem.
Somewhere down the line, I'll probably want to cache to save my server some trouble.  I have never used one before, and am worried that instead of running the script that saves the store_id to session, the page loads from the cache and never stores store_id.  This would mean that the review could theoretically be saved to the wrong store.  Is this a reasonable worry, and is there a way around this?
My other question is if there was maybe a better way to do it.  I'm hesitant to place the store id into the JS or HTML since (at least I think) you can mess with the scripts through Firebug, or other web tools.  I'd like my page to be secure.  Is there a better way to do this?
I hope my question makes sense, and thank you in advance.
-Ethan

A: My advice is don't solve a problem until you have a problem. When they load the page just put the movie ID in the URL, possibly with some sort of checksum or hash so someone can't just blanket upvote and downvote every ID.
There's no need to store this in the session. Just keep it in the database until you need to change it. Don't forget that sessions are file-based. Using them for performance gains is a little misguided. Just use them where appropriate.
Knuth said "premature optimization is the root of all evil" and that's what this looks like to me. You're right in that you greatly complicate your code by keeping an ID in the session and that can get out of sync with what the user is seeing (eg using the back button). Stick the ID in the Webpage and that problem is solved.


text:
Q: How do I add more than 6 items to my Chrome extension's action menu? I've been working on a Chrome extension and adding custom options such as radio buttons to the contxtmenu. After I add six items in my background.js, using the chrome.contextMenus.create command, any subsequent items I add are ignored. I understand that there's a default limit of 6 context menu items you can add, but there's also this command:
chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT.
I tried setting this to chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT = 10, but the limit remained at 6. Is there any way to change the limit so I can add more than 6 items?

A:
Is there any way to change the limit so I can add more than 6 items?

No, this is a constant set by API. As you noticed, changes are ignored - it's only provided so you can use it in your code as a limiter in case that ever changes (to avoid 6 as a "magic number").
Note that it only limits the top level items: therefore, you can create a cascading menu (by specifying parentId in create) that does not have this limitation.


text:
Q: Magento extremely slow My server TTFB wait time is 14 seconds ,
Total loading time is 24.5 seocnds
I have attached my waterfall for GT metrix:
How can I deal with it ??
I am done with following :

*

*I have minified css and JS

*Enabled Flat category

*Production mode is enabled

*Cloudfront images are enabled

*Upgraded Magento version

*Advance JS bundling

The whole store is slow but the product page is extremely slow.
Shall I go for Full page cache warmer extension?
Should I configure Varnish & redis ?
I am also done with advance JS bundling  It reduces only 4 to 5 seconds
Kindly suggest solutions!!!!

A: if you have 14sec TTFB this is related to your code processing time, check profiler or newrelic,
probably you are trying to load something big on that page.
https://devdocs.magento.com/guides/v2.4/config-guide/bootstrap/mage-profiler.html

js bundle is bad


text:
Q: HLS video with special characteres in URL doesn't play on iOS Safari (Flutter) I'm working on a video stream type of APP in Flutter. I implemented the video streaming with better_player and the video itself is being hosted on AWS.
Everything working fine until I tried testing on an iOS device and it broke. I pinpointed the problem as being in the video's URL, since better_player wasn't being able to find the video. All the videos that didn't load had special characteres in their URL (Ç, Ã, Â, Á, À), which are very commom in portuguese, then the URL is encoded as an URI, but the m3u8 file still references the non-encoded .ts URLs and iOS seem to not parse these automatically.

As you can see the highlighted words all have a ú character, and it just breaks everything, thus making iOS/Safari not being able to retrieve the video.
Does anyone have any insight about it?
Can I solve it inside Flutter or do I have to change all my URLs (I would prefer not doing it)?
Possible duplicate of this, but it doesn't have any answers so I thought of asking again.
I tried encoding the stream URL into a URI friendly format, iOS still can't load it.


text:
Q: put tables side by side with divs I am trying to learn spanish and basic webdesign at the same time. I am trying to organize these tables side by side but they are not aligning next to each other. I thought all you needed to do was to put in float: left in the css classes however it is not working. Please help!
<!doctype html>

        1-9

        #
        unidades

        1
        uno

        2
        dos

        3
        tres

        4
        cuatro

        5
        cino

        6
        sies

        7
        siete

        8
        ocho

        9
        nueve

        10-90

        #
        decenas

        10
        diez

        20
        veinte

        30
        treinta

        40
        cuarenta

        50
        cincuenta

        60
        sesenta

        70
        setenta

        80
        ochenta

        90
        noventa

        100-900

        #
        centenas

        100
        cien

        200
        doscientos

        300
        trescientos

        400
        cuatrocientos

        500
        quinientos

        600
        siescientos

        700
        setecientos

        800
        ochocientos

        900
        novecientos

A: You close your divs with
. It should be
.
You also need to remove your
s (which by the way, don't exist, a line break is
).
Demo: http://jsfiddle.net/m233m/

A: Have you tried placing your tables within 2 table td's... like so

//Place Your First Tables Code Here

//Place Your Second Tables Code Here


text:
Q: Searchable SearchView setSuggestionsAdapter() in android studio I'm working on an app. It requires a searchview. im facing a problem while working with cursor adaptor. i simply want a string array or xml string array to displayed in suggestion adaptor. when i click on search button it show suggestion and on suggestion click it do given work.
i need codes that will help me sort out this problem. I'm not a professional programmer.

A: You can achieve Using SearchAutoComplete view,try something below like this
      @Override
        public boolean onCreateOptionsMenu(Menu menu) {

           getMenuInflater().inflate(R.menu.activity_main_menu, menu);
           searchMenuItem = menu.findItem(R.id.action_search)

           searchView = (SearchView) searchMenuItem.getActionView();
           searchAutoComplete = (SearchView.SearchAutoComplete) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);

           SearchManager searchManager =
                            (SearchManager) getSystemService(this.SEARCH_SERVICE);
                    searchView.setSearchableInfo(
                            searchManager.getSearchableInfo(getComponentName()));

           ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.suggetion, jsonArrayList);

                    // jsonarraylist is static string array

           searchAutoComplete.setAdapter(adapter);

           searchAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                          // Your code for onitemclick
           }
        }

activity_main_menu.xml
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <item
            android:id="@+id/action_search"
            android:icon="@drawable/ic_search"
            android:title="@string/search"
            app:actionViewClass="android.support.v7.widget.SearchView"
            app:showAsAction="always|collapseActionView"/>
    </menu>

suggetion.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/dropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:background="@color/colorAccent"
    android:textAppearance="?android:attr/textAppearanceLargePopupMenu"/>

I hope this may help you,All the best.


text:
Q: Caffe Build Error in Windows 10 I'm trying to build Caffe in Windows 10 following instructions here. I have installed all the prerequisites and dependencies. But I'm getting following error.
-- The C compiler identification is unknown
-- The CXX compiler identification is GNU 6.3.0
-- Check for working C compiler: C:/MinGW/bin/gcc.exe
-- Check for working C compiler: C:/MinGW/bin/gcc.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-
3.9/Modules/CMakeTestCCompiler.cmake:51 (message):
 The C compiler "C:/MinGW/bin/gcc.exe" is not able to compile a simple test
 program.

 It fails with the following output:

  Change Dir: C:/Caffe/caffe/build/CMakeFiles/CMakeTmp

 Run Build Command:"C:/Ninja/ninja.exe" "cmTC_6595e"

 [1/2] Building C object CMakeFiles\cmTC_6595e.dir\testCCompiler.c.obj

 FAILED: CMakeFiles/cmTC_6595e.dir/testCCompiler.c.obj

 C:\MinGW\bin\gcc.exe -o CMakeFiles\cmTC_6595e.dir\testCCompiler.c.obj -c
 testCCompiler.c

 ninja: build stopped: subcommand failed.

 CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
 CMakeLists.txt:18 (project)

-- Configuring incomplete, errors occurred!
See also "C:/Caffe/caffe/build/CMakeFiles/CMakeOutput.log".
See also "C:/Caffe/caffe/build/CMakeFiles/CMakeError.log".
ERROR: Configure failed

Caffe Build Error
I searched for a solution and tried different things but nothing could solve the problem. Any help with this regard is highly appreciated.
Thanks in advance!

A: I finally figured it out. It was a problem with the C Compiler in my computer - gcc. I reinstalled the compiler and following two lines to CMakeList.txt file according to this solution,
set(CMAKE_C_COMPILER "C:/MinGW/bin/gcc.exe")
set(CMAKE_CXX_COMPILER "C:/MinGW/bin/g++.exe")


text:
Q: Custom Info View Controller index Is it possible to change Custom Info View Controller's index in AVPlayerViewController?
customInfoViewController

A view controller that provides client-specific content and controls
  alongside system-provided information and settings panels. SDK
tvOS 11.0+

Declaration Swift

var customInfoViewController: UIViewController? { get set }

Declaration Objective-C

@property(nonatomic) UIViewController *customInfoViewController;

Let's take a look inside of AVPlayerViewController.h
...
/*!
    @property   customInfoViewController
    @abstract   A view controller to be displayed alongside system-provided info and settings panels.
    @discussion Use this property to provide client-specific content and controls in an additional info view. Implement -preferredContentSize to provide the desired view size.
 */

@property (nonatomic, nullable) UIViewController *customInfoViewController API_AVAILABLE(tvos(11.0));

...
By default, it's the second item at info panel (after info tab). I want to show at first index.

A: tvOS 15.0
In AVPlayerViewController it is possible to set order of customInfoViewControllers by ading them into Array in desired order as following: customInfoViewControllers = [viewController1, viewController2]. However if you also have Info controller presented (by setting item metadata) , the Info controller is displayer always as first and customInfoViewControllers are only appended next to it by the order you defined in array. The only solution for you might be just completely disabling Info controller by not setting item metadata and setting  just customInfoViewControllers alone.

A: For now it's not possible. Maybe in future releases of tvos.


text:
Q: Elasticsearch match multiple IP subnets DSL Query I am trying to do a DSL Query filter in Kibana for a specific URI, while matching multiple IP subnets.
So far I have managed to make it work with only one IP subnet:
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "uripath": "/specific-uri-path"
          }
        },
        {
          "match": {
            "clientip": "10.0.0.0/8"
          }
        }
      ]
    }
  }
}

But if I try to match for multiple subnets, it fails (probably because match can only contain different fields):
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "uripath": "/specific-uri-path"
          }
        },
        {
          "match": {
            "clientip": "10.0.0.0/8",
          "match": {
            "clientip": "14.0.0.0/8"
          }
        }
      ]
    }
  }
}

A: I was able to make it work with the terms query. That means that I can also use an array of values for "clientip", so overall it's cleaner. I hope it will help someone else too.
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
        "uripath.keyword": "/specific-uri-path"
      }
    },
    {
      "terms": {
        "clientip": [
          "10.0.0.0/8",
          "14.0.0.0/8",
          "20.0.0.0/8"
        ]
      }
    }
   ]
  }
 }
}


text:
Q: android ExpandableListView animate drop down and up? Recently I meet a question is that how to let the ExpandableListView animate drop down and up. I search the result on StackOverflow.
There's an answer:Android animate drop down/up view proper
But it fit to the ListView. When I use it on ExpandableListView, it doesn't work. I think there must be someone who can solve this similar problem. If you have free time, could you tell me the solution or give tips to the question.


text:
Q: How to add styling to an option in ie 8 via JQuery Here is what I am trying to do:
 for (var i = 0; i < paramLength; i++) {
    if (parameters[i].substr(0, 2) == '@_')//Required
    {
        $('#ddParam' + id).append($("<option style='font-style:italic'></option>").attr("value", parameters[i]).text(parameters[i] + ' (REQUIRED)'));
    }
    else
    {
        $('#ddParam' + id).append($("<option></option>").attr("value", parameters[i]).text(parameters[i]));
    }
}

NOTICE the STYLE tag in the OPTION -- this works fine for me in FF but (hang on to your hat) -- is not working in IE8 and that (unfortunately) is the browser that I am designing this app for....
Any suggestions and thanks!

A: I suggest using classes - they are faster than adding single styles one by one. Use on jQuery object addClass('classnameX') or if you like styles: css({'key1':'val1','key2':'val2'}).

A: Have you considered that styling capabilities of <select> elements is very browser specific.
IE did not support that prior to IE8, browsers vary in style on that element a good deal as they do with many form elements.
Further Questions:

*

*Is it possible to style a select box?

*Styling HTML SELECT in Internet Explorer


text:
Q: Making a div dissapear after 5 seconds, validation error message I have a div called ".error" which appears if an registration form is submitted and it has errors, it doesn't appear otherwise. I am trying to make a javascript statement incorporating jquery which uses an if structure.
For example

if error div is visible after submit button is clicked

remove the error div after several seconds

end if statement

Any help would be appreciated
Thanks!
Edit: Here is my actual code, I have tried implementing some of the examples provided but none have worked thus far.

<?php
   $validation_errors = '';
   $proc_errors = '';
   if (isset($_POST['register'])) { // User submitted registration form
   require_once "formvalidator.php";
   $validator = new FormValidator();
   $validator->addValidation("new-username","req","Please enter a username");
   $validator->addValidation("new-username","minlen=5","Username cannot be less than 5           characters");
   $validator->addValidation("new-username","maxlen=25","Username cannot be more than 25 characters");
   $validator->addValidation("new-username","alpha","Username must not contain spaces, numbers or strange characters");

   $validator->addValidation("new-password","req","Please enter a password");
   $validator->addValidation("new-password","minlen=5","Password must be at least 5 characters!");
   $validator->addValidation("new-password","maxlen=25","Password cannot be more than 25 characters");

   $validator->addValidation("new-password2","eqelmnt=new-password","The confirmation password does not match");
   $validator->addValidation("new-password2","req","Please enter the confirm password field");

   $validator->addValidation("email","email","Please enter a valid e-mail address");
   $validator->addValidation("email","req","Please enter a valid e-mail address");

   $validator->addValidation("forename","req","Please enter your forename");

   $validator->addValidation("surname","req","Please enter your surname");

   $validator->addValidation("securityquestion","dontselect=--Select One--","Please choose a security question");

   $validator->addValidation("securityanswer","req","Please enter a security answer");
   $validator->addValidation("securityanswer","minlen=5","Security answer must be more than 4 characters");

   if($validator->ValidateForm()) {
    //If the validations succeeded, proceed with form processing
    $formproc = new regProcessor();
    $res = $formproc->ProcessForm();
    if($res == "SUCCESS") {
        header("Location: registrationsuccess.php"); /* Redirect browser */
        exit();
    } else {
        $proc_errors = '
'.$res.'
';
    }
   } else {
    //Validations failed. Display Errors.
    $error_hash = $validator->GetErrors();
    $validation_errors = '';
    foreach($error_hash as $inpname => $inp_err) {
       $validation_errors .= '
'.$inp_err.'
';
    }
  }
 }
?>

A: To hide the div, create a function such as the one below that uses jQuery hide.
var hideError = function () {
    $(".error").hide();
};

(you can safely call this even if the error div is already hidden)
Call it when your form is submitted (with a jQuery submit event handler), but after a 5 second delay by means of setTimeout.
$("form").submit(function () {
    setTimeout(hideError, 5000);
});

This means that any validation message will be hidden if the user submits the form by clicking the Submit button, but also if they do so by pressing Enter on their keyboard.

A: Use Javascript's setTimeout function, thuswise:
setTimeout(function() {
      // remove your error div
}, 5000);

A: for example:

<button type="submit" onclick="message();">submit</button>

function message() {

 $('#message').show();
 setTimeout(function() { $('#message').hide(); }, 5000);

}

A: $("button").click(function(){
    if ($("div").css("visibility","visible")) {
        setTimeout(function(){$("div").css("visibility","hidden")},2000)
    }
})

This will work if you have hidden this message using visibility if not then change relevant parts accordingly, if you need help just ask

A: If you want a more jQuery idiomatic approach, then extent jQuery:
Define an jQuery extension function:
$.fn.delayedHide = function(delay) {
  var that = this;
  window.setTimeout(function () {
    that.hide();
  }, delay || 5000);
  return that;
}

Now suppose you have the following HTML:

MSG1

MSG2 (ERR)

MSG3

MSG4 (ERR)

Then you can hide all error messages at once with
$(".msg-err").delayedHide();

Full example: http://jsfiddle.net/8wh4h/1/

A: For a smooth transition you could use the jQuery fadeIn/fadeOut functions with a delay after fading in.
$('.error').fadeIn(600, function() {
    $(this).delay(4000).fadeOut(600);
});


text:
Q: how to make REFrostedViewController work with UINavigationController I am using REFrostedViewController library to show side bar menu in my project, which has a tableview to show the content.
When the table cell is selected, I want to show a new page. I want to use UINavigationController to push a new view on top. But it seems that there is no UINavigationController stack in REFrostedViewController context.
How can I achieve UINavigationController behavior to work with REFrostedViewController?

A: In my setup, the FrostedViewController is the rootViewController right from the beginning. It's contentViewController is my NavigationViewController. In the AppDelegate I did the following:
TMSlideMenuViewController *menuController = [[[[self window] rootViewController] storyboard] instantiateViewControllerWithIdentifier:@"slideMenuViewController"];
REFrostedViewController *frostedViewController = [[REFrostedViewController alloc] initWithContentViewController:self.window.rootViewController menuViewController:menuController];

self.window.rootViewController = frostedViewController;

In TMSlideMenuViewController, didSelectRowAtIndexPath method you can do this:
TMNavigationController* navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"tmNavigationController"];

switch (indexPath.item) {
    case 0:
        // Favorites

        frostedViewController.contentViewController = navigationController;
        [navigationController pushViewController:sourcesViewController animated:YES];
        break;

In order to push a ViewController, you should set the contentViewController to your NavigationController. For me, it worked that way.


text:
Q: Running program through Visual Studio causes it to fail? I have a problem with a program that I'm writing. It is a command line parser that parses bencode (used in torrent files). The program accepts a filename as it's command line. When I build and run the program in Microsoft Visual Studio 10.0 using the debugging Commmand Line arguments setting to input a command line the program tells me that it failed parsing.
If I open a command prompt and run the program from the command prompt with the same command line, the program works perfectly! What's going on? Is this a common problem with Visual Studio?
I used the debugger in Visual Studio to trace where the program fails and it appears that a call to the stat function ( http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx ) used to get the length of the file returns an error in Visual Studio but works fine when run outside of Visual Studio.
The Code uses a Bencode parser which can be found here: http://funzix.git.sourceforge.net/git/gitweb.cgi?p=funzix/funzix;a=blob;f=bencode/bencode.c
And here is the code for the program:
#include <stdio.h>
#include "../Parse/bencode.h"

int main(int argc, char *argv[]){
if(argc != 2){
    printf("Usage: whirlwind filename\n");
    return 1;
}

char *buf;
long long len;
be_node *n;

//read the torrent file into a buffer and store at &buf
buf = read_file(argv[1], &len);
if(!buf){
    buf = argv[1];
    len = strlen(argv[1]);
}

printf("Decoding: %s\n", argv[1]);
n = be_decoden(buf, len);

if(!n){
    printf("Parsing failed!\n");
    return 1;
}

if(n->type != BE_DICT){
    printf("This file is not a valid Bencoded Dictionary.\n");
    return 1;
}

int i;
char* keyName;

for(i = 0; i < 10; i++){
    keyName = n->val.d[i].key;
    if(keyName == "announce"){
        printf("\n\n");
    }
    printf("%s\n", keyName);
    if(keyName == "announce"){
        printf("\n\n");
    }
}

return 0;

}

A: If you pass a relative path from Visual Studio you should be sure that it resolves correctly when your app runs inside the IDE. This problem arises because, when debugging, the current directory is usually \bin\debug.
To be on the safe side put a full pathname or read the location of your file from a configuration file.


text:
Q: compare two different collection with the column value I have two different collection, customer and prospect. _Id(customer collection) is presented in prospect collection with the name of customerId.. Now I want to get the customer details based on the customerid. how to achieve it

db.getCollection('st_salesquotes').find({CustomerId:'5a66f2549ca9b27c4df31e62'})

I want to display the customers who are all present in salesquote based on the _id(customer collection)


text:
Q: Which is faster/better for caching, File System or Memcached? I don't think it's clear to me yet, is it faster to read things from a file or from memcached?  Why?

A: "Faster" can not be used without context.
For example, accessing data in memcached on remote server can be "slower" due to network latency. In the other hand, reading data from remote server memory via 10Gb network can be "faster" than reading same data from local disk.
The main difference between caching on the filesystem and using memcached is that memcached is a complete caching solution. So there is LRU lists, expiration concept (data freshness), some high-level operations, like cas/inc/dec/append/prepend/replace.
Memcached is easy to deploy and monitor (how can we distinguish "cache" workload on filesystem from, let's say kernel? Can we calculate total amount of cached data? Data distribution? Capacity planning? And so on).
There are also some hybrid systems, like cachelot
Basically, it's memcached that can be embedded right into the application, so the cache would be accessible without any syscalls or network IO.

A: In fact, it is not as simple as that reading from memory is much faster than reading from HDD. As you known, Memcached is based on tcp connection, if you make connection each time you want to get sth or set sth to memcached server(that is most of programmers do), it proberly performs poorly than using file cache. You should use static Memcached object, and reuse the object. Secondly, the modern OS's will cached files that are frequently used, that makes file caches might be faster than memcaches which are actualy TCP connections.

A: Memcached is faster, but the memory is limited. HDD is huge, but I/O is slow compared to memory. You should put the hottest things to memcached, and all the others can go to cache files.
(Or man up and invest some money into more memory like these guys :)
For some benchmarks see: Cache Performance Comparison (File, Memcached, Query Cache, APC)
In theory:
Read 1 MB sequentially from memory       250,000 ns
Disk seek                             10,000,000 ns

http://www.cs.cornell.edu/projects/ladis2009/talks/dean-keynote-ladis2009.pdf

A: Cache Type | Cache Gets/sec
Array Cache | 365000
APC Cache | 98000
File Cache | 27000
Memcached Cache (TCP/IP) | 12200
MySQL Query Cache (TCP/IP) | 9900
MySQL Query Cache (Unix Socket) | 13500
Selecting from table (TCP/IP) | 5100
Selecting from table (Unix Socket) | 7400
Source:
https://surniaulula.com/os/unix/memcached-vs-disk-cache/
Source of my source :)
https://www.percona.com/blog/2006/08/09/cache-performance-comparison/

A: There are quite a few different aspects that might favour one or the other:

*

*Do you need/want to share this data between multiple servers? The filesystem is local, memcached is accessed over a network.

*How large are the items your caching? The filesystem is likely to be better for large objects.

*How many memcached requests might be there per page? TCP connections and tear-downs might take up more time than a simple filesystem stat() on the local machine.

I would suggest you look at your use case and do some profiling of both approaches. If you can get away with using the filesystem then I would. Adding in memcached adds in another layer of complexity and potential points of failure (memcached client/server).
For what it's worth the other comments about disk vs memory performance might well be academic as if the filesystem data is being accessed regularly then it'll likely be sitting in OS or disk cache memory anyway.

A: You're being awefully vauge on the details. And I believe the answer your looking for depends on the situtation. To my knowledge very few things tend to be better than the other all the time.
Obviously it woudln't be faster to read things of the file system (assuming that it's a harddrive). Even a SDD will be noticably slower than in-memory reads. And the reason for that is that HDD/FileSystem is built for capacity not speed, while DDR memory is particulary fast for that reason.
Good caching means to keep frequently accessed parts in memory and the not so frequently accessed things on disk (persistent storage). That way the normal case would be vastly improved by your caching implementation. That's your goal. Make sure you have a good understanding of your ideal caching policy. That will require extensive benchmarking and testing.

A: It depends if the cache is stored locally.  Memcache can store data across a network, which isn't necessarily faster than a local disk.

A: If that file is stored in disk, and it is accessed frequently, there will be a high probability of finding it in the RAM (as a recently accessed file) or I am missing something here?
Yes the first read will be from the disk which is awefully slow, but what about the subsequent reads (assuming that file is hot and its getting lots of reads) this should be even faster than memcached as this is a pure RAM read


text:
Q: C++ function pointer as parameter in Doxygen I have a situation where I need to document the bsearch() signature in Doxygen. That signature looks like this:
void * __cdecl bsearch (
    const void *key,
    const void *base,
    size_t num,
    size_t width,
    int(__cdecl *compare)(const void *, const void *)
    )

The problem I am having is how to compose the @param command for the pointer *compare since Doxygen complains "argument 'compare' of command @param is not found in the argument list of bsearch" at everything I throw at it.
This is a standalone implementation, so it is not dependent on a library signature, however I am thinking if I did:
typedef int(__cdecl *pcompare)(const void *, const void *);

changing the signature to pcompare compare that callers using the standard signature would have a type problem.
I am open to ANY solution that allows me to document this without alarm from Doxygen.

A:
however I am thinking if I did:
typedef int(__cdecl *pcompare)(const void *, const void *);

changing the signature to pcompare compare that callers using the standard signature would have a type problem.

You should have tried it before giving up.  typedef does not define a new type, it just creates a new identifier for a complex type.  The resulting signatures are identical.
Be careful though, because neither of the forms shown are the correct signature.  To declare A C runtime library function like bsearch you need extern "C". (and so would the function pointer typedef -- language linkage is part of the function type)
All of that said, just setting __cdecl as a predefined macro in your doxygen config would probably be sufficient to allow it to parse all of these variations, including the ones with a complex set of tokens specifying the parameter type.

A: There's no problem with the typedef.
You should use it anyways --- it's clearer to read.


text:
Q: How to filter out this special pattern using python re.findall? I want to find out some special keywords in a long strings.
Here are the example:
long_str = '''
TX[03]
rqn : 0x73
cqn : 0x12
packets : 888
encap : 0
csumNone : 0
csumOk : 0
lroPackets : 0
lroBytes : 0
wqeErr : 0
RX[12]
rqn : 0xa6
cqn : 0x2a
packets : 123
encap : 0
csumNone : 0
csumOk : 0
lroPackets : 0
lroBytes : 0
wqeErr : 0

RX[13]
rqn : 0xa9
cqn : 0x2c
packets : 456
encap : 0
csumNone : 0
csumOk : 0
lroPackets : 0
lroBytes : 0
wqeErr : 0'''
result = re.findall('RX\[\d+\].*packets\s+:\s+(\d+)', a, re.DOTALL)

But the result is ['456'], which is not the same as my expected ['123','456'].
How can i fix my re pattern to filter out the expected values?
Thanks in advance.

A: The simplest solution would be to make it lazy:
RX\[\d+\].*?packets\s+:\s+(\d+)

See it working on regex101.com.
Otherwise, your .* construct eats up the whole string and backtracks afterwards (succeeding when it finds the last packets, that is).

Another one would be:

RX\[\d+\]\n
(?:.+\n){2}
packets\D+(\d+)

See this one working here (and mind the different modifers!).

A: As mentioned in the docs https://docs.python.org/2/library/re.html, the '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against <a> b <c>, it will match the entire string, and not just <a>. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only <a>.
Similarly in your case, result = re.findall('RX\[\d+\].*?packets\s+:\s+(\d+)', a, re.DOTALL) would give the expected result.


text:
Q: Jquery slide menu x-scroll issue I have built a custom slide menu which is giving me a slight bit of grief. Click here for example when you click the menu button, the slide menu pushes the background image to the right and leaves and excess of x-scroll.
My objective for this function is to have sliding menu to sit on top of background image. Currently my background image is an  tag and is absolute positioned as the clients wants to update images manually. this maybe the main reason why this issue is occurring. Also the div id="right" is wrapping all the content, including the background image. I have trying placing around with where i wrap the content however i can't figure out a method to make this work correctly i am wondering if there is a way to to work around this  Below is a snippet of code, both javascript and HTML structure.
$('#button').toggle(
function() {
    $('#right').animate({ left: 400 }, 'slow', function() {
        $('#button').html('Close');
    });
},
function() {
    $('#right').animate({ left: 0 }, 'slow', function() {
        $('#button').html('Menu');
    });
}

);

            Menu

Menu Item 1

Menu Item 2

Menu Item 3

Menu Item 4

Menu Item 5

Menu Item 6

Menu Item 7

Menu Item 8

Menu Item 9

Menu Item 10

Menu Item 11

Menu Item 12

can someone advise me on a way i can solve this issue?

A: Simpy add :
Body{
    overflow-x:hidden;
}

So hide the body-s horizontal scroll.
More information about owerflow.


text:
Q: Find the index of a list element in Python How could I find a certain index as to where one of the elements is located at within sets. So I would like to find where (2.0, 2.0, 152) is located within the sets list, which is the 5th index. Is there a function that I would be able to use to get to that?
from itertools import groupby
from itertools import accumulate
import itertools

#Configs
Lower = [round(x * 0.5,1) for x in range(4,23)]   #ideal = (4,13) Lower and upper boundary values
Upper = [round(x * 0.5,1) for x in range(4,23)] # ideal between (10-23)
number = [round(x *0.5,5) for i in range(100, )]    #used for calculations with stand deriv and linear reg
list_set = [Lower, Upper, number]
sets = []
for element in itertools.product(*list_set):
    print(element)
    sets.append(element)

A: You can use the index-method for that:
sets.index((2.0, 2.0, 152))

The method raises a ValueError if the supplied value is not in the list, which seems to be the case for (2.0, 2.0, 152).

A: There are two ways you could go about finding the index of an element from an array in Python.
The first and the most straightforward way to do so is by using the .index() method of any list, which returns the index at which the specified value is located. Take this example:
list = [123, 417, 098]
print(list.index(417))

You can see here that it will print one, because that is the index at which 417 is located in the list array. Though, keep in mind that you might get an error if the specified value doesn't exist.
The second and harder way is by iterating through the array yourself. Take this example:
list = [123, 417, 098]

def findElement(array, element):
    for index in range(len(array)):
        if (array[index] == element):
            return index

print(findElement(list, 417))

What we did here was to define a method which takes as parameters an array and an element, then, iterates through every index of the list, until the value at that index is the specified element. When the values match, it will return the said index. If no values will ever match, it won't return anything.
The advantage of the second approach is the fact that it won't throw an error if there is no such element in the list, however, it is also a bit harder to set up.

A: try:
    print(sets.index(element))
except:
    print('not found')

If you gonna use more better keep in a dict indexes,which can retrieve you index in O(1) time.Construction can take O(n) time though


text:
Q: Migrating a git-svn branch to a git branch My project (which is rather large, at ~2 million lines of code and tens of thousands of commits) is currently switching from git-svn to git. Many users have git-svn branches with history that would be nice to have in the new pure git repository. The basic scenario is like this
The old git-svn repo:
A-B-C-D-E-F (master)

I have a branch on this repository that has merged master in several times, eg:
    G-H---I-J-K (feature)
   /     /
A-B-C-D-E-F (master)

I want to move this branch to the new pure-git repository and maintain my history. To make things more complex, the directory structure of the pure-git repository and svn repository is slightly different. Specifically, the base directory structure in this repository has two directories, e.g:

foo/
bar/

In the new git repository, bar/ has been moved to a new repository.
How can I move this branch to the new repository and end up with something like this in the pure-git repo?
    G'-H'----I'-J'-K' (feature)
    /       /
A'-B'-C'-D'-E'-F' (master)

I thought the following would work:
From the feature branch on the git-svn repo:
git filter-branch -f --index-filter "git rm -rf --cached --ignore-unmatch bar" B..HEAD

Which should remove all modifications to the foo directory, which is non-existent in the new repo.
Then, add the git-svn repo as a remote for the pure git repo and do this from the pure-git repo:
git checkout -b B' feature
git rebase --preserve-merges --onto feature remotes/old_git_svn_repo/master remotes/old_git_svn_repo/feature

Unfortunately, this doesn't seem to work. I'm still required to manually resolve all of the merge-conflicts that I've already resolved in my feature branch. Is there a way to do what I want?

A: Just as you did, the first thing you should run is a filter-branch --index-filter to fix the tree structure of your branch. But now you need to fix the parent-relationships. Depending on how many merges there have been, there are two options:

*

*Do it manually: have a look at git help replace. git replace allows you to replace one commit with another. Do this for every merge-base. For example:
git replace B B'
git replace E E'

Beware that if you don't run filter-branch on master..feature, B might allready have a different SHA.
After this step, you will need to run filter-branch again to make the replacements permanent. I would recommend doing the replacements first and then running the --index-filter. This way you get it all in one run.

*Do it with a --parent-filter. Have a look at the --parent-filter argument for filter-branch. It will allow you to specify a script to rewrite parent relationships. That script can the use the git-svn-id: that should be recorded in every ported commit message to find the matching commits in the new master.


text:
Q: Get the identifier of a table and display in another table Hello i need help the pictures below represent my problem. Thank you in advance for your help
In my select I retrieved the list of campaigns (in the Campaign table). Now in my logic (Which is the creation or I add one of an appointment, another different table) image 1 I would like to retrieve the identifier of the chosen campaign when adding it.
My select
<div class="col-6">
    <select class="form-control" name="nomCampagne">
        <option selected disabled>Sélectionnez la campagne</option>
        @foreach ($mycampagnes ?? '' as $item)
            <option value="{{ $item->id }}">{{ $item->nom }}</option>
        @endforeach
    </select>
</div>

My controller
 $appointment = Appointement::create([
    'user_id' => auth()->user()->id,
    // 'campagne_id' => $mycampagnes->id,
    'nomCampagne' => $request->nomCampagne,
    'date' => $request->date
]);


text:
Q: VHDL - D flip flop simulation goes wrong I am trying to simulate a D flip-flop using VHDL code which I compile and run using GHDL and later I ploting the waveform using GTKwave.
The problem is that my teacher told me that, when using D flip-flops, if the clock and data signal rises at the same time, the flip-flop state does not update till the next rising edge of the clock. But when I simulate that behavioral on a test bench, I get this:

Which seems to work perfect, except for the last D signal rising, where Q should update to HIGH after 10 nanoseconds. I don't know where the problem is, and it may be due to bad coding so I give you my code if it can help solve the problem.
D flip-flop module:
library IEEE;
use IEEE.STD_LOGIC_1164.all;

entity d_flip_flop is
    port (
        clk:    in  STD_LOGIC;
        d:      in  STD_LOGIC;
        reset:  in  STD_LOGIC;
        q:      out STD_LOGIC
    );
end entity;

architecture asynchronous of d_flip_flop is
begin
    process (clk, reset) begin
        if reset = '1' then
            q <= '0';
        elsif clk'event and clk = '1' then
            q <= d;
        end if;
    end process;
end architecture;

D flip-flop test bench:
library IEEE;
use IEEE.STD_LOGIC_1164.all;

entity d_flip_flop_tb is
end entity;

architecture testbench of d_flip_flop_tb is
    component d_flip_flop
        port (
            clk:    in  STD_LOGIC;
            d:      in  STD_LOGIC;
            reset:  in  STD_LOGIC;
            q:      out STD_LOGIC
        );
    end component;

    signal clk, d, reset, q: STD_LOGIC;
begin
    uut: d_flip_flop port map (clk, d, reset, q);

    process begin
        clk <= '0'; wait for 5 ns;
        clk <= '1'; wait for 5 ns;
    end process;

    process begin
        reset <= '1'; d <= '1'; wait for 12500 ps;
        reset <= '0';           wait for 10 ns;
        d <= '0';               wait for 12500 ps;
        d <= '1';               wait for 20 ns;
        assert false report "End of simulation" severity failure;
        wait;
    end process;
end architecture;

A:
The problem is that my teacher told me that, when using D flip-flops, if the clock and data signal rises at the same time, the flip-flop state does not update till the next rising edge of the clock.

This is a highly idealized description, and not even a very useful one.
A much better model for the behavior, which is still quite simple, is that

If the input is stable during the clock edge, for a "setup time" beforehand and a "hold time" after, that same stable level will emerge from the output after a "delay time".

And no guarantees are made if, as in your simulation, the input is changing within the setup-and-hold window.
In actual circuits, clock distribution is designed to be faster than signal distribution, so that changes happen after the clock edge.  And the hold requirement in modern logic is very nearly zero.  In such cases things work.
But if the delays in the logic producing the flip-flop's input add up to nearly a whole clock cycle, you can get into trouble with setup time violations.
And if you are doing your own PCB layout and not careful to make the clock the shortest trace, then signals synchronized to the clock in one part of the circuit can outrace it and be seen to transition in another part before the clock edge, which also violates the setup&hold requirement.

A: The problem is with how you're driving d in your testbench.
Although in hardware, the logic would execute simultaneously, the simulator has to execute one of the assignments before the other as a delta time step. Since the process in your testbench is not sensitive to clk, the simulation has trouble deciding if clk<='1' or d<='1' happens first.
My preferred solution would be to clock the process in the testbench rather than rely on wait for statements, but if you are looking for a one line solution, add wait until clk'event and clk='1'; between the d<='0' line and the d<='1' line. This will let the simulator know that the clock event comes before the transition d<='1'.

A: For this simulation you assign d to HIGH at the same time clock rises.
Simulation takes that value and assigns it to d. At the same time it goes into your elseif pathway because the clock is high and it assigns the value of D.

A:
... and it may be due to bad coding so I give you my code if it can help solve the problem.

Yes, it is bad coding, bad testbench coding.
You are trying to set up edges to be simultaneous, which is a bad idea anyway. In real life, edges that are simulataneous (within the definition of setup and hold times) are dangerous. They could arrive in either order, or they could make the output metastable, which is even worse than not knowing whether the output is supposed to be 0 or 1.
So aside from the desirability of producing simultaneous changes, the way you have done it is not the way to do it. You have two different processes, one waiting multiples of 5nS, the other waiting 12.5nS, then 10nS, then 12.5nS, in the hope that they will line up at 35nS.
A well known way to get things wrong when computing is to assume that floating point numbers are exact. For instance, 1.0 + 0.1 - 1.1 is not 0.0, not in IEE754 doubles anyway. It's likely that your two different ways of getting to 35nS are different, at least at the few LSBs level.
If you still want to test simultaneous changes, check your VDHL simulator documentation to see whether if you generate them in the same process at the same time, it will implement them simultaneously, or whether they will still be ordered.


text:
Q: macOS - Convert ELF shared object file to MACHO I have a .so library file that I need to reference from C under macOS. file gives:
ELF 32-bit MSB shared object, MIPS, MIPS-II version 1 (SYSV), dynamically linked, stripped

How can I munge the contents of the library so that it can be linked under macOS?
I have tried: objconv, objdump, readelf, dwarfdump - but the flags and output are unintelligible to me so far.
The joint furthest I get is with gobjcopy, but then:
gobjcopy: Unable to change endianness of input file(s)

Also, objconv throws:
Error 2022: Cannot convert executable file

Do I need to deconstruct the .so into object files first, convert each and then bundle them back up to together?
Thanks for all help.


text:
Q: Android ChipGroup : Multiline text in Chips In an Android app, I need to create clickable chips within a Chat bubble (see image below).

I have added a ChipGroup below the TextView but since the text for chips is too long, it is getting clipped.
Any idea how I can have a multiline text in Chip or any workaround for this?

A: Unfortunately chips does not support multiline text. Below is the reference from Chip.java
@Override
public void setSingleLine(boolean singleLine) {
    if (!singleLine) {
          throw new UnsupportedOperationException("Chip does not support multi-line text");
    }
    super.setSingleLine(singleLine);
}

@Override
public void setLines(int lines) {
    if (lines > 1) {
          throw new UnsupportedOperationException("Chip does not support multi-line text");
    }
    super.setLines(lines);
}

@Override
public void setMinLines(int minLines) {
    if (minLines > 1) {
         throw new UnsupportedOperationException("Chip does not support multi-line text");
    }
    super.setMinLines(minLines);
}

@Override
public void setMaxLines(int maxLines) {
    if (maxLines > 1) {
         throw new UnsupportedOperationException("Chip does not support multi-line text");
    }
    super.setMaxLines(maxLines);
}

However we trying to implement the similar behaviour with AppCompatCheckBox as chip inherits the same class.
You can use chip class for detail reference :https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/chip/Chip.java


text:
Q: Streaming of images via nodejs I've been working on a solution, that would stream a series of jpg's to the client, and show them as they were a video. This is to avoid autoplay issues on iPads within a panoramic presentation. We don't need audio, so I tried looking into MJPEG, but since the browser never caches a stream, it's not a viable solution, although it performs really well on the client.
Have any of you come across something similar, and have you solved it? At this point I'm getting slightly obsessed with getting it to work!
The node.js MJPEG streaming server looks like this so far:
var express = require('express'),
    fs = require('fs'),
    http = require('http');

var app = express();

var server = http.createServer(app);

// Routes
app.use(express.static('app'));

app.get(/\.(mjpeg)$/i, function(request, res) {
    var path = res.req._parsedOriginalUrl.path,
        string = path.replace(/.*\\|\..*$/g, ''),
        name = string.replace('/', '');

    var files = fs.readdirSync('app/assets/streams/' + name + '/');

    res.writeHead(200, {
        'Content-Type': 'multipart/x-mixed-replace; boundary=myboundary',
        'Cache-Control': 'no-cache',
        'Connection': 'close',
        'Pragma': 'no-cache'
    });

    var i = 1, id;
    var stop = false;

    res.connection.on('close', function() { stop = true; });

    var send_next = function () {
        if (stop)
            return;

        i = (i + 1);

        // Increment with zero based number padding. (SO: ignore this, implementation specific)
        if (i < 100 && i >= 10)
            id = '0' + i;
        else if (i < 10)
            id = '00' + i;
        else
            id = i;

        var filename = id + '.jpg';

        //console.log(i, id, 'file length:', files.length, 'Path: app/assets/streams/' + name + '/' + filename);

        fs.readFile('app/assets/streams/' + name + '/' + filename, function (err, content) {
            res.write("--myboundary\r\n");
            res.write("Content-Type: image/jpeg\r\n");
            res.write("Content-Length: " + content.length + "\r\n");
            res.write("\r\n");
            res.write(content, 'binary');
            res.write("\r\n");

            // Start next in stream
            setTimeout(send_next, 42);
        });

        // If we're at the end, reset current stream.
        if (i === files.length) i = 1;
    };

    send_next();
});

// Setup
var port = process.env.PORT || 5000;

server.listen(port, function() {
    console.log('Listening on ' + port);
});

I'm aware there are several optimisations that can done in that code, but it's just for demonstration purposes.
Edit: I'm looking for a solution that can serve 400 frames (~20kb, potentially as base64 encoded strings), that I could then cache on the client, and stream in a continuous loop. Curious if anyone else has solved a similar problem, and how.


text:
Q: Spring Boot and OAuth2 example: redirect not working I'm trying to repeat the "Spring Boot and OAuth2" example from tutorial.
I run the example with "gradlew bootRun".
It is working on Windows without problems, but I having an issue on Ubuntu 14.04.
When I clicked on "login" button the service doesn't perform a redirect to the authorization server (e.g. facebook), and after several minutes return with time-out.
The service's log contains the following lines:
o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /logout
o.s.security.web.FilterChainProxy        : /login at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
uth2ClientAuthenticationProcessingFilter : Request is to process authentication

I would be grateful for any help.
Thanks.
Source code of tutorial located on github
My source code are given below:
build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.security.oauth:spring-security-oauth2")

    compile("org.webjars:webjars-locator")
    compile("org.webjars:angularjs:1.4.3")
    compile("org.webjars:jquery:2.1.1")
    compile("org.webjars:bootstrap:3.2.0")

    testCompile group: 'junit', name: 'junit', version: '4.11'
}

application.yml
security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

logging:
  level:
    org.springframework.security: DEBUG

SocialApplication.java
@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

    @RequestMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and().logout().logoutSuccessUrl("/").permitAll()
                .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    public static void main(String[] args) {
        SpringApplication.run(SocialApplication.class, args);
    }
}

A: The timeout was caused by the secure random call.
The solution for me is the following lines:
bootRun {
    jvmArgs = ["-Djava.security.egd=file:/dev/./urandom"]
}


text:
Q: Prove that an ideal $ \mathfrak{m} $ of a commutative ring $ R $ is maximal iff $ R/\mathfrak{m} $ is simple. Could someone give me a hint on whether I'm on the right track or not? For sufficiency, I tried the following:
Suppose that $ \mathfrak{m} $ is a maximal ideal. With the quotient map, we get $ R/\mathfrak{m} $, where any $ x \in R/\mathfrak{m} $ is of the form $ a + \mathfrak{m} $, with $ a \in R $. Suppose that $ J $ is a non-zero ideal of $ R/\mathfrak{m} $, and let $ y \in J $. As $ J $ is an ideal, we have $ x y \in J $, so $ x y = a y + \mathfrak{m} $. Given that $ a \in R $, $ y \in J $ and $ J \subseteq R $, we get $ y \in R $, so $ a y \in R $. This implies that $ a y + \mathfrak{m} \in R/\mathfrak{m} $. Hence, $ x y \in J $ and $ x y \in R/\mathfrak{m} $, and so $ J \subseteq R/\mathfrak{m} $.
Now, pick any $ a b + \mathfrak{m} \in R/\mathfrak{m} $, where $ b \in J $, with $ J $ an ideal of $ R/\mathfrak{m} $. We know that
$$
a b + \mathfrak{m} = (a + \mathfrak{m}) b \in R/\mathfrak{m},
$$
and as $ b \in J $, we have $ (a + \mathfrak{m}) b \in J $. Hence, $ R/\mathfrak{m} \subseteq J $. We have therefore shown that $ J = R/\mathfrak{m} $ if $ J $ is not the zero ideal.
We thus have only two cases, (i) when $ J $ is not the zero ideal, which we showed implies $ J = R/\mathfrak{m} $, and (ii) when $ J $ is the zero ideal. Therefore, these are the only ideals of $ R/\mathfrak{m} $, and so $ R/\mathfrak{m} $ is simple.
Is this proof on the right path? Also, does anyone have a hint for necessity?

A: If $\mathfrak m$ is maximal, then $R/\mathfrak m$ is a field and hence it is simple.
Conversely, if $R/\mathfrak m$ is simple, then by the Correspondence Theorem, $\mathfrak m$ is maximal.

A: This is wrong because you can't multiply an element of $R/M$ by an element of $J$. They're separate rings. The proof of this I'm familiar with supposes $M$ is maximal and constructs the ideal
$$J=\{m+rx:m\in M,r\in R\}$$
where $x$ is an element such that $x+M\neq M$ (or $x\notin M$). Then this ideal contains $M$ by letting $r=0$, and it contains $x$ by letting $m=0,r=1$. Therefore $M\subset J\implies J=R$. Then we know $1\in J$. So $1=m+rx$ for $m\in M,r\in R$.
I'll let you try to figure out the rest

A: These are all standard results:
$(1)$ Given an $R$-module $N$ and a submodule $N'$, there is a canonical bijection between the collection of submodules of $N''=N/N'$ and the collection of submodules $M$ of $N$ such that $M\supseteq N'$.
$(2)$ A module $S$ is simple if it has precisely two distinct submodules.
$(3)$ Finally, an ideal $\mathfrak m$ is maximal if and only if the only ideals lying over $\mathfrak m$ are $\mathfrak m$ and the unit ideal $R$.


text:
Q: Error creating bean with name 'grailsApplication' Grails v2.3.7
When starting my Grails application I am getting the following error:
Error creating bean with name 'grailsApplication' defined in ServletContext

Stacktrace
Error |
    2014-04-23 13:51:13,856 [localhost-startStop-1] ERROR context.ContextLoader  - Context initialization failed
    Message: Error creating bean with name 'grailsApplication' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsConfigurationException: Class not found loading Grails application: conf.ApplicationResources
        Line | Method
    ->>  262 | run       in java.util.concurrent.FutureTask
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Caused by GrailsConfigurationException: Class not found loading Grails application: conf.ApplicationResources
    ->>  262 | run       in java.util.concurrent.FutureTask
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Caused by ClassNotFoundException: conf.ApplicationResources
    ->>  366 | run       in java.net.URLClassLoader$1
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |    355 | run       in     ''
    |    354 | findClass in java.net.URLClassLoader
    |    425 | loadClass in java.lang.ClassLoader
    |    262 | run . . . in java.util.concurrent.FutureTask
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Error |
    2014-04-23 13:51:14,606 [localhost-startStop-1] ERROR context.GrailsContextLoader  - Error initializing the application: Error creating bean with name 'grailsApplication' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsConfigurationException: Class not found loading Grails application: conf.ApplicationResources
    Message: Error creating bean with name 'grailsApplication' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.codehaus.groovy.grails.exceptions.GrailsConfigurationException: Class not found loading Grails application: conf.ApplicationResources
        Line | Method
    ->>  262 | run       in java.util.concurrent.FutureTask
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Caused by GrailsConfigurationException: Class not found loading Grails application: conf.ApplicationResources
    ->>  262 | run       in java.util.concurrent.FutureTask
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Caused by ClassNotFoundException: conf.ApplicationResources
    ->>  366 | run       in java.net.URLClassLoader$1
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |    355 | run       in     ''
    |    354 | findClass in java.net.URLClassLoader
    |    425 | loadClass in java.lang.ClassLoader
    |    262 | run . . . in java.util.concurrent.FutureTask
    |   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    744 | run       in java.lang.Thread
    Error |
Forked Grails VM exited with error

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="grailsApplication" class="org.codehaus.groovy.grails.commons.GrailsApplicationFactoryBean">
        <description>Grails application factory bean</description>
        <property name="grailsDescriptor" value="/WEB-INF/grails.xml" />
        <property name="grailsResourceLoader" ref="grailsResourceLoader" />
    </bean>

    <bean id="pluginManager" class="org.codehaus.groovy.grails.plugins.GrailsPluginManagerFactoryBean">
        <description>A bean that manages Grails plugins</description>
        <property name="grailsDescriptor" value="/WEB-INF/grails.xml" />
        <property name="application" ref="grailsApplication" />
    </bean>

    <bean id="grailsConfigurator" class="org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator">
        <constructor-arg>
            <ref bean="grailsApplication" />
        </constructor-arg>
        <property name="pluginManager" ref="pluginManager" />
    </bean>

    <bean id="grailsResourceLoader" class="org.codehaus.groovy.grails.commons.GrailsResourceLoaderFactoryBean" />

    <bean id="characterEncodingFilter" class="org.springframework.web.filter.CharacterEncodingFilter">
        <property name="encoding">
            <value>utf-8</value>
        </property>
    </bean>

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" />
</beans>

A: Please , entirely check that you have no spell errors on controller names , package names that you have used inside controllers .

Specially controller.

A: Duplicate with Grails ApplicationContext.xml grailsResourceLoader
https://groups.google.com/forum/#!forum/grails-dev-discuss.
(copy over the applicationContext.xml from the 2.4 distro into your
grails app)

A: I have also found the same exception When i have remove some package directory in my domain class -> Class not found loading Grails application
The reason for the Exception was that wrong package imported in some file.

A: Create a simple Gradle project.
Open build.gradle file.
Make sure that the Gradle, Grails and Groovy plugin versions are compatible between each other.
From the Gradle-Grails plugin Website copy the content of the build.gradle example and paste it to the opened build file inside your IDE.
In the Gradle tool window, click refresh icon to refresh your Gradle project.
The list of Grails tasks are added to the All tasks area in the Gradle Tool Window.
From the All tasks list, run init task.
The task creates a Grails application. The Grails View tool window becomes available and you can start working with Grails.
For more information on working with Grails, see Grails procedures.
https://www.jetbrains.com/idea/help/creating-gradle-project-with-grails-integration.html


text:
Q: Tags in posts link to the wrong site Remove the [organization] tag was moved from here to Meta Stack Overflow. It is about a tag on Stack Overflow that should burninated. When I click on the tag, I am taken to this very site, not Stack Overflow. The same doesn't happen in questions asked on Stack Overflow that didn't get migrated, such as Get rid of move tag?
The tag is organization. The tag reference on this very site takes to Stack Overflow, which is still not the expected behavior, since it should point to tags used on Stack Exchange, which is the main site for this site. If this doesn't make sense because Stack Exchange doesn't use tags, then [tag:organization] should links to tag pages here.
I tried editing the question in question, to see if that would help, but nothing changed.

A: It has been fixed: The tag reference on Meta Stack Overflow takes to Stack Overflow, while here it takes to this very site.


text:
Q: estado cidade JQuery erro na seleção JQuery:
$(function() {
  $(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor );
   });

  $(document).delegate('#cidade', 'change', function() {
    var valor = $('#cidade').val();
    alert(valor);
    $('#bairro').load('_requires/bairros.php?cidade=' + valor );
   });

 });

HTML:

   Estado

   <select class="typeTextMedio" id="estado" name="estado" required>
      <option value="">Escolha o Estado</option>
      <option value="MG">MG</option>
      <option value="ES">ES</option>
      <option value="RJ">RJ</option>
      <option value="SP">SP</option>
   </select>

   Cidade

   <select class="typeTextMedio" id="cidade" name="cidade" required>
      <option value="">Escolha a Cidade</option>
   </select>

   Bairro

   <select class="typeTextMedio" id="bairro" name="bairro" required>
     <option value="#">Indiferente</option>

   </select>

Quando selecionar na combo estados, popular a combo cidades. Isto esta funcionando.
Quando selecionar na combo cidades, popular a combo bairro. Isto NÃO esta funcionando. Mas observei que na combo cidades só ocorre o ERRO com a primeira cidade apenas e quando clico nela, o evento não ocorre. Com as demais normalmente ocorre.
Uma observação importante é que se escolher segunda cidade da combo, e a combo dos bairros é carregada, então voltar e selecionar a primeira cidade novamente, então agora funciona. Na primeira tentativa nem o alert funciona!
Como resolver?

A: O problema está ocorrendo porque voce não esta retornando junto com os resultados das cidades o option Escolha a Cidade. Desta forma a primeira cidade vem por default como selecionada mas sem ativar o change do combo.
Outra forma de resolver o problema é trocar o código javascript combo #Estado para:
$(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor, function() {
       $('#cidade').trigger('change');
   });

 });

Observe que o trigger vai invocar o evento de change no combo de #cidade.


text:
Q: Why some __init__ methods in class inheritance in Python are not called? As I mentioned in the title I wonder why some __init__ methods are not called. Here is my example:
class Type(type):
    def __repr__(cls):
        return cls.__name__

class A(object, metaclass=Type):
    def __init__(self):
        print("A")

class B(A):
    def __init__(self):
        print("B1")
        super().__init__()
        print("B2")

class D(object, metaclass=Type):
    def __init__(self):
        print("D")

class E(B):
    def __init__(self):
        print("E1")
        super().__init__()
        print("E2")

class F(D, E):
    def __init__(self):
        print("F1")
        super().__init__()
        print("F2")

print(F.mro())
F()

which returns the order in which methods should be inherited (mro()) and actual results:
[F, D, E, B, A, <class 'object'>]
F1
D
F2

Why the actual results are different from:
F1
D1
E1
B1
A
B2
E2
D2
F2

as the MRO would suggest?
I know the answer half way, that is, the lack of __init__ in A's class definition breaks this chain, but why?


text:
Q: Type class constraint with multiple variables I have a hard time to grasp the following type class constraint of a Monad Reader function, that receive multiple variables,
local :: MonadReader r m => (r -> r) -> m a -> m a

How to correctly understand the type class constraint? which one is the type constructor, r or m or both? (from the m a part it suggests the type constructor is m).
Compared with for example the bind function, where the type class constraint admitted only single parameter;
(>>=) :: Monad m => m a -> (a -> m b) -> m b

Unlike the local function above, it's obvious and easy to comprehend that the type class constraint for the bind function demand type constructor m to be a Monad instance.

A: In those cases it's best to look at the class (MonadReader) here.
There you'll find this:
class Monad m => MonadReader r m | m -> r where

and quite a bit more.
So here m is some monad and r will be the thing you read from (MonadReader is a so called monad-transformer ... well ok not quite - it's the class that is common to all those transformers - ReaderT is the transformer ... but that's really horrible to explain ... sorry)
local is used to change the thing you read from (I like to think of it as the configuration or the environment) - the r->r part - giving you a computation in the monad m that will do this change.
And if you read on in the documentation there is even an example of how to use this:
calculateContentLen :: Reader String Int
calculateContentLen = do
    content <- ask
    return (length content);

-- Calls calculateContentLen after adding a prefix to the Reader content.
calculateModifiedContentLen :: Reader String Int
calculateModifiedContentLen = local ("Prefix " ++) calculateContentLen

main = do
    let s = "12345";
    let modifiedLen = runReader calculateModifiedContentLen s
    let len = runReader calculateContentLen s
    putStrLn $ "Modified 's' length: " ++ (show modifiedLen)
    putStrLn $ "Original 's' length: " ++ (show len)

as you can see local is used here to add "Prefix " in front of the string
please note that the monad m in this example is not IO - it's Identity (basically nothing - it has no effect)

(I hope it's ok to copy and paste it ... if not please let me know or remove it)