text:
Q: Wordpress when sending a WP_Ajax_Response the response is not received I'm searching for days now for a solution to my problem.
When I send a WP_Ajax_Response the clientside is not receiving it.
I checked all possible tips on internet but still I can't get it working.
Can somebody help me?
I registered the javascript file:
wp_register_script('test-ajax-js',get_template_directory_uri() . '/library/script/ajax.test.js', array( 'jquery', 'wp-ajax-response' ), '1.0' );
wp_enqueue_script( 'test-ajax-js');
wp_localize_script( 'test-ajax-js', 'ajaxtest',
                    array(
                        'Ajax_Url' => admin_url( 'admin-ajax.php' ),
                        'deshopNonce' => wp_create_nonce( 'deshop-ajax-test-nonce' )
                    )
            );

This is the PHP code:
add_action('wp_ajax_shop_ajax_test', 'test_function');
add_action('wp_ajax_nopriv_shop_ajax_test', 'test_function');

function test_function() {
check_ajax_referer( 'deshop-ajax-test-nonce' );

$response = array( 'what'=>'validate_user_login',
            'action'=>'validate_user_login_results',
            'id'=>'1',
            'data'=>'OK'
            );

$xmlResponse = new WP_Ajax_Response($response);
$xmlResponse->send();

exit();
}

and this is the javascript file:
jQuery(document).ready(function(event) {
var post = {
                action: 'shop_ajax_test',
                _ajax_nonce: ajaxtest.deshopNonce
            };

jQuery.post( ajaxtest.Ajax_Url, post, function(response){
                var res = wpAjax.parseAjaxResponse(response, 'ajax-response');
                jQuery.each( res.responses, function() {
                    var a = 0;
                });
            });

});

While debugging the res content shows responses=[0]. In the jQuery.each function no responses are handled!
Thanks a lot for any tips that might help me out here!
Marc

A: I got the same problem but I solved it by using jQuery.ajax() not post()
here's a link that might

A: Is it at all possible that the domain, subdomain, or protocol are different?  That will kill an Ajax response as the browser won't send it.
Also, have you used Firefox's firebug or Chrome's inspector, as apparently they will show you the request and the response (or perhaps why it didn't get there)?


text:
Q: How do I repeat a set of values across all entries in a dataframe? I apologize if this question has been asked but I don't know how to properly ask it and thus find the answer.
I have a dataframe:
val1 val2
val1 val3
val2 val1
val2 val3
I want to append a set of years to every entry:
val1 val2 1990
val1 val2 1991
val1 val2 1992
val1 val3 1990
val1 val3 1991
val1 val3 1992
etc....
I figured out how to do this with only one column of values, but I have since added another column and cannot figure out how to replicate the process. There must be an easy way to do this, but I cannot figure it out, nor can I find an answer on this. How can I do this?

A: You can use a cross join in Pandas.
>>> df1 = pd.DataFrame({
     'col1': ['val1', 'val1', 'val2', 'val2'],
     'col2': ['val2', 'val3', 'val1', 'val3']
})
>>> df1
   col1  col2
0  val1  val2
1  val1  val3
2  val2  val1
3  val2  val3
>>> df2 = pd.DataFrame({'col3': [1990, 1991, 1992]})
>>> df2
   col3
0  1990
1  1991
2  1992
>>> pd.merge(df1, df2, how='cross')
    col1  col2  col3
0   val1  val2  1990
1   val1  val2  1991
2   val1  val2  1992
3   val1  val3  1990
4   val1  val3  1991
5   val1  val3  1992
6   val2  val1  1990
7   val2  val1  1991
8   val2  val1  1992
9   val2  val3  1990
10  val2  val3  1991
11  val2  val3  1992

A: One way would be to assign the list to each row and then explode:
df["Year"] = [[1990, 1991, 1992]]*df.shape[0]
df = df.explode("Year")

>>> df
      A     B  Year
0  val1  val2  1990
0  val1  val2  1991
0  val1  val2  1992
1  val1  val3  1990
1  val1  val3  1991
1  val1  val3  1992
2  val2  val1  1990
2  val2  val1  1991
2  val2  val1  1992
3  val2  val3  1990
3  val2  val3  1991
3  val2  val3  1992

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript: getElementsByTagName returns empty nodeList I'm trying the following code on the main gmail page:
var iFrame = document.getElementById('canvas_frame');

var innerDoc = (iFrame.contentDocument) ? iFrame.contentDocument : iFrame.contentWindow.document;

var tag = innerDoc.getElementsByClassName('vI8oZc cS');

tag always comes up as an empty nodeList.  I'm checking this in the debugger and I can see one of the first divs is of this class type "vI8oZc cS".  How can I get the node element and not an empty list?

A: The browser security policies don't allow such actions if the source of the iframe isn't on the same site the parent page on.


text:
Q: Use a #define VALUE with a template i cannot pass defined values to a template. Even a simple calculation doesnt work:
    #define IR_TIMEOUT 564*173/2
    return decodeSpace<IR_TIMEOUT>(
    duration);

    return decodeSpace<564*173/2>(
    duration);

Working:
    return decodeSpace<48786>(
    duration);

The definition:
    template <uint16_t irTimeout>
    bool decodeSpace(unsigned long duration){}

The error:

E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp: In member function 'virtual bool IRLprotocolNEC::decodeIR(long unsigned int)':
  E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp:46:11: error: no matching function for call to 'IRLprotocolNEC::decodeSpace(long unsigned int&)'
     duration);
             ^
  E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp:46:11: note: candidate is:
  In file included from E:\Arduino\sketchbook\libraries\IRLremote/IRLprotocolNEC.h:27:0,
                   from E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp:24:
  E:\Arduino\sketchbook\libraries\IRLremote/CIRLremote.h:103:9: note: template bool CIRLprotocol::decodeSpace(long unsigned int)
      bool decodeSpace(unsigned long duration){
           ^
  E:\Arduino\sketchbook\libraries\IRLremote/CIRLremote.h:103:9: note:   template argument deduction/substitution failed:
  E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp:46:11: error: overflow in constant expression [-fpermissive]
     duration);
             ^
  E:\Arduino\sketchbook\libraries\IRLremote\IRLprotocolNEC.cpp:46:11: note: in template argument for type 'unsigned int'

Is this a bug or a feature? Or better: How can i avoid/solve things like this?
I want to create different different decoding functions with the same structure but different timings. Passing the values takes a lot of flash so i better copy the function over and over. Thatswhy i wanted to use templates.

A: The problem is that 564*173 overflow uint16.
Use a define or a direct expression is the same thing when it comes for constant folding.
Constant folding is the fact that the compiler "expand" your expression. For example, replace "2*3" with "6".

A: The problem was that i needed to declare the calculation itself as long:
define IR_TIMEOUT 564UL*173/2
Thx @  Matt McNabb


text:
Q: Declare the nativeptr type I'd like to know if it's possible in F# to declare the type:
nativeptr<unit>

This seems not possible (compiler complains with "A generic construct requires that the type 'unit' is an unmanaged type"). Is there a workaround I could use?
The ultimate goal is to declare my own blitDelegate for exposing the opcode Cpblk to some of my F# code.
Thanks.
Edit:
Here's what I've tried based on kvb's answer:
type blitDelegate<'T when 'T : unmanaged> = delegate of nativeptr<'T> * nativeptr<'T> * uint32 -> unit

let createBlitDelegate<'T when 'T : unmanaged>() =
    let dm = new DynamicMethod("blit",
                               typeof<System.Void>,
                               [| typeof<nativeptr<'T>>; typeof<nativeptr<'T>>; typeof<uint32> |])
    let ilGenerator = dm.GetILGenerator()
    ilGenerator.Emit(OpCodes.Ldarg_0)
    ilGenerator.Emit(OpCodes.Ldarg_1)
    ilGenerator.Emit(OpCodes.Ldarg_2)
    ilGenerator.Emit(OpCodes.Cpblk)
    ilGenerator.Emit(OpCodes.Ret)
    dm.CreateDelegate(typeof<blitDelegate<'T>>) :?> blitDelegate<'T>

let blit (blitDel:blitDelegate<'T>) dst src byteWidth = blitDel.Invoke(dst, src, byteWidth)

Then I call this code from a class member like that:
let dst = //get nativeint destination address
let src = //get nativeint source address

let bd = createBlitDelegate<'T>()

let tdst = NativePtr.ofNativeInt<'T> dst
let tsrc = NativePtr.ofNativeInt<'T> src

do blit bd tdst tsrc (uint32 size)
//Program.MemCpy.Invoke(dst.ToPointer(), dst.ToPointer(), uint32 size)

This results in a runtime error at blit (System.Security.VerificationException: Operation could destabilize the runtime.)
The commented code works well (and can be found here) but my point was to code it in F# (not C#).
The reason why I wanted to use at first a nativeptr<unit> is that it is actually the type of the two first arguments of MemCpy delegate (that matches void* type) and somewhat wanted to mimic it.
Edit2:
Based on kvb's edit, I modified my code to host the delegate creation in a type using static members (like the C# version) and it now works.
I don't use the version with the unmanaged constraint but this one, since I actually need to blit array of structs:
type blitDelegate = delegate of nativeint * nativeint * uint32 -> unit

A: From your description, it's not clear to me why you'd like a nativeptr<unit>.  Essentially, nativeptr<'t> is just a thin wrapper over nativeint with some helpers for doing arithmetic on the pointer.  Since you're unlikely to have an array of units, I don't see how this actually helps you, though.  Perhaps if you show more of your code it will be easier to give a more satisfactory answer.
EDIT
I think you're doing almost everything right.  However, anonymously hosted DynamicMethods must be verifiable, and the cpblk opcode is never verifiable.  Try using a different constructor for DynamicMethod to host it on a type or module.


text:
Q: Passing a Javascript Variable to Android Activity? Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it there.
     /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface {

        @SuppressWarnings("unused")
        public void setX(String html){
            Activity.this.x = html;
            Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
        }

    }

this works but I want to be able to call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...
Any tips?

A: You can not access stored javascript variables, you must do it through a function call.
You have to call it from javascript in your html page, for example:
TheNameOfYourInterface.setX('value');

TheNameOfYourInterface will be a javascript object when you add the interface to the webview via
YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");

so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.

A: I found a different solution to what I need, and I feel like it works for all who do not need get a value calc'd by javascript. My solution to my need was to HTTP GET the html/javascript and then parse it as a string. It saves me some time by not needing to load X WebViews and then (re)creating all my functions in the JavaScript Interface.

A: I think it will be a good idea to store the HTML in Shared Preferences ,which is a form of persistent storage.This way you will be able to access it from anywhere.
   //------get sharedPreferences

SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

//--------modify the value

pref.edit().putString("ToastString", html).commit();

//-------get a value from this from anywhere

String toastValue=pref.getString("ToastString", "");


text:
Q: When do you do a health check? So, I have an application here that posts requests to another service via REST API calls. I have to implement a health check within my application that ensures that the other service is up. I'm a software noob here and my question is this:
When do I ping the other service to check if they're up? During my application startup (this is just going to be a one time thing) or when I initialize the client which makes the REST API calls to the other service?

A: This is like the classic I/O mistake where you test if a file exists before opening it for writing. By the time you attempt to open it, it may not exist anymore.
You test services when you use services. Not before. Testing before use, say to warn the user that the fields they're about to fill out might be lost is dumb.  The services are free to go up or down between test and use.  It's far better to hold the fields locally an attempt to use again.
Of course you're free to let the user test as they like but don't force this into their workflow. It's completely pointless.

A: I'm not completely agree with above answers.. I'll take the example of the readiness probe concept of Kubernetes.
The idea is that we want to avoid routing requests to the pod until it is ready to accept traffic.
However, the readiness probe will continue to be called throughout the lifetime of the container, every periodSeconds, so that the container can make itself temporarily unavailable when one of its dependencies is unavailable
If you service (deployed in a container) is not capable of handle the traffic (for instance because the database is down and it is a critical dependency) it is useless to send requests to it because it will result in timeout (and so potential blocked thread), cascading failures and lot of stacktraces in console and log files..
It is exactly like the concept of circuit breakers.. If a service can handle your requests just don't call it. Fail-Fast is better than let users waiting for 5 seconds for finally send him an internal error response..
So yes all of these things applies during all the lifetime of the service but I think these should be applied too during start-up.

A: Don't do that. Seriously. Concurrent distributed systems are hard, and this is why. Testing before use ("health checks") simply builds a race condition into your system design since you can't guarantee availability anyway. The API endpoint can always fall over between test and use.
Consider that from the client's perspective there's no difference between failure because the endpoint is down and failure due to network transients. Non-availability is non-availability -- why doesn't matter to the client. Your best bet is to do something sane with the error, whether that's back off and retry, log and fail, or something else.
And while you're learning, the ACM's digital library (http://dl.acm.org) is open for all until 30 Jun. There's a solid book on Leslie Lamport's contributions to distributed computing and concurrency you can grab for free -- highly recommended.


text:
Q: If else evaluation Suppose I have the following statement:
    bool foo=true;
    if (foo){
            foo=false;
    }
    else{
             //do stuff
    }

Will it enter the else condition, or is the if evaluated once discarding  the else immediately?

A: else won't evaluate because the condition's executed only once.
When you say foo=true foo is checked, then the code in one of the conditions is executed. If foo is true, then foo=false is done and execution stops.

A: if is a split. Depending on the value of the expression, either the "if" or the "else" part of the code is evaluated, but not both, and that's all about it.
In your example, because the value of foo is true, the "if" branch runs (setting foo to false) and the "else" branch is ignored.

A: The if statement does not provide a way to fall through to the else part if the condition evaluates to true.
If you need such a feature, you can use switch:
bool foo = true;
switch (foo) {
case true:
    foo = false;
    // FALL THROUGH
default:
    //...
}


text:
Q: Replacing empty values with nulls in JavaScript string Given the following string:
var str = "[,,,1,2,,,3,4,,,,,,5,6]";
I want to replace all "empty" values with nulls. In other words, I want this result:
"[null,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6]"
This almost works, but it misses the first empty value:
var str = "[,,,1,2,,,3,4,,,,,,5,6]";
str.split(',').map(function(x) { return x ? x : 'null' }).join(',')
// Gives [,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6]

Likewise, I noticed if I have trailing empty values, it misses the last one there too:
var str = "[,,,1,2,,,3,4,,,,,,5,6,,]";
str.split(',').map(function(x) { return x ? x : 'null' }).join(',')
// Gives [,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6,null,]

Any ideas how I can make sure that first and last empty values are also replaced?
Thanks!

A: this is going to work:

  var str = "[,,,1,2,,,3,4,,,,,,5,6]";
  var result = '[' + str.replace(/^\[|\]$/g, '').split(/[,]/).map(function(x) { return x ? x : 'null' }).join(',') + ']';
  console.log(result);

A: The secret is that your brackets are getting combined with your commas / numbers at the start and end of the string when it is split. In order to resolve this, you need to remove the brackets before splitting.
This can be done with .replace() on /[\][]/g:

var str = "[,,,1,2,,,3,4,,,,,,5,6,]";
console.log(
  str.replace(/[\][]/g, '').split(',').map(function(x) {
    return x ? x : 'null'
  }).join(',')
);

A:

var str = "[,,,1,2,,,3,4,,,,,,5,6]";
var a = `[${str.slice(1, -1).split(",").map(n => n || "null")}]`

console.log(a);

A: As mentioned - the [ and ] are altering your return - this removes them and using the same function as your existing function - but on the shortened string  and returns the correct value.

var str = "[,,,1,2,,,3,4,,,,,,5,6]";
let newStr = str.substring(1,str.length-1).split(',').map(function(x) { return x ? x : 'null' }).join(',')

console.log(newStr);
// Gives [null,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6]

var str = "[,,,1,2,,,3,4,,,,,,5,6,,]";

newStr = str.substring(1,str.length-1).split(',').map(function(x) { return x ? x : 'null' }).join(',');
console.log(newStr);
// Gives null,null,null,1,2,null,null,3,4,null,null,null,null,null,5,6,null,null

A: You have removed all the empty values. "[" and "]" are not nothing.

A:

String.prototype.repEmptyWithNull =
function() {return this
  .replace(/,,/g, ',null,')
  .replace(/,,/g, ',null,')
  .replace('[,', '[null,')
  .replace(',]', ',null]')
}

console.log ("[,,,1,2,,,3,4,,,,,,5,6,]".repEmptyWithNull())
console.log ("[,,1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())
console.log ("[,1,2,,,3,4,,,,,,5,6,,]".repEmptyWithNull())
console.log ("[,1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())
console.log ("[1,2,,,3,4,,,,,,5,6,]".repEmptyWithNull())
console.log ("[1,2,,,3,4,,,,,,5,6]".repEmptyWithNull())


text:
Q: Extract time in getSymbols I want to extract the time for some stock market to fit tree model. For example these codes are for loading Nikkei Market data:
library(quantmod)
library(zoo)
symbols=c('^N225')
getSymbols(symbols,src='yahoo', from="2003-04-28", to="2007-10-29")

After that, I want to extract the time that the market is work (we could see the time in the first left column of the market data after we write N225). when we save these data with csv format the time column is replaced with ID number.
Someone say that use the zoo format and after I save the data with these code:
N<-data.frame(N225)
Ndata<-read.zoo(N)

the warning has appeared as follow:
In zoo(rval, index(x)[i]) :
some methods for "zoo" objects do not work if the index entries in 'order.by' are not unique

and when we write Ndata the time column is replaced with some number that is not the time. how can I extract the time?

A: I can't get your code to run, but this will get the same info. from the St. Louis Fed:
library(quantmod)
library(zoo)
symbols=c('NIKKEI225')
getSymbols(symbols,src='FRED')

df <- as.data.frame(NIKKEI225)
df <- cbind(date=as.Date(rownames(df)),df)
write.csv(df,file="Ndata.csv, row.names=F)

The problem is that getSymbols(...) returns a timeseries object, where the times are implicit. So when you save you just get the "time index", rather than a data-time variable. The code above makes the times explicit by putting them in a column of the dataframe, and explicitly setting them to class Date.
As @GSee points out in the comment below, this is another, better way:
df <- data.frame(date=index(NIKKEI225),NIKKEI225)
write.csv(df,file="Ndata.csv, row.names=F)

A: Looks like getSymbols might be giving you trouble. I don't have a API key for Yahoo so I had to manually download the file and I did not have any trouble.
library(quantmod)
symbols=c('^N225')
getSymbols(symbols,src='yahoo', from="2003-04-28", to="2007-10-29")
#this returned an error so I had to manually read in the CSV file
N225 <- read.csv("table.csv")
Ndata <- read.zoo(N225)
head(Ndata)
           Open High  Low Close Volume Adj.Close
2003-04-28 7679 7685 7604  7608  46000      7608
2003-04-30 7695 7831 7695  7831  63200      7831
2003-05-01 7804 7896 7746  7863  55800      7863
2003-05-02 7863 7907 7792  7907  53400      7907
2003-05-06 7995 8133 7995  8084  61400      8084
2003-05-07 8127 8156 8062  8110  57600      8110


text:
Q: How can I call a translation with the translation key being a variable? I would like to display a translation where the current item in an iteration is the translation key.
In my model I have :
def self.topics
    [ "topic_birds", "topic_trees"  ]
end

In my view :
Book.topics.each do |topic|
    ...

<%= t(topic) %>

    ...
end

And in my YML file
topic_birds: 'Birds'
topic_trees: 'Trees'

Instead of returning :
Birds
Trees

My code returns :
Topic Birds
Topic Trees

So it seems the translation function does not accept or interpret the variable topic properly in my each statement. Instead it returns a formatted version of the key (uppercase first letter and spaces) and not the translation from the YML file.

A: When the specified key cannot be found in your language yml file, the default behavior of Rails translation helper is to use the specified key as the value. This appears to be what you are experiencing.
If you inspect the HTML output of your view, you will see the "translated" value is wrapped in an element with a special translation_missing class and title, e.g.:
Topic Birds

Tip: You can cause missing translations to raise an error by setting ActionView::Base.raise_on_missing_translations = true.

Based on the information you provided, I'm guessing the language yml file is structured properly, so the likely issue is that the topic_birds and topic_trees keys are defined in a different locale than what is set in the app.
For example, if you have an en.yml file that looks like this:
en:
  topic_birds: 'Birds'
  topic_trees: 'Trees'

...but the app's locale is set to de, then you will experience the issue you're describing.
You can set the locale with I18n.locale = :en.


text:
Q: Split Attributed String and Retain Formatting How can you take an existing NSAttributedString and divide it based on a predefined separator while maintaining formatting? It does not seem that componentsSeparatedByString will operate on an NSAttributedString.
My current workaround produces the splits at the correct points, but only outputs an NSString. Thus losing formatting.
NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
// Wish I could do this
// NSArray *separatedArray = [rtfFileAttributedString componentsSeparatedByString:importSeparatorPref];
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];
NSLog( @"Separated array: %@", separatedArray );

A: In Swift 4, I made the function.
func splitAttributedString(inputString: NSAttributedString, seperateBy: String) -> [NSAttributedString] {
    let input = inputString.string
    let separatedInput = input.components(separatedBy: seperateBy)
    var output = [NSAttributedString]()
    var start = 0
    for sub in separatedInput {
        let range = NSMakeRange(start, sub.utf16.count)
        let attribStr = inputString.attributedSubstring(from: range)
        output.append(attribStr)
        start += range.length + seperateBy.count
    }
    return output
}

A: Here is an NSAttributedString extension that works in a similar fashion to some of the other examples here.
private extension NSAttributedString {
    func components(separatedBy separator: String) -> [NSAttributedString] {
        var result = [NSAttributedString]()
        let separatedStrings = string.components(separatedBy: separator)
        var range = NSRange(location: 0, length: 0)
        for string in separatedStrings {
            range.length = string.utf16.count
            let attributedString = attributedSubstring(from: range)
            result.append(attributedString)
            range.location += range.length + separator.utf16.count
        }
        return result
    }
}

A: You can make use of your split non-attributed string to split up the attributed string. One option would be:
NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];

NSMutableArray *separatedAttributedArray = [NSMutableArray arrayWithCapacity:separatedArray.count];
NSInteger start = 0;
for (NSString *sub in separatedArray) {
    NSRange range = NSMakeRange(start, sub.length);
    NSAttributedString *str = [rtfFileAttributedString attributedSubstringFromRange:range];
    [separatedAttributedArray addObject:str];
    start += range.length + importSeparator.length;
}

NSLog(@"Separated attributed array: ", separatedAttributedArray);

A: In swift the answer is simple.
var string = NSAttributedString(
    string: "This string is shorter than it should be for this questions answer.",
    attributes: [.font: UIFont.systemFont(ofSize: 12)]
)
let range = NSRange(location: 0, length: 120)
let newString = string.attributedSubstring(from: range)
print(newString)


text:
Q: python 3.7 dict (insertion ordered) equivalent in c++ There are several questions regarding the c++ equivalents to pythons dict.
Since python 3.7, however, python dictionaries preserves insertion order.
All previous answers give std::map or std::unordered_map as the answer,
but they do not provide this property. std::map orders by key values but not in order of insertion.
I know that the key values in python can also have different types, but that's not what this question is about. For this question i would restrict that there is only one key type.
So what would be the equivalent to a dict that preserves the insertion order in c++?
Can something like this be assembled from standard library containers? No matter which c++ standard.

A: C++ standard library doesn't have a linked hash table container out of the box.
This kind of container introduces additional memory overhead to save insertion order, which is not needed in most of common scenarios.
This behavior doesn't satisfy a common C++ concept: "don't pay for something you don't use".
At the same time, if you still need to save insertions order you can trivially combine std::list - doubly linked list and unordered_map - hash table in a single class.
For example:
#include <iostream>

#include <list>
#include <unordered_map>

template<typename K, typename V, typename H = std::hash<K> >
class linked_hash_map
{
private:
    typedef std::list<V> holder_container_t;
public:
    typedef typename holder_container_t::iterator iterator;
    typedef typename holder_container_t::const_iterator const_iterator;
private:
    typedef typename std::unordered_map<K, iterator> access_container_t;
public:
    linked_hash_map():
        holder_(),
        index_()
    {}

    std::pair<iterator, bool> insert( const std::pair<K,V>& entry)
    {
        holder_.push_back( entry.second );
        auto idx_insert = index_.insert( std::make_pair(entry.first, --holder_.end() ) );
        if(!idx_insert.second) {
            holder_.pop_back();
            return std::make_pair(holder_.end(),false);
        }
        else {
            return std::make_pair(--holder_.end(),true);
        }
    }

    iterator erase(const K& key)
    {
        auto ret = index_.find(key);
        if(ret == index_.end()) {
            return end();
        }
        index_.erase(ret);
        return holder_.erase( ret->second );
    }

    bool contains(const K& k) const
    {
        return index_.contains(k);
    }

    iterator find(const K& key)
    {
        auto ret = index_.find(key);
        return  ( ret == index_.end() ) ? end() : ret->second;
    }

    const_iterator find(const K& key) const
    {
        auto idx = index_.find(key);
        return idx == index_.cend() ? cend() : *idx;
    }

    iterator begin()
    {
        return holder_.begin();
    }

    iterator end()
    {
        return holder_.end();
    }

    const_iterator cbegin() const
    {
        return holder_.cbegin();
    }

    const_iterator cend() const
    {
        return holder_.cend();
    }

private:
    holder_container_t holder_;
    access_container_t index_;
};

int main()
{

    linked_hash_map<std::string, std::size_t> lhm;

    // fill a map in a reverse order
    for(int i=10; i >= 0 ; i--) {
        auto key = std::string("Test") + std::to_string(i);
        lhm.insert( std::make_pair( key, i ) );
    }

    //  look up for elements
    auto sret = lhm.find("Test5");
    if( lhm.end() != sret )
        std::cout << "Test5 = " << *sret << std::endl;

    sret = lhm.find("Test7");
    if( lhm.end() != sret )
        std::cout << "Test7 = " << *sret << std::endl;

    lhm.erase("Test5");
    sret = lhm.find("Test5");
    if( lhm.end() != sret )
        std::cout << "Test5 = " << *sret << std::endl;
    else
        std::cout << "Test5 not found" << std::endl;

    // Iterate over the map by values in their insert order
    for(auto it: lhm) {
        std::cout<< it << ' ';
    }

    return 0;
}


text:
Q: Passing client data to server-side methods I have a JavaScript file that checks for bids using json data.
Now the problem I have is the plugin for the countdown has an onExpiry function that won't let you pass parameters, when u do the callback is called before the counter expires. On expiry of the countdown, it should set auction to Won, alert the user and add them to winners table. Most of this is handled by php, but the function I have made requires the auction_id and the username to be passed, but without passing parameters I cant think of how to do this. Here is the code I have at present.
Is Won PHP Function:
 function isWon($user, $auction){
        $this->load->model('Auction_model', 'Auction');
        $this->load->model('Bid_model', 'Bid');
        $this->load->model('Customer_model', 'Customer');

        $makeWon = $this->Auction->isWon($auction);
        $customer = $this->Customer->getByUsername($user);

        if ($makeWon){
            $json = array(
                'success' => 'Congratulations '.$user.' You have won.',
            );
        }

        echo json_encode($json);

    }

Common.Js
function checkBids(){

    var id = $('div.auction').attr('id');
    $.ajax({
        url: 'http://localhost/tinybid/index.php/auction/auctiondata',
        dataType: 'json',
        success: function(json) {
            for (var i = 0; i < json.length; i++) {

                $('#auction'+json[i]['i']+' li.user').html(json[i]['u']);
                $('#auction'+json[i]['i']+' li.curPrice').html(json[i]['p']);
                if (typeof json[i]['t'] =='number'){
                    $('#auction'+json[i]['i']+' li.timer').countdown({until: startTimer(json[i]['i'],json[i]['t']), onExpiry: isWon});
                }
            }
        }

    });
}
function startTimer(auction, stamp){
    var time= new Date();
    time.setTime(stamp*1000);
    $('#auction'+auction+' li.timer').countdown('change', {until: time});

}

function isWon(user, auction){
    if (user){
        $.ajax({
            url: 'http://localhost/tinybid/index.php/auction/isWon/'+user+'/'+auction,
            dataType: 'json',
            success: function(json) {
                if (json['success']){
                    alert(json['success'])
                }
            }

        });
    }
}

Here is the Json returned on the checkBids() function
[{"i":"5","t":1324374080,"p":"£ 0.13","u":"chrissy"}]

Is this the best way to create this countdown, or is the a better, cleaner way?
If this is the best way how can I get the functions to all work lol :)

A: You don't need the "onExpiry" to let you pass parameters.
First - you can alway to the function
onExpiry : function(){  isWon(user, auction); }

Thus effectively passing the arguments in the annonymous function implementation.
But what I usually do is simply add a hidden input fields
<input id="user_id" type="hidden"/>
<input id="auction_id" type="hidden"/>

and in the "isWon" function - instead of getting "user" and "auction" as parameters simply do the following
var user_id = $("#user_id").val();
var auction_id =  $("#auction_id").val();

And then pass it in ajax to server, or directly pass it in ajax like so
 $.ajax({
            url: 'http://localhost/tinybid/index.php/auction/isWon/'+user+'/'+auction,
            dataType: 'json',
            data:{user_id:$("#user_id").val(), auction_id:$("#auction_id").val()},
            success: function(json) {
                if (json['success']){
                    alert(json['success'])
                }
            }

By the way - please note that the "URL" is weird in your example. Should start with "/" and not contain "index.php" in the middle. If I could have your file hierarchy I can resolve this too.


text:
Q: ASP.NET MVC4 Bundling with Twitter Bootstrap I'm trying to use the new bundling feature in MVC 4 with Twitter bootstrap and it seems to me like the paths to the glyphicons png-files int the css get's messed up in some way. Heres my code:
 bundles.Add(new StyleBundle("~/bundles/publiccss").Include(
            "~/Static/Css/bootstrap/bootstrap.css",
            "~/Static/Css/bootstrap/bootstrap-padding-top.css",
            "~/Static/Css/bootstrap/bootstrap-responsive.css",
            "~/Static/Css/bootstrap/docs.css"));

        bundles.Add(new ScriptBundle("~/bundles/publicjs").Include(
            "~/Static/Js/jquery-1.7.2.js",
            "~/Static/Js/bootstrap/bootstrap.js",
            "~/Static/Js/cookie/jquery.cookie.js"));

I'm not seeing any icons on buttons and likewise. Am I doing something wrong here? Any suggestions?

A: What you can do is you can go to the customize page and change @iconSpritePath and @iconWhiteSpritePath in the Sprites section and, of course, download the new style.
I've put my images in the folder Content/Images folder and I've changed the path in:

*

*/Content/Images/glyphicons-halflings.png

*/Content/Images/glyphicons-halflings-white.png
Another alternative is to download all the LESS files from github, change the same variables in the variables.less file and recompile the bootrap.less file with a tool like SimpLESS.

A: The issue is most likely that the icons/images in the css files are using relative paths, so if your bundle doesn't live in the same app relative path as your unbundled css files, they become broken links.
We have rebasing urls in css on our todo list, but for now, the easist thing to do is to have your bundle path look like the css directory so the relative urls just work, i.e:
new StyleBundle("~/Static/Css/bootstrap/bundle")

Update: We have added support for this in the 1.1beta1 release, so to automatically rewrite the image urls, you can add a new ItemTransform which does this rebasing automatically.
bundles.Add(new StyleBundle("~/bundles/publiccss").Include(
            "~/Static/Css/bootstrap/bootstrap.css",
            "~/Static/Css/bootstrap/bootstrap-padding-top.css",
            "~/Static/Css/bootstrap/bootstrap-responsive.css",
            "~/Static/Css/bootstrap/docs.css", new CssRewriteUrlTransform()));

A: The 'CssRewriteUrlTransform' works just fine for applications that DON'T run on top of a virtual directory.
So, if your app runs on http://your-site.com/ it runs just fine, but if it runs on http://your-site.com/your-app/ you'll have 404 for all your images because the default 'CssFixRewriteUrlTransform' is referencing your images with a '/'.
To solve this issue, I have implemented my own version of 'CssRewriteUrlTransform' like this:
    public class CssFixRewriteUrlTransform : IItemTransform {
    private static string ConvertUrlsToAbsolute(string baseUrl, string content) {
        if (string.IsNullOrWhiteSpace(content)) {
            return content;
        }
        var regex = new Regex("url\\(['\"]?(?<url>[^)]+?)['\"]?\\)");
        return regex.Replace(content, match => string.Concat("url(", RebaseUrlToAbsolute(baseUrl, match.Groups["url"].Value), ")"));
    }

    public string Process(string includedVirtualPath, string input) {
        if (includedVirtualPath == null) {
            throw new ArgumentNullException("includedVirtualPath");
        }
        var directory = VirtualPathUtility.GetDirectory(includedVirtualPath);
        return ConvertUrlsToAbsolute(directory, input);
    }

    private static string RebaseUrlToAbsolute(string baseUrl, string url) {
        if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(baseUrl) || url.StartsWith("/", StringComparison.OrdinalIgnoreCase)) {
            return url;
        }
        if (!baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase)) {
            baseUrl = string.Concat(baseUrl, "/");
        }
        return VirtualPathUtility.ToAbsolute(string.Concat(baseUrl, url));
    }
}

UPDATE: thanks to superjos who pointed out that there was another solution out there:

public class CssRewriteUrlTransformWrapper : IItemTransform
{
    public string Process(string includedVirtualPath, string input)
    {
        return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
    }
}

A: Fix for this now added to my AspNetBundling NuGet package which resolves a bunch of other issues in the standard transformer, particularly around using data-uris. Open-sourced on GitHub too.
Just do:

*

*Install-Package AspNetBundling

*Replace CssRewriteUrlTransform with CssRewriteUrlTransformFixed


text:
Q: Subtract date variables PHP Helllo, I have 2 time variables. One I take from the database and another is the current time.
$time_ended = $row['time_ended'];
$time_ended = new DateTime($time_ended);
$now = new DateTime();

What I want is to subtract $now from $time_ended and echo the number of seconds in a result.
Basically the output should be something like 121 or 134. I need this data to create a countdown timer.
Can someone show me the trick?
Thank you for your time.

A:
PHP > 5.3: http://php.net/datetime.diff
PHP < 5.3: http://php.net/strtotime

Use the diff method:
// PHP > 5.3
$diff = $time_ended->diff( $now );
echo $diff->format( '%s' ); // Seconds, with leading zeros

Or if you are not running PHP > 5.3:
// PHP < 5.3
$diff = ( strtotime( $now ) - strtotime( $time_ended ) ) / 3600;
echo date( 's', $diff ); // Seconds, with leading zeros

A: http://php.net/manual/en/datetime.diff.php
Use the diff method of the DateTime object.
$interval = $time_ended->diff($now);
$diff_seconds = $interval->s; // returns the number of seconds

This will return a DateInterval (http://www.php.net/manual/en/class.dateinterval.php) object. The s property gets the number of seconds of the interval.


text:
Q: troubleshoot failed cloudwatch events This part of cloudformation template creates the event, but do not actually execute it.
  MyCWEventRule:
    Type: AWS::Events::Rule
    Properties:
      Name: my-batch-event-rule
      ScheduleExpression: cron(01 07 ? * * *)
      State: ENABLED
      Targets:
        - Id: my-batch-job
          Arn: !Ref Queue
          BatchParameters:
            JobDefinition: !Ref StartJob
            JobName: tds-job
          RoleArn: !Join [ "", [!Sub "arn:aws:iam::${AWS::AccountId}:role/service-role/", !Ref ruleIAMRole]]

There are no logs to check what the problem is. If I submit the job myself using console, it works as expected.
The Job Definition parameter mentioned in cron is correct as seen in this image...

How do I troubleshoot failed cloudwatch events?

Update:
When I click on Edit and use "Create a new role for this specific resource" it works.
It means there is some problem with the line...

RoleArn: !Join [ "", [!Sub
"arn:aws:iam::${AWS::AccountId}:role/service-role/", !Ref
ruleIAMRole]]

A: You guessed it right! There is no need of "service-role" in the ARN role path. It should look like this...
RoleArn: !Join [ "", [!Sub "arn:aws:iam::${AWS::AccountId}:role/", !Ref ruleIAMRole]]

Or even better:
RoleArn: !GetAtt ruleIAMRole.Arn


text:
Q: I'm using jenkins with 3 slaves, however I'd like to run jenkins pipeline only on 2 of them I tried:
pipeline
  agent {lablel slave1 && slave2}
  agent {lablel 'slave1' && label 'slave2'}

But it won't work. Any help would be appreciated.

A: You can configure a label 'myGoodNodes' in the Nodes configuration.
Then refer to it as:
agent { label 'myGoodNodes' }

A: Your syntax is not exactly right. The quotation marks should be around the whole condition. Also, you want to "Or" the two labels instead of "and".
This should do what you want:
agent { label 'slave1 || slave2' }


text:
Q: exchange the elements in diagonal in Array - C# I'd like to know how to write a program in 2D array to exchange the elements of main diagonal with secondary diagonal then print the result
like this
3 2 7
4 5 3
2 8 9
and the result show like this
7 2 3
4 5 3
9 8 2

A: Actually it's not a very specific problem, but as I don't see the part where you're stuck I'll try to explain a whole example to you:
static int[,] GetDiagonallySwitched(int[,] oldMatrix)
{
    var newMatrix = (int[,])oldMatrix.Clone();

    for (var i = 0; i < oldMatrix.GetLength(0); i++)
    {
        var invertedI = oldMatrix.GetLength(0) - i - 1;
        newMatrix[i, i] = oldMatrix[i, invertedI];
        newMatrix[i, invertedI] = oldMatrix[i, i];
    }
    return newMatrix;
}

First of all I'm cloning the old matrix, because a few values actually remain the same. Then I switch the values from the left side to the right side. I'm doing this with the invertedI, which basically is i from the other side - so that in the end the cross is mirrored and it seems as though the lines switched. This is working for any size of the matrix.
For the printing: If you actually want to print it bold, you'll have to use a RTB in WinForms, but I don't guess this was part of your question. Otherwise you could use this code to print the matrix:
static void Print(int[,] switched)
{
    for (var y = 0; y < switched.GetLength(0); y++)
    {
        for (var x = 0; x < switched.GetLength(1); x++)
            Console.Write(switched[y, x]);
        Console.WriteLine();
    }
}

I hope I could help you.


text:
Q: When a client connects to server do foreach UNET How to make when a client connects to server, that my foreach is working. Because when I put the foreach in Update, it's working great. What's the problem?
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class Net : NetworkManager {

    public GameObject[] _mans;

    void Update()
    {
        _mans = GameObject.FindGameObjectsWithTag ("Player");
        Debug.Log (_mans.Length);
    }

    public override void OnClientConnect(NetworkConnection conn)
    {
        foreach (GameObject man in _mans)
        {
            man.GetComponent<UIManager> ().Play ();
        }
    }

}


text:
Q: Clarification for public key while signing initial transaction I need clarification from API doc reference,
If I am signing transaction based on legal identity key then it works fine.
If I am signing transaction by generating fresh public key and send it to acceptor then it throws exception - The Initiator of CollectSignatureFlow must have signed the transaction
Here as per below doc, we can use public key of legal identity Or can generate public key for signing transaction

A: It sounds like your issue is as follows:

*

*When adding the required signers to the commands, you're using your standard identity

*When signing the transaction, you're using a fresh public key, which doesn't correspond to the identity listed in the commands

*The counterparty can't match your signature with the fresh public key to your standard identity listed as a required signer, and therefore throws a SignaturesMissing exception

Instead of creating a fresh public key manually, you should be use the SwapIdentitiesFlow: https://docs.corda.net/api-identity.html#swapidentitiesflow.


text:
Q: I want to capture comments from java file using python script For documentation purpose, I want to capture the comments of every function which lies above its code.
I am able to iterate the file to their function names. As soon as I get the function name line, I want to capture its comment which is above it.
comment are in '/** xxx */' block
/**
* this is the comment
* this is the comment
* this is the comment
*/
@Attribute(type = Attribute.STRING.class)
String RESPONSE_TEXT = "responseText";

/**
* this is the comment
* this is the comment
*/
@Attribute(type = Attribute.LONG.class)
String TIME = "clTimestamp";

A: this need to work:
data = open(file_name).read()
data = data.split('/**')
old = data
data = list()
for i in old:
    data.extend(old.split('*/'))
comments = []
for i in range(1, len(data), 2):
    comments.append(data[i])
for k in comments:
    print(k)

A: Now when I know function name line starts with @Attribute it is quite easy to get it done using regular expression (re module), which can be done following way:
import re
content = '''
/**
* this is the comment
* this is the comment
* this is the comment
*/
@Attribute(type = Attribute.STRING.class)
String RESPONSE_TEXT = "responseText";

/**
* this is the comment
* this is the comment
*/
@Attribute(type = Attribute.LONG.class)
String TIME = "clTimestamp";
'''
comments = re.findall(r'(/\*\*.*?\*/)\n(@Attribute[^\n]*)',content,re.DOTALL)

print('Function comments:')
for i in comments:
    print(i[1])
    print(i[0])
    print('\n')

Output:
Function comments
@Attribute(type = Attribute.STRING.class)
/**
* this is the comment
* this is the comment
* this is the comment
*/

@Attribute(type = Attribute.LONG.class)
/**
* this is the comment
* this is the comment
*/

For clarity I hardcoded content, I used re.findall with pattern which have two groups, one is for comment, second for name, thus it give list of 2-tuples, each consisting of comment and function name. Note re.DOTALL meaning that .*? might give multiline match and escaping of characters with special meaning, namely * as \*.

A:   x = find_comment(x, "/*", "*/", 2)
  x = find_comment(x, "//", "\n", 0)
  def find_comment(n_array, start_string, end_string, add_index):
     comment_index = n_array.find(start_string)
     if comment_index != -1:
         comment_end_index = n_array.find(end_string, comment_index)
         print(comment_end_index)
         if len(n_array) > comment_end_index:
             print(n_array[comment_index:comment_end_index + add_index])
             n_array = n_array[0: comment_index:] + n_array[comment_end_index + add_index::]
             find_comment(n_array, start_string, end_string, add_index)
             return n_array
      return n_array


text:
Q: Pandas multiply between columns does not work I have the following multiindex jpy_bal dataframe:
                        2019-07-28 00:00:00  2019-07-29 00:00:00     (2019-07-28 00:00:00,)  (2019-07-29 00:00:00,)
app_vendor_id currency
3             1WO                       262                  262              2.418967e+00            2.517868e+00
              ABX                        10                   10              9.226124e-01            1.037273e+00
...                                     ...                  ...                   ...                     ...
29193         BCH                         8                    8              3.372592e+04            3.352354e+04

[129 rows x 4 columns]

I try then to multiply with the following code:
jpy_bal.iloc[:,[0]] = jpy_bal.iloc[:,[0]] * jpy_bal.iloc[:,[3]]

But this give me the following output:
                        2019-07-28 00:00:00  2019-07-29 00:00:00     (2019-07-28 00:00:00,)  (2019-07-29 00:00:00,)
app_vendor_id currency
3             1WO                       Nan                  262              2.418967e+00            2.517868e+00
              ABX                       Nan                   10              9.226124e-01            1.037273e+00
...                                     ...                  ...                   ...                     ...
29193         BCH                       Nan                    8              3.372592e+04            3.352354e+04

[129 rows x 4 columns]

I have Nan instead of the result. Would you know why this could happen? Any contribution is appreciated.

A: You are not multiplying two series but you are multiplying two dataframes because you call iloc[:, [0]] instead of .iloc[:, 0]. This will use the column index AS WELL AS the row index and not find a match.
try
jpy_bal.iloc[:, 0] * jpy_bal.iloc[:, 3]
Example
df = pd.DataFrame([[1,2,3],[4,5,6]])

# 2 dataframes with same index, works as expected.
df.iloc[:, [0]] * df.iloc[:, [0]]

# 2 dataframes with different index, yields a 2x2 matrix with NaN's
df.iloc[:, [0]] * df.iloc[:, [1]]

Result
    0   1
0 NaN NaN
1 NaN NaN

Corrected code
df.iloc[:, 0] * df.iloc[:, 1]


text:
Q: issue with converting auto-py-to-exe with tkinter SystemExit: pre-safe-import-module hook failed I'm getting an issue when I convert Tkinter code to exe  my libraries are follows
import tkinter as tk
from tkinter import simpledialog
from selenium import webdriver
import webdriver_manager.chrome
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
# from fake_useragent import UserAgent
import time
import argparse
from selenium.webdriver.common.proxy import Proxy, ProxyType
from numpy import random
from time import sleep
from selenium.common.exceptions import NoSuchElementException
import os

from selenium.webdriver.chrome.options import Options

and I'm getting this error and I removed some lines in the log file.

Provided command: pyinstaller --noconfirm --onedir --console --icon "D:/fiver/amazone/Danleech-Simple-Amazon.ico"  "D:/fiver/amazone/guit/onlyui.py"

#removed some logs

    submodule = self._safe_import_module(head, mname, submodule)
  File "c:\programdata\anaconda3\lib\site-packages\PyInstaller\depend\analysis.py", line 431, in _safe_import_module
    hook_module.pre_safe_import_module(hook_api)
  File "c:\programdata\anaconda3\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-setuptools.extern.six.moves.py", line 40, in pre_safe_import_module
    raise SystemExit("pre-safe-import-module hook failed, needs fixing.")
SystemExit: pre-safe-import-module hook failed, needs fixing.

Project output will not be moved to output folder
Complete.


text:
Q: REACT - Composition of a component with subcomponents in TypeScript react-bootstrap let you create a modal component with:
<Modal>
    <Modal.Header>
        <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>

Text in a modal

    </Modal.Body>
    <Modal.Footer>
        <Button>Close</Button>
    </Modal.Footer>
</Modal>

I want to do a composition of the modal component and create a MyModal component:
import * as React from 'react';
import { Modal, ModalBody, ModalProps } from 'react-bootstrap';

interface Props extends ModalProps {
  plain?: boolean;
}

class MyModal extends React.Component<Props> {

  static Body: typeof ModalBody;

  constructor(props: Props) {
    super(props);
  }

  render() {
    const { plain, ...other } = this.props;
    return (
      <Modal className={plain ? 'plain' : ''} {...other} />
    );
  }
}

export default MyModal;

but if I use it like this:
import MyModal from './MyModal';

...

render() {
  return (
    <MyModal plain={true}>
      <MyModal.Body>

Hello!

      </MyModal.Body>
    </MyModal>
  );
}

I get the following error:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Any idea what's going wrong?

A: static Body: typeof ModalBody;

is undefined, so it cannot be used as <MyModal.Body>.
In case it's inherited from wrapped component, it should be:
static Body = ModalBody;

Where Body type is inferred.
This problem could be avoided by using TypeScript strict (strictNullChecks) compiler option.


text:
Q: Script to check if files in $HOME are owned by $USER and -if not- change them Need to create a script at startup that checks if files in $HOME are owned by $USER and -if not- change them.
Would start with
find $HOME ! -user $USER
and later
chown -R $USER:$USER $HOME
but can't write it properly to be started automatically as a service at startup in Debian.

A: This should work.You will probably need to run as sudo.
find $HOME ! -user $USER -exec chown -R $USER:$USER {} \;

To execute a command with find you can use -exec with the command you want to run.
The filename/directory found is inserted into statement as {}. And when using -exec you have to include a semicolon at the end.

If you execute this from a shell script and use sudo be sure to use $SUDO_USER and /home/$SUDO_USER since $USER evaluates to root when running a shell script using sudo


text:
Q: WordPress добавление в метаданные пост тайпа Только осваиваю WordPress, есть кастомный пост тайп.
function setup_custom_post_type() {
    $args = array(
        'thumbnail',
        'public'    => true,
        'label'     => __( 'Listing', 'textdomain' ),
        'menu_icon' => 'dashicons-format-aside',
        'rewrite' => array('slug' => 'listing'),
    );
}

add_action( 'init', 'setup_custom_post_type' );

Хочу добавить поле в метаданные поста, в котором будет время добавления, но моя функция не работает.
function save_custom_post_tye(){
    add_post_meta( get_the_ID(), 'date_cr', date("Y-m-d H:i:s") );
}

add_action( 'wp_insert_post', 'save_custom_post_tye', 10, 3);

Что нужно поменять/добавить?

A: Функция get_the_ID() работает только в главном цикле WordPress. Вам нужно использовать аргументы, которые передаются в хук.
/**
 * Save custom post meta at creation.
 *
 * @param int     $post_id Post ID.
 * @param WP_Post $post    Post object.
 * @param bool    $update  Whether this is an existing post being updated or not.
 */
function save_custom_post_type( $post_id, $post, $update ) {
    add_post_meta( $post_id, 'date_cr', date( 'Y-m-d H:i:s' ) );
}

add_action( 'wp_insert_post', 'save_custom_post_type', 10, 3 );


text:
Q: Reference for Wiener's formula in the context of Fourier Could anyone point me to an easily available reference for Wiener's formula used in the following answer ?
fourier transform of radon measure
I tried the most obvious sources without success.

A: It is a formula usually attributed to Parseval:
http://en.wikipedia.org/wiki/Parsevals_theorem

A: You can find a proof of this in
W. F. Eberlein, "A note on Fourier-Stiltjes Transforms", Proceedings of the AMS, Vol 6, No 2, April 1955, pp 310-312.
I think the result is older than this paper.


text:
Q: How to add a String to duplicate element in Array in Powershell I have following array:
$array = 'A', 'B', 'C', 'A'

I want to identify the duplicate and add to the duplicate a string, for example, $string='Part 2'
so that I have
$array = 'A', 'B', 'C', 'A Part 2'

How do I do this in PowerShell?

A: Use a hashtable to keep track of strings you've already seen, then loop through all items in the array - if we've already seen the same, modify the item, otherwise leave it as is:
$array = 'A','B','C','A'

# Create hashtable to keep track of strings we've already encountered
$stringsSeen = @{}

# Now iterate over the array
$modifiedArray = $array |ForEach-Object {
  if(!$stringsSeen.ContainsKey($_)){
    # First encounter, add to hashtable
    $stringsSeen[$_] = 1
  }
  else {
    # We've seen it before! Time to update value and modify `$_`
    $number = ++$stringsSeen[$_]
    $_ += " Part $number"
  }

  # finally output `$_`, regardless of whether we modified it or not
  $_
}

$modifiedArray now holds the new array of (partially) modified strings:
PS ~> $modifiedArray
A
B
C
A Part 2

A: Mathias R. Jessen's helpful answer shows an effective, readable solution.
The following solution streamlines the approach to make it more concise (though thereby potentially more obscure) and more efficient:

*

*The .ForEach() array method is used to process the input array, as a faster alternative to the ForEach-Object cmdlet. (A foreach statement would be even faster, but is a bit more verbose).

*It relies on the (non-obvious) fact that ++ applied to a non-existent hashtable entry implicitly creates the entry with value 1.
$array = 'A', 'B', 'C', 'A'

$ht = @{}
$newArray = $array.ForEach(
  { if (($count = ++$ht[$_]) -eq 1) { $_ } else { "$_ Part $count" } }
)

Note: $newArray is technically not an array, but of type [System.Collections.ObjectModel.Collection[psobject]], but that usually won't make a difference.
In PowerShell (Core) 7+ an even more concise solution is possible, using ?:, the ternary conditional operator:
$array = 'A', 'B', 'C', 'A'

$ht = @{}
$newArray = $array.ForEach({ ($count = ++$ht[$_]) -eq 1 ? $_ : "$_ Part $count" })


text:
Q: Join table data duplicate in Mysql I have created two tables busbook and seats. When I join two tables data duplicated I don't why.
SELECT seats.busno,
       seats.seats,
       busbook.status,
       busbook.customer,
       busbook.mobile,
       seats.date
FROM seats
     Left JOIN busbook ON  seats.busno=busbook.busno

This is an output I got:
busno  seats     status     customer         mobile    date
91000     1       Booked     ss              11      2019-12-06
91000     2       Booked     ss              11      2019-12-06
91000     3       Booked     ss              11      2019-12-06
91000     4       Booked     ss              11      2019-12-06
91000     5       Booked     ss              11      2019-12-06
91000     6       Booked     ss              11      2019-12-06
91000     7       Booked     ss              11      2019-12-06
91000     8       Booked     ss              11      2019-12-06
91000     9       Booked     ss              11      2019-12-06
91000    10       Booked     ss              11      2019-12-06

seats table:
id    busno   seats       date
1     91000    1      2019-12-06
2     91000    2      2019-12-06
3     91000    3      2019-12-06
4     91000    4      2019-12-06
5     91000    5      2019-12-06
6     91000    6      2019-12-06
7    91000     7      2019-12-06
8    91000     8      2019-12-06
9    91000     9      2019-12-06
10   91000    10      2019-12-06
11   91000     11     2019-12-06
12   91000     12     2019-12-06

busbook table:
id  busno   seat     status       customer       mobile        date
2   91000    1       Booked          ss            11          2019-12-06
3   91000    19      Booked          dd            22          2019-12-06

A: How about
SELECT seats.busno, seats.seats,busbook.status, busbook.customer,busbook.mobile,seats.date FROM seats
Left JOIN busbook ON seats.busno=busbook.busno
AND seats.seats = busbook.seat

I guess it depends on what exactly scheme is to do join by seats.id or seats.seats

A: You can use the below query to get require result:
SELECT seats.busno,
       seats.seats,
       busbook.status,
       busbook.customer,
       busbook.mobile,
       seats.date
FROM seats
 JOIN busbook ON seats.busno = busbook.busno AND seats.seats = busbook.seat

A: SELECT s.busno, s.seats, s.status,
       b.customer, b.mobile, s.date
FROM seats s
INNER JOIN busbook b ON s.busno=b.busno AND s.seats = b.seats
The requirements are not very clear from your question, and your question is at risk of being downvoted.
But in the interest of solving your problem. This is the query you most probably need.
You have used the LEFT JOIN keyword
But the The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
What you want to use is The INNER JOIN keyword selects records that have matching values in both tables.
Also your query has multiple mistakes at the join ON condition. I have rectified it, Hope this solves your problem.


text:
Q: Setting a dev and prod build with AWS credentials in Xcode? I have a dev and prod cognito pool, a dev/prod lambda function that pushes to a dev/prod dynamoDb table.
Is there a simple way to have it know when to use the prod credentials (pool id, etc), and when to use the dev credentials?
And same to do with firing the appropriate dev/prod API gateway apis that check the appropriate pools for authentication, and post to the appropriate dynamoDb tables? For now I just manually change the tokens, and in API Gateway, I manually switch out which cognito pool the API gateway authenticates and which tables they post to, which isn't very practical.

A: If you expose your lambda with API Gateway then just deploy it to two stages - a prod stage which calls the prod lambda which accesses prod Dynamodb & a dev stage which calls dev lambda. In your application, you would just need to change the stage name & you can do so by setting it from Info.plist.
Regarding how to get tokens for prod or dev automatically, it depends on how you get these tokens. For example, you could create a /login resource in API Gateway which takes username + password as parameters and returns tokens. Again, deploy it to two stages which use different Cognito pool in the backend calls. Now, you can use the same variable/property in your application to get the stage name for getting tokens too.
So, by just changing the value of one property you can switch between prod & dev in your app.


text:
Q: Split file using shell based on column value I have a table which has 2 columns - Person Number and Value. I need to split file with chunk size 12. (Each file having 12 rows)
Input Table
100 aewvc
100 bsv
100 fsv
100 r3r
100 sac
100 fwe
100 cre
100 cr3
100 vrev
101 dvs
101 we
101 rever
101 fwcw
101 fcw
101 fwcw
101 fwe
102 rever
103 fwcw
103 fcw
103 fwcw
103 fwe

If I use rank function in oracle sql , I can split it in 2 files but person 101 will get splitted in 2 files. I want all rows of a person in single file (First or second doesn't matter).
I have billions of records with multiple columns so Oracle SQL Approach is taking too much time. Any solution using shell script where basic split can be done using sql and later with shell we can make sure to distribute 101 in file1 or file2?
Current output from SQL
File 1
100 aewvc
100 bsv
100 fsv
100 r3r
100 sac
100 fwe
100 cre
100 cr3
100 vrev
101 dvs

File 2
101 we
101 rever
101 fwcw
101 fcw
101 fwcw
101 fwe
102 rever
103 fwcw
103 fcw
103 fwcw
103 fwe

Desired Output from shell
File 1
100 aewvc
100 bsv
100 fsv
100 r3r
100 sac
100 fwe
100 cre
100 cr3
100 vrev
101 dvs
101 we
101 rever
101 fwcw
101 fcw
101 fwcw
101 fwe

File 2
102 rever
103 fwcw
103 fcw
103 fwcw
103 fwe

Thanks in advance!!!
Bhushan


text:
Q: Give first 16 and 3935 and output is not responding is gives me number not binary #include <stdio.h>
#include <math.h>

long long convertToBinary(int dnumber);

int main() {

    int width;
    int dnumber;
    printf("Enter Width(int bits): ");
    scanf("%d",&width);
    printf("\nEnter Decimal NUmber: ");
    scanf("%d",&dnumber);

    if(width==8)
    {
        if(dnumber<=255 && dnumber>0)
        {
            printf("\nOutput - U2B(%d) = %lld",dnumber,convertToBinary(dnumber));
        }else{
            printf("You entered bigger than 8 bits");
        }
    }else if(width==16){

        if(dnumber<=65535 && dnumber>255){
           printf("\nOutput - U2B(%d) = %lld",dnumber,convertToBinary(dnumber));
        }else{
            printf("You entered lower or bigger number than 16 bits");
        }
    }
    return 0;
}

long long convertToBinary(int dnumber){

    long long binaryNumber = 0;
    int remaindr, i = 1;

    while (dnumber!=0)
    {
        remaindr = dnumber%2;
        //printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", i++, dnumber, remaindr, dnumber/2);
        dnumber /= 2;
        binaryNumber += remaindr*i;
        i *= 10;
    }
    return binaryNumber;
}

*

*When i give 8 and 255 it gives me binary

*When i give 16 and 3935 it gives me decimal

Why it must give me binary number?

A: i overflows in convertToBinary
Change the type to long long:
long long i = 1;


text:
Q: Como puedo hacer que me aparezcan seleccionados los checkbox que guarde en mi base en esta parte los muestro

Lista de permisos

                        @foreach( $permissions as $permission)

                                    {{Form::checkbox('permissions[]',$permission->id,null)}}
                                    {{$permission->name}}
                                    ({{$permission->description ?:'Sin descripcion'}})

                        @endforeach

este es mi controlador
public function update(Request $request, Role $role)
    {
//        actualizar usuario
        $role->update($request->all());

//        actualizar roles
        $role->permissions()->sync($request->get('roles'));

        return redirect()->route('roles.edit',$role->id)
            ->with('info','Rol actualizado con exito');
    }

A: puedes hacerlo asi:
siempre y cuando tu propiedad se llame checked o algo referente

Lista de permisos

        @foreach( $permissions as $permission)

                    <input id="{{ $permission->id }}" name="permissions[]" type="checkbox" value="{{ $permission->id }}"
                    @if($permissions->checked)
                        checked=checked
                    @endif
                    >{{$permission->name}}
                    ({{$permission->description ?:'Sin descripcion'}})

        @endforeach


text:
Q: Critical error detected c0000374 while freeing the loaded dll by FreeLibrary I have met a memory error when I try to free an user-defined DLL. If you do not want to know the background of this problem, I recommend you to read my problem from the beginning of the section 2. user-defined DLL.
Background
In my program, I need to use a third-party library. In the following part I call it LIB-A / DLL-A. The abstract process of this library could be descripted by using 4 functions:
initResources(): initialze the configuration.
callAPI_to_saveAsFile(...): main process.
freeMem(...): free memory of returned data.
destroyResources(): free memory of the configuration.

The used LIB-A has referred ice34d.dll, and iceutil34d.dll. By adding the lib and included files in my project (I call this program exe-A), I have found these functions could work well.
But now I have to use another method to refer the DLL-A. In other words, I have to use LoadLibrary, GetProcAddress and FreeLibrary to complete this task. Since I have found that the DLL-A does not provide any avaliable interface of the above functions, I try to remove DLL-A from the folder containing exe-A. The result shows that DLL-A is not a valid file, exe-A could work well without it.
User-defined DLL
Because the DLL-A is invalid, I have to write a user-defined DLL to wrap the above 4 functions, I call this program DLL-B. DLL-B has be linked with such libs:
iced.lib
iceutild.lib
LIB-A

Although DLL-A is invalid, LIB-A is necessary, because I infer that the above 4 founctions are not only declared but also defined in LIB-A, and DLL-A is actually empty. After setting the libs and included files, I write 4 wrapping functions. Here are the main part of .h file and .cpp file.
.h file: (some parameters are omitted)
#include "LIBA.h"
#ifdef MYLIBDLL
    #define CM_EXTERN extern "C" _declspec(dllimport)
#else
    #define CM_EXTERN extern "C" _declspec(dllexport)
#endif

CM_EXTERN int w_initResources();
CM_EXTERN int w_callAPI_to_saveAsFile(...);
CM_EXTERN int w_destroyResources();
CM_EXTERN int w_freeMem(...);

.cpp file:
#include "stdafx.h"
#pragma comment (lib, "../music-lib/release_dll/iced.lib")
#pragma comment (lib, "../music-lib/release_dll/iceutild.lib")
#pragma comment (lib, "../music-lib/release_dll/DLLA.lib")

int w_initResources(){
    return initResources();
}

int w_destroyResources(){
    return destroyResources();
}

int w_freeMem(...){
    return freeMem(...);
}

int w_callAPI_to_saveAsFile(...){
    return callAPI_to_saveAsFile(...);
}

char* w_callAPI_to_downFileByte(char* fileURL,char *ret_bytes){
    return callAPI_to_downFileByte(fileURL, ret_bytes);
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Problem
After all, I begin to write a test program (I call it exe-B). In this program, I use such codes to load DLL-B:
.h file:
typedef int (*callAPI_to_saveAsFile_ptr)(...);
typedef int (*initResources_ptr)();
typedef int (*destroyResources_ptr)();
typedef int (*freeMem_ptr)(...);

.cpp file:
callAPI_to_saveAsFile_ptr Proc_API = NULL;
initResources_ptr init_API = NULL;
destroyResources_ptr destru_API = NULL;
freeMem_ptr free_API = NULL;

HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
    Proc_API = (callAPI_to_saveAsFile_ptr)GetProcAddress(h, "w_callAPI_to_saveAsFile");
    init_API = (initResources_ptr)GetProcAddress(h, "w_initResources");
    destru_API = (destroyResources_ptr)GetProcAddress(h, "w_destroyResources");
    free_API = (freeMem_ptr)GetProcAddress(h, "w_freeMem");
    cout << "Have loaded: " << "DLLB.dll" << " successfully!" << endl;
}
else{
    cout << "Do not find this DLL:" << "DLLB.dll" << endl;
    FreeLibrary(h);
    return 0x100;
}
int errorflag=0;
if (Proc_API==NULL){
    cout << "Function not loaded: callAPI_to_saveAsFile" << endl;
    errorflag = errorflag | 0x001;
}
if (init_API==NULL){
    cout << "Function not loaded: initResources" << endl;
    errorflag = errorflag | 0x002;
}
if (destru_API==NULL){
    cout << "Function not loaded: destroyResources" << endl;
    errorflag = errorflag | 0x004;
}
if (CMISS_free_API==NULL){
    cout << "Function not loaded: freeMem" << endl;
    errorflag = errorflag | 0x008;
}
if (errorflag!=0){
    FreeLibrary(h);
    return 0x100 | errorflag;
}
cout << "Function loaded successfully!" << endl;
...Perform above functions...
if(h)
    FreeLibrary(h);
    return 0;

It is confusing that even the program could be compiled well, GetLastError() returns 0, and all of the 4 founctions are performed well. However, once I let the program free the DLL instance, I would receive such an error:
Critical error detected c0000374
exeB.exe has triggered a breakpoint.

If I do not free the library, there will be no error in this program.
To prove my guess, I have done another 2 experiments:
Exp1
I write a DLL(DLL-C) to wrap another library (LIB-D) designed by myself. And I load DLL-C by similiar method in the section. Problem. The result shows that DLL-C could be freed without error. The only difference between DLL-C and DLL-B is that DLL-B load the third-party libs(ice, LIB-A), and DLL-C load a simple library (LIB-D) designed by myself. It seems that this error is triggered by the third-party libs. Unfortunately, I could not see the detail of these external libs.
Exp2
I change the .cpp file as follow:
HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
    cout << "H_Valid!" << endl;
    FreeLibrary(h);
    cout << "Have loaded: " << "DLLB.dll" << " successfully and free it!" << endl;
    return 0;
}
else{
    cout << "Do not find this DLL:" << "DLLB.dll" << endl;
    FreeLibrary(h);
    return 0x100;
}

It is appalling that although I do nothing with the loaded DLL-B, once I load it, I could not free it safely. The error is the same as above error in section. Problem.
Critical error detected c0000374
exeB.exe has triggered a breakpoint.

How could I solve this problem? Whether does it mean that I could not free the library but use it normally?


text:
Q: Unable to Put ViewPager inside a ScrollVIew/NestedScrollView I have a ViewPager which resides inside a parent Linear Layout and below the ViewPager there are some buttons. The ViewPager was working great until recently I changed the parent from LinearLayout to a ScrollView. Now the ViewPager disappeared. Please don't mark it as spam or duplicate.
Also, there are tons of apps on Playstore currently using this. See this app - link
What I Tried:

*

*setFillViewport (true) - This didn't work for me.

*Set layout_height to 0dp

*Use a CustomScrollView

All these doesn't help me. I am running the app on Android M.
This is my layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".activities.HomeActivity">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:onClick="pagerClick"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="top"
android:layout_weight="1"
android:overScrollMode="never"/>

<RelativeLayout
android:layout_weight="0.8"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
.....two buttons
</RelativeLayout>

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

Question:
How can I achieve this? Also, is there an official way of doing it?

A: I solved the issue by fixing the height of my ViewPager like :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".activities.HomeActivity">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:onClick="pagerClick"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="top"/>

...

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

A: Better use a recyclerView and add Viewpager as its child inside the adapter. You need to intercept the touch of recyclerview to give the scroll to ViewPager.
public class TouchInterceptRecyclerView extends RecyclerView {

    private boolean interceptTouch = true;
    private static final int MIN_DISTANCE = 200;
    private float downX = 0, downY = 0, moveX = 0, moveY = 0, upX = 0, upY;

    public TouchInterceptRecyclerView(Context context) {
        super(context);
    }

    public TouchInterceptRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (getRvTop() == 0) {
            onTouchEvent(ev);
        }
        return interceptTouch;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = event.getX();
                moveY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                upX = event.getX();
                upY = event.getY();
                break;
        }
        float deltaX = upX - downX;

        if (getViewTop() == 0 && moveY > downY && Math.abs(moveY - downY) > MIN_DISTANCE) {  // moving down
            interceptTouch = true;
        }else if (Math.abs(deltaX) > MIN_DISTANCE) {
            if (upX > downX) {    // Left to Right swipe action
                interceptTouch = false;
            }else {    // Right to left swipe action
                interceptTouch = false;
            }
        } else {  // screen tap
            interceptTouch = false;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public void onScrolled(int dx, int dy) {
        if (getViewTop() <= 0) {
            interceptTouch = false;            // dispatch the touch to child when reached top
        } else {
            interceptTouch = true;           // do not dispatch the touch event
        }
        super.onScrolled(dx, dy);
    }

    public int getViewTop() {
        int top = 0;
        View v = this.getChildAt(1);
        if (v == null) {
            v = this.getChildAt(0);
        }
        if (v != null && v instanceof LinearLayout) {
            top = v.getTop();
        }
        return top;
    }

    public int getRvTop() {
        int top = -1;
        View v = this.getChildAt(1);
        if (v == null) {
            v = this.getChildAt(0);
        }
        if (v != null && v instanceof LinearLayout) {

            ViewPager vp = (ViewPager) v.findViewById(R.id.single_pager);
            if (vp != null) {
                int currentPos = vp.getCurrentItem();
                RecyclerView rv = (RecyclerView) vp.findViewWithTag("recyclerview" + currentPos);
                if (rv != null) {
                    View v1 = rv.getChildAt(0);
                    if (v1 != null && v1 instanceof CardView) {
                        top = v1.getTop() - ResourceUtils.getDimensionPixelOffset(R.dimen.padding_20);   // deducting 20 as we have give top margin as 20 to the top layout
                    }
                }
            }
        }
        return top;
    }
}

Inside the adapter for RecyclerView you can add ViewPager like this :
@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        View view;
        switch (viewType) {
            case TYPE_VIEW_PAGER:
                view = LayoutInflater.from(context).inflate(R.layout.pager, parent, false);
                viewHolder = new ViewPagerAdapter(context, view);
                break;
        }
        return viewHolder;
    }


text:
Q: Get error in AlertDialog I have a simple app, and when I tap the Exit to show an AlertDialog, the app crashes.
Code:
final ImageView Exit = (ImageView) findViewById(R.id.imageView3);
Exit.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        mp.pause();
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                getBaseContext());

        // set title
        alertDialogBuilder.setTitle("Do you want to Exit?...");

        // Setting Icon to Dialog
        alertDialogBuilder.setIcon(R.drawable.exit2);

        // set dialog message
        alertDialogBuilder
                .setMessage("")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            // do something when the button is clicked
                            public void onClick(DialogInterface arg0,
                                    int arg1) {
                                finish();
                                // close();
                            }
                        })
                .setNeutralButton("Rate us!",
                        new DialogInterface.OnClickListener() {

                            // do something when the button is clicked
                            public void onClick(DialogInterface arg0,
                                    int arg1) {
                                {
                                    Uri uri = Uri
                                            .parse("market://details?id="
                                                    + getPackageName());
                                    Intent goToMarket = new Intent(
                                            Intent.ACTION_VIEW, uri);
                                    try {
                                        startActivity(goToMarket);
                                    } catch (ActivityNotFoundException e) {
                                        Toast.makeText(
                                                getApplicationContext(),
                                                "Couldn´t launch Google Play",
                                                Toast.LENGTH_LONG)
                                                .show();
                                    }
                                }
                            }
                        })
                .setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
});

LogCat:
03-13 01:13:00.084: I/Choreographer(918): Skipped 57 frames!  The application may be doing too much work on its main thread.
03-13 01:13:12.114: D/AndroidRuntime(918): Shutting down VM
03-13 01:13:12.124: W/dalvikvm(918): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-13 01:13:12.145: E/AndroidRuntime(918): FATAL EXCEPTION: main
03-13 01:13:12.145: E/AndroidRuntime(918): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:563)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:269)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.app.Dialog.show(Dialog.java:281)
03-13 01:13:12.145: E/AndroidRuntime(918):  at rain.dreams.MainActivity$3.onClick(MainActivity.java:116)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.view.View.performClick(View.java:4240)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.view.View$PerformClick.run(View.java:17721)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.os.Handler.handleCallback(Handler.java:730)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.os.Looper.loop(Looper.java:137)
03-13 01:13:12.145: E/AndroidRuntime(918):  at android.app.ActivityThread.main(ActivityThread.java:5103)
03-13 01:13:12.145: E/AndroidRuntime(918):  at java.lang.reflect.Method.invokeNative(Native Method)
03-13 01:13:12.145: E/AndroidRuntime(918):  at java.lang.reflect.Method.invoke(Method.java:525)
03-13 01:13:12.145: E/AndroidRuntime(918):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-13 01:13:12.145: E/AndroidRuntime(918):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-13 01:13:12.145: E/AndroidRuntime(918):  at dalvik.system.NativeStart.main(Native Method)
03-13 01:13:14.864: I/Process(918): Sending signal. PID: 918 SIG: 9

A: Probably  getBaseContext() causing issue so use current Activity context for creating Alert as:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                                        MainActivity.this);


text:
Q: Erro ao importar imagem: Allowed memory size Estou usando um script simples para recortar a imagem, ao recortar algumas imagens ele dá esse erro:

Allowed memory size of 268435456 bytes exhausted (tried to allocate
  155648 bytes)  in /home/site/public_html/admin/controller/foto.php on
  line 65

O estranho é que a imagem tem só 65kb, alguém sabe o que pode ser? Tem como eu gerar um log mais detalhado?
abaixo o script e a linha 65 comentada:
//RECORTAR E IMPORTAR AS FOTOS NO FTP ****************************************
foreach($_FILES as $key => $ft){
    if($ft['tmp_name']!=''){
        $pastafoto = $root.'imagens/usuarios/';
        $photo_url = $ft['tmp_name'];
        list($width, $height, $type, $attr) = getimagesize($photo_url);
        $nomearquivo=$ft['name'];
        if($key=='foto'){
            $proporcao=1;
            $tamanho='150';
        }elseif($key=='capa'){
            $tamanho='1060';
            $proporcao=6.057142857142857;
        }

        if(!is_dir($pastafoto.$usuario['id'])){
            mkdir($pastafoto.$usuario['id'], 0755);
        }
        $dest = $pastafoto.$usuario['id'].'/' . $nomearquivo;
        $source_image = $photo_url;
        $nome=$nomearquivo;
        $destination = $pastafoto.$usuario['id'].'/'.$local.'/'.$nome;
        $tn_w = $tamanho;
        $tn_h = ($tamanho * $proporcao);
        $quality = 80;
        $wmsource = '';
        $success = image_handler($source_image,$destination,$tn_w,$tn_h,$quality,$wmsource);
        $sql = "UPDATE ptp_usuarios SET {$key}='{$nome}' WHERE id = {$usuario['id']}";
        $result = $db->prepare( $sql );
        $result->execute();
    }
}
//FUNÇÃO COPIA FOTO
function image_handler($source_image,$destination,$tn_w = 100,$tn_h = 100,$quality = 100,$wmsource = false) {
    $info = getimagesize($source_image);
    $imgtype = image_type_to_mime_type($info[2]);
    switch ($imgtype) {
        case 'image/jpeg':
        $source = imagecreatefromjpeg($source_image);
        break;
        case 'image/gif':
        $source = imagecreatefromgif($source_image);
        break;
        case 'image/png':
        $source = imagecreatefrompng($source_image);
        break;
        default:
        die('Invalid image type.');
    }
    $src_w = imagesx($source);
    $src_h = imagesy($source);
    $src_ratio = $src_w/$src_h;
    if ($tn_w/$tn_h > $src_ratio) {
        $new_h = $tn_w/$src_ratio;
        $new_w = $tn_w;
    } else {
        $new_w = $tn_h*$src_ratio;
        $new_h = $tn_h;
    }
    $x_mid = $new_w/2;
    $y_mid = $new_h/2;

    // Now actually apply the crop and resize!

//ESSA LINHA ABAIXO É A QUE FALA QUE DEU ERRO! ***********************************************

    $newpic = imagecreatetruecolor(round($new_w), round($new_h));
    imagecopyresampled($newpic, $source, 0, 0, 0, 0, $new_w, $new_h, $src_w, $src_h);
    $final = imagecreatetruecolor($tn_w, $tn_h);
    imagecopyresampled($final, $newpic, 0, 0, ($x_mid-($tn_w/2)), ($y_mid-($tn_h/2)), $tn_w, $tn_h, $tn_w, $tn_h);
                    // If a watermark source file is specified, get the information about the watermark as well. This is the same thing we did above for the source image.
    if($wmsource) {
        $info = getimagesize($wmsource);
        $imgtype = image_type_to_mime_type($info[2]);
        switch ($imgtype) {
            case 'image/jpeg':
            $watermark = imagecreatefromjpeg($wmsource);
            break;
            case 'image/gif':
            $watermark = imagecreatefromgif($wmsource);
            break;
            case 'image/png':
            $watermark = imagecreatefrompng($wmsource);
            break;
            default:
            die('Invalid watermark type.');
        }
        // Determine the size of the watermark, because we're going to specify the placement from the top left corner of the watermark image, so the width and height of the watermark matter.
        $wm_w = imagesx($watermark);
        $wm_h = imagesy($watermark);
                        // Now, figure out the values to place the watermark in the bottom right hand corner. You could set one or both of the variables to "0" to watermark the opposite corners, or do your own math to put it somewhere else.
                        //$wm_x = $tn_w - $wm_w;
                        //$wm_y = $tn_h - $wm_h;
        $wm_x = ($tn_w / 2) - ($wm_w / 2);
        $wm_y = ($tn_h / 2) - ($wm_h / 2);
                        // Copy the watermark onto the original image
                        // The last 4 arguments just mean to copy the entire watermark
        imagecopy($final, $watermark, $wm_x, $wm_y, 0, 0, $tn_w, $tn_h);
    }
                    // Ok, save the output as a jpeg, to the specified destination path at the desired quality.
                    // You could use imagepng or imagegif here if you wanted to output those file types instead.
    if(Imagejpeg($final,$destination,$quality)) {
    return true;
    }
                    // If something went wrong
    return false;
}

A: Bom dia, você pode verificar o seu php.ini a diretiva memory_limit altere para algo em torno de 1024M ou mais.
Alguns retornos referente a limite de memória:
PHP: Fatal Error: Allowed Memory Size of 8388608 Bytes Exhausted - 8 MB
PHP: Fatal Error: Allowed Memory Size of 16777216 Bytes Exhausted - 16 MB
PHP: Fatal Error: Allowed Memory Size of 33554432 Bytes Exhausted - 32 MB
PHP: Fatal Error: Allowed Memory Size of 67108864 Bytes Exhausted - 64 MB
PHP: Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted - 128 MB
PHP: Fatal Error: Allowed Memory Size of 268435456 Bytes Exhausted - 256 MB
PHP: Fatal Error: Allowed Memory Size of 536870912 Bytes Exhausted - 512 MB
PHP: Fatal Error: Allowed Memory Size of 1073741824 Bytes Exhausted - 1 GB

Como pode ver a sua está em 256MB.
Você também pode verificar essas outras diretivas que também são referente a upload de arquivos (mas a primeira solução acima já resolve seu problema):
upload_max_filesize
file_uploads
upload_max_filesize
max_file_uploads
post_max_size
max_input_time

Lembrando que após realizar esta alteração no seu php.ini seu apache deve ser reiniciado para que funcione.
Caso queira colocar a solução em seu arquivo use o código abaixo. Mas indico alterar o php.ini.
<?php
    ini_set('memory_limit', '1024M'); // no caso usando 1G

Espero ter ajudado


text:
Q: Join and subselects I need to rid my iSeries DB2 query of subselects. In the query below, I need to get ALADD1 and ALADD2 (address 1 and 2) from F0116 matched on both ABAN8 and MAPA8 into one record. ABAN8 is the shipping address ID and MAPA8 is the billing address ID. F0116 holds the values for these address IDs.
Current query:
SELECT T1.ABAN8,T2.MAPA8,T3.ALADD1,T3.ALADD2,
(SELECT ALADD1 FROM F0116 WHERE MAPA8 = ALAN8) AS ALADD101,
(SELECT ALADD2 FROM F0116 WHERE MAPA8 = ALAN8) AS ALADD201
FROM F0101 T1
LEFT JOIN F0150 T2 ON ABAN8 = MAAN8
LEFT JOIN F0116 T3 ON ABAN8 = ALAN8

The result looks like this:
ABAN8,  MAPA8,  ALADD1,             ALADD2,     ALADD101,           ALADD201,
100,    200,    555 SHIPPING STR,   SUITE B,    555 BILLING STR,    SUITE C,
101,    201,    556 SHIPPING STR,   SUITE B,    556 BILLING STR,    SUITE C,
102,    202,    557 SHIPPING STR,   SUITE B,    557 BILLING STR,    SUITE C

But this is a very simplified example. There are actually six address fields, so efficiency is horrible. How can I accomplish this without the subselects for each of the address 2 fields?
Thanks in advance.

A: Since you didn't really include a schema, and the names don't help at all, I just made a couple of assumptions on which fields do what (they're probably wrong).
You can just add the table a second time in a LEFT JOIN, and pull the addresses that way, like this:
SELECT
     T1.ABAN8
    ,T2.MAPA8
    ,SHIP.ALADD1
    ,SHIP.ALADD2
    ,BILL.ALADD1
    ,BILL.ALADD2
FROM F0101 T1
LEFT JOIN F0150 T2
  ON T1.ABAN8 = T2.MAAN8
LEFT JOIN F0116 AS SHIP
  ON T1.ABAN8 = SHIP.ALAN8
LEFT JOIN F0116 AS BILL
  ON T1.ABAN8 = BILL.ALAN8


text:
Q: Exact matches with wildcard search + keyword analyzer I use a wildcard query on fields indexed with a keyword analyzer. I want to find the following document
{
  title: "JavaScript beginner course",
  url: "https://youtube.com/xyz"
}

with these queries: *beginner course* and *youtube* (* are wildcards). This is working.
When I search for *Java*, the document above will also match. That's fine. However, I want to boost search results with exact word matches. Meaning, a document with Java in the title should have a higher search score.
Problem is, the keyword analyzer doesn't index each word separately. But I need the keyword analyzer, because otherwise *beginner course* wouldn't match in the example above.
Is there a way to achieve exact matching with wildcard search + a keyword analyzer?


text:
Q: AppendChield не работает Всем привет. Имею проблему: не могу создать элемент в javascript. Невозможно даже пустой div в документ засунуть.
let div = document.createElement('div');
document.body.appendChild(div);

Мне выдает ошибка в консоли: Cannot read property 'appendChild' of null
at lesson4.js:421
a div не создается.
Как правильно создать html файл в js, что я делаю не так? Помогите, пожалуйста)

A: У меня есть предположение, что вы подключаете .js файл в head, попробуйте подключить перед закрывающим тегом body.
<!DOCTYPE html>
<html>
<head>
    ...
</head>
<body>
    ...

    <script src="lesson4.js"></script>
</body>
</html>


text:
Q: Crazy python import error I have a python file that will not correctly perform an import.
If I go to the python prompt I can manually import the module without error.
Python 2.4.3 (#1, Feb 22 2012, 16:06:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from amqplib import client_0_8 as amqp

When I step through the program with pdb, the result of executing the import:
-> from amqplib import client_0_8 as amqp
(Pdb) s
--Call--
> /home/ralphie/Desktop/Projects/catamaran/build/bdist.linux-i686/egg/amqplib/__init__.py(0)?()

When I check sys.path:
Python 2.4.3 (#1, Feb 22 2012, 16:06:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from amqplib import client_0_8 as amqp
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg',
'/usr/lib  /python2.4/site-packages/mechanize-0.2.5-py2.4.egg',
'/usr/lib/python2.4/site-packages/ClientForm-0.2.10-py2.4.egg',
'/usr/lib/python2.4/site-packages/simplejson-2.3.2-py2.4-linux-i686.egg',
'/usr/lib/python2.4/site-packages/amqplib-1.0.0-py2.4.egg',
'/usr/lib/python24.zip',
'/usr/lib/python2.4',
'/usr/lib/python2.4/plat-linux2',
'/usr/lib/python2.4/lib-tk',
'/usr/lib/python2.4/lib-dynload',
'/usr/lib/python2.4/site-packages',
'/usr/lib/python2.4/site-packages/Numeric',
'/usr/lib/python2.4/site-packages/PIL',
'/usr/lib/python2.4/site-packages/gtk-2.0']

It is not coming from environment variables, I've deleted all .pyo & .pyc files.
I just have no idea where that crazy egg reference is coming from.
Any clues sincerely appreciated.

A: Try upgrading python to a more recent version, I had a lot of issues with python2.4 and amqp.
Even though the import statement succeeded the functional logic is not tested or executed until called.