text:
Q: Explode and search-> mySql I have a tag string saved as $value ,
$value is equal to 'my,name,is' .
I now want to separate $value and search every row that contains (eg: 'name') in my db...
I've tried doing this ->
$value = explode(',' , $value);

$query = "SELECT * FROM table WHERE words LIKE '%$value%'    ";

But this doesnt seem to work..
Please help :)
Thanks a lot,
I will appreciate any answers...

A: Need to Learn this by step by step
1)first get the full string in backend like "How to Work and Earn Money in expertsuggestion.com"
2)explode string by space
3)make a null array.
4)foreach for every explode string pass in you query one by one and the query of result array push into the null array
5)then after you can remove the duplicates id from array.
6)you got the final array.

A: php explode() returns array.
So you will need to use $value[0] etc
or use foreach loop:
$value = explode(',' , $value);
$i = 0;
$len = count($value);
$q = ' ';
foreach ($value as $val) {
    $q .= 'words LIKE '.$val.' ';
    if ($i != $len - 1) {
        $q .= ' OR ';
    }
    $i++;
}
$query = "SELECT * FROM table WHERE '$q'";

Did not test this, but you get the point. Comment if you need anything else.
Edit:
$value = 'name,is,my,etc';
$vals = explode(',', $value);

$i = 0;
$len = count($vals);

$string = '(';
foreach ($vals as $v) {
    $string .= "'".$v."'";
    if ($i != $len - 1) {
        $string .= ',';
    }
    $i++;
}
$string .= ')';

echo $string;

This will echo: ('name','is','my','etc')
You can paste it here and see the results
http://writecodeonline.com/php/

A: Not possible as written. $value is going to be an array. When you use an array in string context, it becomes the literal text Array.
If you want to do a like on each individual member of that array, your query has to look like
SELECT ... WHERE words LIKE '%value1%' OR words LIKE '%value2' OR ....

That means exploding your string into an array, then wrapping each member of that array with the '% ... %' and OR LIKE business.

comment followup:
$parts = explode(',', $value);
$in_clause = "'" . implode("','", $parts) . "'";
$sql = "SELECT ... IN ($in_clause)";

but note that this leaves you open to sql injection attacks.


text:
Q: Template code optimization for specific values of non-type parameters. template <bool flag>
class foo
{
    public:
        int bar()
        {
            if(flag)
            {
                // stuff
            }
        }
};

When the compiler compiles this class, it replaces the flag parameter by true or false. Then we have if(true) ( or if(false) ). Then, the if clause checks against a constant expression and WILL BE REMOVED at compile time. Can I expect compilers to behave like this?

A: No you can't. Any optimization is completely up to the compiler. Since you are using templates, you should write a specialization for both cases of flag.

A: Optimizations are compiler-specific. Why don't you create release build and step through disassembly?
Still, this is not idiomatic way to do that. You should either use template specialization or method overloading. They both provide compile-time resolving. So, in this case I would prefer the latter:
#include <type_traits>
template <bool flag>
class foo
{
public:
    int bar()
    {
        _bar(std::integral_constant<bool, flag>())
    }
private:
    int _bar(std::true_type)
    {
        // stuff
    }
    int _bar(std::false_type)
    {
        // empty
    }
};

EDIT: this requires C++0x, but can be easily translated to C++98 by including boost/type_traits and changing std:: directives to boost::. And, of course, it will require boost libraries.

A: Expect, yes. Rely, no. But how would you notice anyway?
Note that you cannot instantiate the template with false if you write code inside the if statement which fails to compile when flag is false. Removing the test would be done by an optimizer, which conceptually runs after the compiler has figured out what the code means in the first place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ngInfiniteScroll is not working on Firefox I'm having issues to make Firefox working with the ng-infinite-scroll - v1.0.0 - 2013-02-23
Please look at this Plunker : http://plnkr.co/edit/dlrca98kgJIQxbzmqadt?p=preview
it works fine on Chrome and Safari on my Mac.
The latest release (ng-infinite-scroll - v1.1.0 - 2014-04-03) doesn't fixes this specific issue instead isn't working anymore on Chrome and Safari.


text:
Q: adding using file integers input so i got the whole setup for my program and i was able to read the whole file content. the only one thing i need is to be able to add each column and put it in the variables i made. first column is miles second is gallons. so how can i make it possible using my code.
54 250 19
62 525 38
71 123 6
85 1322 86
97 235 14
#include <stdio.h>
#include <conio.h>

int main()
{
    // pointer file
    FILE *pFile;
    char line[128];
    int miles;
    int gallons;
    int mpg;

    // opening name of file with mode
    pFile = fopen("Carpgm.txt","r");

    //headers
    printf("Car No.  Miles Driven    Gallons Used\n");
    //checking if file is real and got right path
    if (pFile != NULL)
    {

        while (fgets(line, sizeof(line), pFile) != NULL)
        {
            int a, b, c;

            if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
            {
                /* Values read */
                printf("%d        %d             %d\n",a, b, c);

            }

        }
        mpg = miles / gallons;
        printf("Total miles driven: \n",miles);
        printf("Total Gallons of gas: \n",gallons);
        printf("Average MPG: \n",mpg);

        printf("%d",a);

        //closing file
        fclose(pFile);
    }
    else
    {
        printf("Could not open file\n");

    }

    getch();
    return 0;
}

A: That depends what you want to do.
If you just want to add values, you can do something like:
    ...
    int miles = 0;
    int gallons = 0;
    ...
    /* Values read */
    miles += b;
    gallons += c;
    ...

Note that you can't print a like you did before closing the file as a is defined only in the while loop.
Furthermore, your printf statements won't work as expected, you forgot to specify the format %d, do:
    printf("Total miles driven: %d\n",miles);
    printf("Total Gallons of gas: %d\n",gallons);
    printf("Average MPG: %d\n",mpg);


text:
Q: Filter a struct array according to a NSPredicate SWIFT I have an UITableView and an UISearchController. I want to filter my array of data (named: allGames)  according to the NSPredicate of the UISearchBar.text.
My code only filter an array of string like this:
func updateSearchResults(for searchController: UISearchController) {

    filteredGames.removeAll(keepingCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let array = (allGames).filtered(using: searchPredicate)

    filteredGames = array as! [String]

    self.tableView.reloadData()
}

Here I can filter my array. But if I create this struct:
struct Games {

    var name: String?
    var type: String?
    var image: UIImage?
}

How can I filter the array according to the game names and types? Thanks in advance for your help.

A: Assuming allGames is an array [Games] – by the way the struct is supposed to be named in singular form Game – I highly recommend to use the native Swift filter function
let searchText = searchController.searchBar.text!
let fileredGames = allGames.filter { $0.name?.range(of: searchText, options: [.caseInsensitive]) != nil
                                  || $0.type?.range(of: searchText, options: [.caseInsensitive]) != nil }

Consider also to declare type and name in the struct as non-optional.


text:
Q: How to get user's current location without asking for permission? can any one tell me how can i get the current location-latitude/longitude info of the user without asking his permission? Like getting user's location automatically?
Thanks in Advance.
Shreya

A: From apple's documentation

Important: In addition to hardware not being available, the user has
  the option of denying an application's access to location service
  data. During its initial uses by an application, the Core Location
  framework prompts the user to confirm that using the location service
  is acceptable. If the user denies the request, the CLLocationManager
  object reports an appropriate error to its delegate during future
  requests. You can also check the application's explicit authorization
  status using the authorizationStatus method.

So apple wont allow to use CoreLocation framework without user's permission. I don't thing there is no other way without using CoreLocation framework, atleast with public API..

A: I wouldn't recommend trying to get around Apple's TOS regarding getting user's permission to enable CoreLocation for an app.  It seems like a sure fire way to get your app rejected.  Apple may be sensitive about this kind of stuff.
Here's a related question I found.


text:
Q: Ruby Object Model / Class / Modules .... diagram anywhere? I have been thinking about making my own diagram to better put my head around how all the classes and modules in Ruby inherit from each other.  How it all ties together visually. I am sure there is a good one out there. I Googled it but was not satisfied with the results. Any suggestions?

A: I am also a visual learner and ended up drawing my own "homemade" diagram:

Hope this helps.

A: One of the best explanations and diagrammatic explanation of the ruby object model can be found in this book:  Metaprogramming Ruby  I tried googling the relevant pages but came up empty

A: For a good understanding on how the Ruby Object Model and Metaprogramming work, I would highly recommend these ScreenCasts by Pragmatic Programmer's Dave Thomas:
http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming
Dave Thomas is awesome at explaining the concepts, and the screencasts have nice graphics in them visualizing how things relate to each other..  those ScreenCasts are straight to the point, without distractions - and are worth every penny, err cent!
There is also a book "Metaprogramming Ruby" http://pragprog.com/book/ppmetr/metaprogramming-ruby
but although it covers a lot of concepts, the book is badly written, and through it's writing style makes it really hard to memorize the concepts / or use the book as a reference to look up things later..

A: A diagram showing superclass and eigenclass links between Ruby objects (but not the module inclusion links) is available at www.atalon.cz.
Since 11 January 2012 there is a diagram containing module inclusion links.


text:
Q: Simple jquery counter on appear There are so many different counter scripts I'm not sure where to start, what's overkill and what's not.
I'm looking for a simple counter script that fires when the target element first appears into view onscreen (for example, does not fire until scrolled into view)
The idea is that all I have to do to get the element to animate/count when scrolled into view, is give it a class of counter.
For example, html will be:
9955

First, those elements would be set to visibility:hidden until scrolled into view. Then, they would increment from 0 to the value of the text node (99 and 55 in this case) and stop when they reach the value. Some sort of ease out effect may be desirable but isn't a must (for example, start fast and slow down as it reaches the value)
Thanks in advance. Just looking for the simplest solution.

A: This is a complete code for your purpose:
function isElementVisible($elementToBeChecked)
{
    var TopView = $(window).scrollTop();
    var BotView = TopView + $(window).height();
    var TopElement = $elementToBeChecked.offset().top;
    var BotElement = TopElement + $elementToBeChecked.height();
    return ((BotElement <= BotView) && (TopElement >= TopView));
}

$(window).scroll(function () {
    $( ".counter" ).each(function() {
    isOnView = isElementVisible($(this));
        if(isOnView && !$(this).hasClass('Starting')){
           $(this).addClass('Starting');
           startTimer($(this));
        }
    });
});

function startTimer($this) {
    setTimeout(function(){
        $this.html($this.html() - 1);
        startTimer($this);
    }, 1000);
}

The isElementVisible function help to find out is a control is appeared on the screen after every scroll or not.
Then you call this function of every scroll and if  a .counter element appear on display, then start timer ONLY for THIS element using the startTimer function.
The !$(this).hasClass('Starting') is added to code to prevent unwanted call function, when a timer is started before and scroll on it again and again.
When a timer start for first time, the Starting class is added to element and is skipped in next times.
>>> JSFiddle Sample
You can see that every timer start only when is seen and other counters don't start until those are seen too.

A: Looks like part of your question already has an answer: Start executing jQuery function when I scroll to a specific

The answer on that question has a jsfiddle that will get you started. It's a matter of writing a simple counter script in start_count


text:
Q: Python: How to dynamically create parameterized anonomous/lambda functions? I need to create a function that parameterizes another function whereby some parameters are explicitly set and others are only set during the call to that function. (I have tried to make the question as succinct as possible whilst conveying the general specification of my problem) this is a brief implementation of what I am trying to accomplish.
class registration():
   #...
   def register(self, func, **kwargs):
     # ... append spec to internal dict

class spec():
     def __init__(self, func, **kwargs):
        self.func = func
        self.args = **kwargs

     def __call__(self, *args):
        # should call func with the

reg = registration()
def register(func, **kwargs)
    reg.register(func, **kwargs)

def func (**kwargs):
    for i in range(kwargs['param2'])
        print(kwargs[])
        print(kwargs['param3']['something'])

def func2 (**kwargs):
    if kwargs['param3']:
       print(kwargs['param1'])
    else:
       print(kwargs['param2'])

 register(func, param1 = "answer:", param2 = lambda x: x ** 0, param3 = {"something": lambda x: x * 8})

 # spec[0](111,8) -> answer: 1 64

 register(func2, param1= "hello", param2 = "goodbye", param3= x: if x >=0: return True; else: return False; )

 # spec[1](1) -> hello

My problem is how to effectively implement the functionality with regards to mapping/inputting the args in the call to the spec class and the parameters as shown above regardless of their position in the register function. This is especially significant when multiple registrations are implemented as shown above.
How could I most effectively implement the process of passing the parameters as in functools.partial, but for multiple different arrangements?


text:
Q: establish the identity $\|u+v\|^2+\|u-v\|^2=2\|u\|^2+2\|v\|^2$ for $u$, $v \in \mathbb R^n$ establish the identity $\|u+v\|^2+\|u-v\|^2=2\|u\|^2+2\|v\|^2$ for $u$, $v \in \mathbb R^n$.
I couldn't understand how to solve it  please just give me the first step, maybe I can figure out the solution.

A: Use the fact that $\|a\|^2 = a \bullet a$ ($a$ dot product itself).
Then $\|u+v\|^2 = (u+v)\bullet (u+v) = u\bullet (u+v) + v \bullet (u+v) = u\bullet u+ u\bullet v + v\bullet u + v\bullet v$.
You can expand $\|u-v\|^2$ in the same way.
The identity should follow pretty easily! :)

A: Turn all those norms into inner (dot products), using $\|u\|^2=u\cdot u$. Appeal to properties of inner (dot) products.


text:
Q: Python string formatting incremental changes def foo(string, **kwargs):
  return string % kwargs  # simplified a much more complex SQL query function with argument binding.

string = '%(a)s %(b)s.'
print foo(string %{'a': 'Hello'}, b='world')

I want to achieve this '%(a)s %(b)s' => 'Hello %(b)s' => 'Hello world' (and not '%(a)s %(b)s' => 'Hello world' in one go).
Is there anyway in python to make it work?

A: Just double the %:
string = '%(a)s %%(b)s.'

If you want to use the new string formatting spec, then you can similarly double the braces:
def foo(string, **kwargs):
  return string.format(**kwargs ) # simplified a much more complex SQL query function with argument binding.

string = '{a} {{b}}.'
print foo(string.format(a='Hello'), b='world')

prints:
Hello world.


text:
Q: Can you profit on the stock market from Friend Request? This answer mentions that you can profit from investing at the right time with the right companies related to Lester's assassination missions as Franklin.
Friend Request is the first mission the player does with Lester and its description mentions how Lester will make bank as a shareholder when Jay Norris is assassinated -- it's unclear how, but it's a small detail not mentioned.
In the real world, Facebook (LifeInvader) and Twitter (Bleeter) are sort-of competitors because they are huge moguls in the same sector -- I imagine, if something drastic happened to one, the other might see an opposite reaction in its stock price.
Is this the case in GTA V too? If I buy stock in Bleeter (or a LifeInvader competitor, if there's another), will its price go up for a profit?
I plan to test this and write an answer, but I may as well ask first, in case anyone else knows.

A: Life Invader and Bleeter are not competitors. They won't rise/fall with the other's misfortunes.
For a list of all competitors, and what missions you can profit from, go here.

A: Cyberclaw is correct.
If you want to make some easy cash. Buy 25000 ecola stocks (3-6 bucks) after the friend request mission and sell them when it hits 125 per share. (Later on in the story) Just keep any eye on the stock.

A: Just buy the stocks and keep buying ecola from a vending machine. You buy your own stock back by drinking it and it will increase after every 10 cans of soda. Keep going to that machine or others.


text:
Q: How to load the latest version of bootstrap I saw someone referencing:

http://twitter.github.com/bootstrap/1.4.0/bootstrap.min.css

But what I'd like to do is load "the latest" of version 1, similar to how Google cdn includes all the versions of a library along with "the latest" one.
Q: Is there something that I can load like:

http://twitter.github.com/bootstrap/1/bootstrap.min.css

To get the latest version 1 of twitter bootstrap?

A: AFAIK there isn't a pre-compiled version of the bootstrap css available on github, but I suppose you could reference http://twitter.github.com/bootstrap/assets/css/bootstrap.css, which is the one used by their site (but obviously this is not guaranteed to work indefinitely)

A: I don't think there is a reason to do so.
You always should test a new version to make sure it doesn't break your current application.


text:
Q: window.matchMedia not changing even if media queries are present There's a CSS file with these rules:
@media screen and (orientation:portrait) {
  .foo {}
}
@media screen and (orientation:landscape) {
  .foo {}
}

And then I've got this script, running on orientationchange:
function checkOr(){
    if (window.matchMedia("(orientation:portrait)").matches) {
      console.log('portrait ' + window.orientation);
    } else {
      console.log('landscape '+ window.orientation);
    }
}

But matchMedia always returns initial state of the page, when window.orientation returns correct value:
portrait -90
portrait 0
portrait -90

Tested on iPhone 5 and iPad 4 with latest iOS updates.
What am I doing wrong?
Webkit bugtracker says that there must be rules for each media query, but that's not my case.

A: How are you adding the event to call the function on orientationchange? I just tried this on my iPad and it seems to work fine: http://jsbin.com/ewixuc/2
function checkOr(){
    if (window.matchMedia("(orientation:portrait)").matches) {
      alert('portrait ' + window.orientation);
    } else {
      alert('landscape '+ window.orientation);
    }
}

window.addEventListener("orientationchange", checkOr);


text:
Q: restore button in inapp purchase I uploaded my app with in-app purchase feature to itunes store.But apple rejects my app due to "there is no restore button".If I added "Restore" button,how can I get my locally stored data?Please help me to solve this.

A: If, when you call [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];, setting the status of a purchase to YES for something that has been purchased before, there shouldn't be a problem. You won't need to consider the local data you have stored.
To retrieve something from NSUserDefaults:
[[NSUserDefaults standardUserDefaults] integerForKey:@"intKey];

A: You need to use restoreCompletedTransactions on the SKPaymentQueue to restore your previous transactions


text:
Q: Client Side Binding using by Converting the WCF Services to JSON We have  a Requirement of Consuming the WCf Services which is hosted in IIS like  http://localhost/someservice.svc.
We would like to consume that Service via java script and bind my sample data controls called grid view on client side itself.
I think this can be done by Serializing and deserialzing to JSON and consume the data source and bind the  grid controls.
Pls Refer the below link
http://forums.infragistics.com/forums/p/48035/258346.aspx
I would like to Achieve my func like the above link.
Can you pls guide me to achieve this Tasks.
Thanks
Regards
N.Balaji

A: Balaji,
Yes, you can definitely enable your WCF service (whether within IIS or not) to use JSON.
You do need to make one choice: do you want to use that service from the ASP .NET AJAX framework, or do you want to create a more general solution that is not tied down to that framework's usage within the browser?
If it's the former, use WebScriptEnablingBehavior. If it's the latter, use WebHttpBehavior.
For either scenario, detailed instructions are available in the following two MSDN sections:

*

*AJAX Integration and JSON Support

*WCF Web Http Programming Model


text:
Q: Export of all tags, not only your own When you get a list of files through the Box API, you also get the tags assigned to those files in string format. These tags include your own Box tags as well as shared tags (My Tags vs All Tags).
However, if you want to verify in a later phase if some of these tags have been deleted for instance, that seems not possible. The 'export tags' API method only returns your own tags.
This makes it really difficult to keep tags in sync, and I don't see a good reason why you would be able to see tags in the Box UI but not in the API. In the end it's just another representation of the same data, or that's what you would expect.
Anyone knows a possible workaround for this?

A: There isn't a known workaround for this at this time, but we're in the process of building out tags support in our V2 API and will take this use case into consideration.


text:
Q: jQuery Input Mask Decimal point I am using the jQuery plugin found at https://github.com/RobinHerbots/jquery.inputmask but I can't seem to be able to derive a pattern that corresponds to a integer & a decimal. For example,
I need the following to be valid:
      10
      150
      12.25
      0.45

At the moment I am doing:
$('#from_id').inputmask("9{0,5}.9{0,2}");

But this means that if the user does not specify what comes after the decimal point, the resulting output is:
For example, if the user only wants to input 12 (and he does not specify the decimal point) the output is
12___.__

(as the mask is waiting for the decimal point)
But if the user specifies the decimal point, for example 12.00, The output is fine like:
12.00

Could someone help me with this problem?

A: Try to use the optional parmaneter greedy like,
$('#from_id').inputmask({'mask':"9{0,5}.9{0,2}", greedy: false});

Read optional-masks-with-greedy-false
You can validate above mask. Or use your own logica to validate like,
$(function(){
    $('#id').on('keyup', function(e) {
        if (!this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/)) {
            $(this).addClass('error');// adding error class
        } else {
            $(this).removeClass('error');// remove error class
        }
    });
});

Demo
Or simply use toggleClass like,

$(function() {
  $('#id').on('keyup', function(e) {
    $(this).toggleClass('error', !this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/));
  });
});
.error {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="id" />

A: Have you tried using multiple masks?
$('#from_id').inputmask({'mask':["9{0,5}.9{0,2}", "999"]});


text:
Q: ProgressDialog is not showing even I am using a Thread for the task I have this (inside onCreate() method):
                    private ProgressDialog pDialog; //(this is in the header)
                    .
                    .
                    .
                    //This is onCreate() method
                    pDialog=new ProgressDialog(MenuActivity.this);
                    pDialog.setMessage(getString(R.string.downloading));
                    pDialog.setCancelable(false);
                    ...some lines of code...
                    pDialog.show();
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            resultados=timeConsumingTask();
                        }
                    });
                    thread.start();
                    try {
                        thread.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if(resultados.contains(1)){
                        if(pDialog!=null){
                            if(pDialog.isShowing()){
                                pDialog.dismiss();
                            }
                        }
                        doSomething();
                    }else{
                        if(pDialog!=null){
                            if(pDialog.isShowing()){
                                pDialog.dismiss();
                            }
                        }
                        doOtherThing();
                    {

I have looked at every tutorial and every answer here at SO. Everyone of them says that you must do pDialog.show(); just before the time consuming task, but obviously I am missing something, since the pDialog is never shown.
Can you help me to show it, and to dismiss it inside the if?
Thank you.
EDIT:
Maybe is relevant that I am calling the show() method and everything in the onClick() method of a FloatingActionButton)

A: To render any of the UI part activity OnCreate() function call must have to be finished/completed.
Since you are trying to show and hide the progress dialog from the same function it does not give effect of showing on screen.
Also by doing thread.join() you are blocking the main threat which prevents the OnCreate() completion and result in showing and hiding progress dialog within onCreate()
Solution: Try to perform your timeConsumingTask() on thread without thread.join() and use runOnUiThread() method to hide the progressDialog from thread itself

A: If the UI is blocked on some point the Dialog will not be shown.
The line  thread.join(); is blocking your UI thread.
Try using an AsyncTask instead a Thread and put on AsyncTask.onPostExecute() the code to be executed after the thread terminates.


text:
Q: Using JavaScript to make a button react ( adding animation ) In the Code Academy platform, one activity asked me to code my own button and make it react when the user clicks it.
This is what they asked me.
Fill in the event handler below to apply the class "btn-like" to the $(".btn") element. Use .toggleClass() to apply the class. Use this to operate on the already-selected HTML element.
and this is the code they give me.
var main = function() {
   $(".btn").click(function() {

  });
 };

$(document).ready(main);

I tried different ways but none of them was successful.  What is the correct way to program the reaction?

A: var main = function() {
    $(".btn").click(function() {
        $(this).toggleClass("btn-like");
    });
};

$(document).ready(main);

A: Just do what they've asked you to do within the .click() callback.
var main = function() { $(".btn").click(function() {
    $(this).toggleClass('btn-like');
}); };

$(document).ready(main);

A: https://s3.amazonaws.com/codecademy-content/courses/ltp2/img/events/click-try.svg
That's the Hint button but for me, isn't a hint is more confusing


text:
Q: Com Docker, devo usar o Composer no container ou no host? Tenho algumas dúvidas quanto ao ambiente de desenvolvimento. Tenho um projeto em Laravel e estou utilizando o Docker. Quando for utilizar o Composer ou o Artisan do Laravel, qual é o local indicado para se fazer isso? Na minha máquina host ou no container do Docker?

A: Se há necessidade de reaproveitar os pacotes em cache para outros projetos (quando instala um pacote o composer guarda em cache para não baixar novamente caso crie ou instale o pacote noutro projeto) então recomendo que use o composer do host, mas se isso não fizer muita diferença pode usar o composer do container.
Tenha em conta que, para o efeito deve estar usando uma imagem que trás o composer instalado ou poderá ainda criar sua própria imagem contendo toda stack que quiser.
Caso queira usar imagens prontas (com php, composer.. etc) recomendo o ambientum.


text:
Q: How to achieve Android Button Animation with text-blurred and shadow I want to achieve this button animation in Android. The sample below is from iOS. I want the shadow to disappear when the user clicks the button and reappear once the user releases the button.
Any help will be highly appreciated.

A: You need to add color like the following. For example, the color name is button_text_color.xml. Here is the .xml file which needs to be put in the color folder. If the color folder does not exist, create one in your res directory.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#50FFFFFF" android:state_pressed="true" />
    <item android:color="#FFFFFF" android:state_pressed="false" />
</selector>

Check that I have added 50% transparency to the white color in the pressed state. Now just add this attribute in the Button where it is declared.
Now you need a background drawable, to be put in your drawable folder. For example, let us take the name of the drawable is button_state_list_animator.xml. This should have the following content.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <layer-list>
            <item>
                <shape>
                    <solid android:color="@android:color/darker_gray" />
                    <corners android:radius="19dp" />
                </shape>
            </item>
            <item android:bottom="5px">
                <shape>
                    <padding android:bottom="5dp" />
                    <gradient android:angle="270" android:endColor="#163969" android:startColor="#1c4985" />
                    <corners android:radius="19dp" />
                    <padding android:bottom="10dp" android:left="10dp" android:right="5dp" android:top="10dp" />
                </shape>
            </item>
        </layer-list>
    </item>

    <item android:state_pressed="true">
        <layer-list>
            <item>
                <shape>
                    <solid android:color="#102746" />
                    <corners android:radius="19dp" />

                </shape>
            </item>
            <item android:bottom="5px">
                <shape>
                    <padding android:bottom="5dp" />
                    <gradient android:angle="270" android:endColor="#163969" android:startColor="#1c4985" />
                    <corners android:radius="19dp" />
                    <padding android:bottom="10dp" android:left="10dp" android:right="5dp" android:top="10dp" />
                </shape>
            </item>
        </layer-list>
    </item>
</selector>

Now your button construction is simple.
<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_margin="32dp"
    android:background="@drawable/button_state_list_animator"
    android:text="Save Changes"
    android:textColor="@color/button_text_color" />

Here is the screenshot from my code.

You can have the push-down animation using the library as well, as mentioned in an answer here.
Hope that helps!

A: Use the animation effect (as the code below) on the custom button when clicking on the button.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXScale="1"
        android:toXScale="0.8"
        android:fromYScale="1"
        android:toYScale="0.8"
        android:duration="500"
        android:pivotX="50%"
        android:pivotY="50%" >
    </scale>
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.8"
        android:duration="500">
    </alpha>
</set>

set Animation on Button Click using.
 btn_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R
                        .anim.animation_btn);
                btn_custom.startAnimation(animation);
            }
        });

try changing alpha values as your need and see the effect.

A: You can use this library : pushdown-anim-click
How to install:
compile( 'com.github.thekhaeng:pushdown-anim-click:1.1.1' ){
    exclude group: 'com.android.support'
}

How to use:
Button button = findViewById( R.id.button );

PushDownAnim.setPushDownAnimTo( button, ... )
    .setOnClickListener( new View.OnClickListener(){
        @Override
        public void onClick( View view ){
            Toast.makeText( MainActivity.this, "PUSH DOWN !!", Toast.LENGTH_SHORT ).show();
        }

});

For Shadow:
As I saw library files, There are only three java files. He just used class to animate button. You can give shadow in your button by this way. Even though I have created issue You can keep watch on this.

For more functionality, you can visit github link.
Thank you.

A: Add a layout with the background as the shadow below the button. In the button.setOnTouchListener hide the layout when button is pressed and make it visible when released.
However it will only work if the shadow is below.


text:
Q: How can i bind datagrid to some properties of a class in wpf? Is it possible to bind a datagrid to only selective members of a class?
The way I have made the binding presently, all the class variables have been binded(one to one mapped) to datagrid's columns.
    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

Now i want only a few class properties(not all) to be binded to the datagrid.

A: Yes, Just turn off the AutoGenerateColumns and manually specify them
In MainWindow.xaml
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Hello}" Header="Hello" />
        <DataGridTextColumn Binding="{Binding World}" Header="World" />
    </DataGrid.Columns>
</DataGrid>

In MainWindow.xaml.cs
  public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new[] { new FakeViewModel() };
    }
}

In FakeViewModel.cs
namespace WpfApplication4
{
  class FakeViewModel
  {
    public FakeViewModel()
    {
        Hello = "Hello";
        World = "World";
        Then = DateTime.Now;
    }
    public DateTime Then { get; set; }
    public string Hello { get; set; }
    public string World { get; set; }
  }
}

Please note the unused Property Then!


text:
Q: python install zope.interface module, show : AssertionError: Tried to end_progress without start_progress I use python ,and want to install module zope.interface in window 7, I used the cmd :
pip install zope.interface

but the console show :
Removing temporary dir c:\users\000790\appdata\local\temp\pip_build_000790...
Exception:

Traceback (most recent call last):

  File "C:\Python27\lib\site-packages\pip\basecommand.py", line 134, in main
    status = self.run(options, args)

  File "C:\Python27\lib\site-packages\pip\commands\install.py", line 236, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)

  File "C:\Python27\lib\site-packages\pip\req.py", line 1092, in prepare_files
    self.unpack_url(url, location, self.is_download)

  File "C:\Python27\lib\site-packages\pip\req.py", line 1238, in unpack_url
    retval = unpack_http_url(link, location, self.download_cache, self.download_dir)

  File "C:\Python27\lib\site-packages\pip\download.py", line 622, in unpack_http_url
    download_hash = _download_url(resp, link, temp_location)

  File "C:\Python27\lib\site-packages\pip\download.py", line 510, in _download_url
    logger.end_progress('%s downloaded' % format_size(downloaded))

  File "C:\Python27\lib\site-packages\pip\log.py", line 98, in end_progress
    "Tried to end_progress without start_progress")

AssertionError: Tried to end_progress without start_progress

Please let me know if you have any workaround for the above error.

A: Donwload from here the .egg of zope.interface and try this in CMD:
c:\Python27\Scripts\easy_install.exe c:\zope.interface-3.6.1-py2.6-win32.egg
NOTE: To install .egg, we need 'Easy Install' that is part of setuptools. So, we have to install setuptools first. Download it from here.
NOTE 2: the .egg sometimes is unrecognised if it isn't on C:\ path


text:
Q: Creating a workbook, sending values to it, then opening it for the user I'm getting an overflow error now with the line that inserts the date.
        With ActiveSheet
            Dim wbNewAudit As Workbook: Set wbNewAudit = Workbooks.Open("\\JACKSONVILLE-DC\Common\SOP's for JV\SOP Audits\2019\" & NewAuditFileName, True, True)
            wbNewAudit.Worksheets(1).Range("A1") = "SOP Title: " & .Cells(ActiveRow, 3)
            wbNewAudit.Worksheets(1).Range("E1") = "Date: " & Format(Now, "MM / dd / yyyy")
        End With

A: Change the quotation marks to straight quotes: Format(Now, "MM / dd / yyyy") via BigBen


text:
Q: How to Append Result to a Table in BigQuery Below is my code for Querying BQ datasets :
   BigQuery  bigquery = bigQuery();
  TableId destinationTable = TableId.of(datasetName, TableName);

        QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(Query())
                .setDestinationTable(destinationTable).setWriteDisposition(JobInfo.WriteDisposition.WRITE_APPEND)
                .setSchemaUpdateOptions(ImmutableList.of(JobInfo.SchemaUpdateOption.ALLOW_FIELD_ADDITION))
                .setUseQueryCache(false)
                .build();

        TableResult results = bigquery.query(queryConfig);

results is returning me the data of present query + data which is already present in my
TableName. So if my query return 1 row and there are 2 rows already present in the destination table so result is having 3 row.
How to get the result of query only.


text:
Q: What are "Force Carriers"? The concept of "force carriers" is hard for me to understand.  I can understand "energy carriers".  I can understand mass x acceleration but I can't see how this applies.  Does anyone have a descriptive definition?  Something more classical?
Perhaps "force carrier" is QM shorthand for a more complex concept.
Gravity is a force that can be described in terms of geometry.  I can understand that.

A: When particles experience a mutual force, it can be thought of in a couple of different, but equivalent ways. The first is in terms of a field that produces a force depending on the coordinates in space and time. The second is in terms of the exchange of other particles that mediate the force.
For example, scattering between two electrons can be understood as one electron emitting a photon which is absorbed by the other, transferring momentum.
Force carriers are the fundamental particles that describe these interactions. In general they are bosons, i.e. particles with integer spin.
For example the gauge bosons are force carriers in the standard model of particle physics:
Particle          Corresponding force
-------------------------------------
Photon            Electromagnetic
Gluon             Strong nuclear
W and Z Bosons    Weak

A: In the standard model of physics, the SU(3)xSU(2)xU(1), this is the table of particles that enter into the Lagrangian:

The red column has the "carrier of the forces", gluon the strong force, gamma the electromagnetic,Z and W the weak. They are the gauge bosons which  have a mass of zero in the unified theory , before symmetry breaking by the Higgs field.
They are exchanged in the first order Feynman diagrams of the interactions and in this sense characterize most of the crossections attributed to that specific fundamental force, that is why they are called "force carriers", they transfer momentum between interacting particles to first order and force is ~dp/dt.
A classical analogue is the boomerang and the boat analogy, see my answer to this question.

A: The force carrier is the particle that mediates an interaction between two particles and sometimes two clusters of particles. The most common force carrier in nature is the photon. It is the force carrier for Electromagnetism. All particles that couple to electromagnetism emits or absorbs photons. This is basically all atoms. This is because each of those are made of charged particles which do couple to the electromagnetic field. On top of this quarks and sometimes the hadrons they build interact with the strong force. The gluon is the force carrier here. On top of this all fermions interact with the weak force. The weak force uses particles called W and Z bosons. The Higgs boson is like a force carrier sometimes and can be considered as part of the weak force though it is not usually done.

A: Force carriers is a concept from quantum field theories.  There are two basic classifications for fundamental particles:  fermions, which are those which obey Fermi-Dirac statistics, have spin that is an odd multiple of 1/2; these contrast with the bosons, which obey Bose-Einstein statistics, and have integral spin.
Examples of fermions are electrons, neutrinos, quarks - all spin 1/2.
Examples of bosons are photons and gluons - all spin 1; they also have no mass.
The bosons are also known as force carriers, while the fermions are used to build up material systems.
The both carry energy and momentum.  You can find endless amounts of information for bosons and fermions at www.theparticleadventure.org

A: Materia consist from particles. The energy exchange between materia happens by the emission and absorption of photons. This you can prove for all physical and chemical processes except processes inside the nucleus, where the quarks interact through gluons.
But how to deal with an electrostatic field and with a magnetic field? Both fields exist without any energy transfer (if suppose that both phenomenon are intrinsic properties and exist without our observation or any other interaction). Approaching two equally charged particles together, the energy content of the electrostatic fields is not changed, but the fields get deformed and by this they store energy (as one see when release them, they immediately repel each other).
To explain this phenomenon it was introduced the force carrier. No energy exchange but force exchange. For magnetic fields this is much harder to explain such exchange since the field is closed in circles because magnetic monopoles do not exist. The concept of force carrier seems to be a little bit helpless since every force is based on energy exchange.
Fields have to be understood as having an inner structure and consist of quanta. When instead of photon exchange there would be a changing inner structure of quanta clusters. Photons are nothing else than emitted clusters from this quanta and arise when the inner structure of the fields is not able to transform itself. But it seems that to think about the inner structure of electric and magnetic fields and the electromagnetic radiation is not worth. Anyway, it happen to me and I was free to elaborate it: Complex one-dimensional structures of space.


text:
Q: Bootstrap pre element with overflow-x: auto has the width of the window instead of the parent I have a Bootstrap 4.3 pre as shown below.
A
 element has overflow: auto;, which means overflow-x: auto; and overflow-y: auto;. This produces a horisontal scroll bar when the content inside has more width than its parent.
But the parent elements width is not analysed correctly. If, for example, the col-nav to the left takes up 100px, then the
 is 125px too wide. Which makes the web page 125px too wide.
In other words, the width of the
 seems to be determined by the windows width.
Check it out in this jsfiddle.
What am I doing wrong?
Ps. If I give the
 element a specific low width in px my web page stays within the width of the window, but not if I give it a low % width. I can't use something like calc(100% - 125px); either. But even if I could, I would not know what the width of col-nav.

    ...

        ...

A: The problem is that flexbox, by default, won't shrink something smaller than it can go.
Because your green text is one single word, and you didn't use word-break:break-word;white-space:normal; or something similar, the browser can't break the word into multiple lines, and therefore there's a minimum size that it can be shrunk.
If you want to shrink the flex item smaller than its minimum size, you'll need to use min-width:0; on the flex item.
JSFiddle: https://jsfiddle.net/gkvz6s3h/


text:
Q: Json Deserialize fails Could please someone explain me why Deserialize method fails ?
        [Test]
        public void Serialize_Deserialize_ExpandObject()
        {
            dynamic obj = new ExpandoObject();
            obj.Name = "Claudio";
            obj.Age = 32;

            JavaScriptSerializer ser = new JavaScriptSerializer();
            string json = ser.Serialize(obj as IDictionary<string, object>);
            Console.WriteLine(json);

            IDictionary<string, object> deserialize = ser.Deserialize<IDictionary<string, object>>(json);
            Assert.IsTrue(deserialize.ContainsKey("Name"));
            Assert.IsTrue(deserialize.ContainsKey("Age"));
        }

A: It seems as though ExpandoObject gets serialized as an array (of dictionaries) rather than a dictionary.
It gets serialized as [{"Key":"Name","Value":"Claudio"},{"Key":"Age","Value":32}] rather than {"Name":"Claudio","Age":32}
I guess there is some other interface that ExpandoObject implements like IEnumerable (as well as IDictionary<>) so the Serialize method treats it as an array. The cast (as IDictionary<string, object>) makes no difference because it doesn't actually alter what gets passed to the Serialize method. But this all seems to contradict the documentation http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx.
You can deserialize to List<IDictionary<string, object>> but I suppose thats not terribly useful.


text:
Q: Restore a point between two full backups I make two full backups on Oct 1 and Oct 10. I want to restore the server to a state in Oct 5. So I just do as follows:

*

*Perform a transaction log backup on the server on Oct 23. I have never backup transaction log in the past.

*Restore the server with Oct 1 full backup with NORECOVERY option.

*Try to restore to the point at Oct 5 12:00, with the transaction log.

But the restore fails and  SQL Server said the transaction log does not contain the point. The point is too early. Why? Also my .LDF file is about 13G, but the transaction log backup is only 200MB. Why?
Thanks

A: You can do a point in time recovery to Oct 5th if you have only full backups and a last transction log backup (called a tail log backup).
Your transaction log backup contains all transactions back to the last log backup. So that should be sufficient to do a point in time recovery.
That you are getting the message "transaction log does not contain the point" indicates one of the following:

*

*There were other transaction log backups taken before your last transaction log backup.

*The database was in Simple recovery mode somewhere between the 1st and the 23rd of October.

The reason your transaction log is so big is that it was not backed up regurarly. As transactions happen, the log grows. A transaction log backup truncates your transaction log, and then the empty space can be used for new transactions. The reason can also be that there was a big amount of data modified.
Recommendation: regurarly backup your database (for example every day) and your transaction logs (at least every hour or even more often, depending on the activity in the database). Keep those backups in a safe place. Then you will be able to do proper point in time recovery.


text:
Q: Blackberry HttpPost null pointer exception Java With the following code, the server is getting hit, but I also want to send variables in POST method.
But it just gives me a null pointer exception. It has something to do with the OutputStream.   I have checked postData ... it has some address, which means it is not null.
So why I am given null pointer exception?
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
try {
    connDesc = connFact.getConnection("http://example.com/login.php", Connector.READ_WRITE, returnContent);
    httpConn.setRequestMethod(HttpConnection.POST);
    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
    encPostData.append("count", "Hell Yeah!");
    byte[] postData = encPostData.toString().getBytes("UTF-8");

    httpConn.setRequestProperty("Content-length", String.valueOf(postData.length));
    Dialog.alert("Post Data: " + postData);

    OutputStream os = httpConn.openOutputStream();
    os.write(postData);
    os.flush();
    httpConn = (HttpConnection) connDesc.getConnection();

    final int iResponseCode = httpConn.getResponseCode();
    UiApplication.getUiApplication().invokeLater(new Runnable() {
        public void run() {
            //Dialog.alert("Response code: " +  Integer.toString(iResponseCode));
        }
    });
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

A: You are misusing the ConnectionFactory.getConnection(String url, int transportType, String ConnectionUID) method. For instance, check what you pass as transportType...
Here is what API says about return value:

Returns: a ConnectionDescriptor if a connection can be established;
  null otherwise

So, it just fails and returns null. And that's why you get a NPE.
UPDATE:
I would recommend to just use a simpler API ConnectionFactory.getConnection(String url):
ConnectionDescriptor cd = connFact.getConnection("http://example.com/login.php");
if (cd == null) {
    // throw an error signalling there is no connectivity right now
}
HttpConnection httpConn = (HttpConnection) cd.getConnection();
// the rest of the code working with httpConn ..

A: Have a look to the linked answer and verify if that implementation of 'login' procedure is ok for your needs:
authentication username password url in blackberry


text:
Q: Java applet from jar Had no luck getting this to work via what I found on google.

A: You can load any resource that is available on the classpath, which your jar would be a part of, using ClassLoader.getResource(String)
You can obtain a reference to a relevant ClassLoader object using Class.getClassLoader()
ClassLoader cl = MyClass.class.getClassLoader();

If your image were named myimage.png and in a directory called images inside your jar, you could get the image like so.
URL url = cl.getResource("images/myimage.png");

You can then use the URL to create an image object in memory.
Image i = Toolkit.getDefaultToolkit().createImage(url);

A: The tutorial on How to Use Icons at the Java website may be of use to  you.
You'll do something like this:
java.net.URL imgURL = this.getClass().getResource(path);

The getResource() method uses the same loading rules as defined by the ClassLoader for the class.


text:
Q: How can I fetch rand records from a union query? SELECT a, b, c FROM ".TBL_A." WHERE [statement] **`ORDER BY RAND()`** LIMIT 1
UNION
(SELECT a, b, c FROM ".TBL_A." WHERE [different statement] ORDER BY RAND() LIMIT 5)";

This query works fine without first ORDER BY RAND(), but what I need is to fetch first rec randomly by first statement and then 5 other random recs by other statement.
It seems that I can't use two order by statements on one query...
Any thoughts?

A: Your approach should work. Perhaps you just need to wrap your selects in an outer select.
SELECT * FROM (
    SELECT a, b, c FROM your_table WHERE [statement] ORDER BY RAND() LIMIT 1
) T1
UNION
SELECT * FROM (
    SELECT a, b, c FROM your_table WHERE [different statement] ORDER BY RAND() LIMIT 5
) T2

Note. Make sure that you have considered the difference between UNION and UNION ALL. It is a common mistake to get them mixed up.

A: you should select it all with out order - and then do big select for the 2 queries with order by.

A: Do not use RAND() it is a terrible generator. Use a cryptographically secure generator. Depending on platform it might be arcrand(), reading from /dev/random, openSSL or some other source.


text:
Q: Set jdk location in ubuntu for glassfish server While running glassfish server from a windows command prompt, I was getting errors like
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required

I resolved it by adding one line in the asenv.bat file in the config directory of glassfish server folder
set AS_JAVA=C:\Program Files\Java\jdk1.7.0_17

Now I am getting the same error on Ubuntu and I need to know the syntax that I need to put in the asenv.bat file.
My JDK locaion is \home\szlynas\jdk1.6.0_45

A: Bat files are for the Windows environment, in Linux you should apply modifications to the asenv.conf file.


text:
Q: compiling java package classes. Cannot access Class. class file contains wrong class while working with packages I was trying to compile a few files in a package in java. The package name is library. Please have a look at the following details.
This is my Directory Structure:
javalearning
---library
------ParentClass.java
------ChildClass.java

I tried to compile in the following way:
current directory: javalearning
javac library/ParentClass.java   //this compilation works fine
javac library/ChildClass.java    //error over here

The following is the ParentClass.java:
package library;
class Parentclass{
...
}

The following is the ChildClass.java:
package library;
class ChildClass extends ParentClass{
...
}

The error is as follows:
cannot access ParentClass
bad class file: .\library\ParentClass.class
Please remove or make sure it appears in the correct sub directory of the classpath

A: You've got a casing issue:
class Parentclass

That's not the same as the filename ParentClass.class, nor is it the same as the class you're trying to use in ChildClass: class ChildClass extends ParentClass.
Java classnames are case-sensitive, but Windows filenames aren't. If the class had been public, the compiler would have validated that the names matched - but for non-public classes, there's no requirement for that.
The fact that you've ended up with ParentClass.class suggests that at some point it was declared as ParentClass, but then you changed the declared name and when recompiling, Windows just overwrote the content of the current file rather than effectively creating Parentclass.class.
Make sure your declared class name exactly matches the filename. You may well want to delete all your class files before recompiling, just to get out of a confusing state.


text:
Q: Login to slideshare I'm trying to create a tool to manage multiple slideshare accounts. It's pretty tiresome to login and logout of each of them manually, so a thought to create a simple webbrowser tool that does the login for me.
Problem is, when I try to hit the login button it tells me the 'fields need to be populated' (and they are) then when i focus the control and try to press the login manually (from within the webbrowser control) i tells me that it's 'invalid username/password combination'
I even took it a step firther and deleted the text from the inputs and repasted the same ones from a text file, but the same 'invalid user/pass' massage appears.
When I try yo do this manually from an actual IE browser, it logs in no problem. I have no idea what I'm doing wrong. Here's the code:
Private Sub targetSlideshare()
    Dim details() As String
    details = accounts(currentAcc).Split(":")
    user = details(0)
    pass = details(1)
    Label19.Text = (currentAcc + 1).ToString + "/" + accounts.Length.ToString

    status = "Logout"
    Label20.Text = status
    loaded2 = False
    WebBrowser2.Navigate("https://www.slideshare.net/logout")
    While loaded2 = False
        Threading.Thread.Sleep(1000)
    End While
    Threading.Thread.Sleep(1000)

    status = "Logging In"
    Label20.Text = status
    loaded2 = False
    WebBrowser2.Navigate("https://www.slideshare.net/login")
    While loaded2 = False
        Threading.Thread.Sleep(1000)
    End While
    Threading.Thread.Sleep(5000)
End Sub

Private Sub WebBrowser2_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser2.DocumentCompleted
    If WebBrowser2.ReadyState <> WebBrowserReadyState.Complete Then
        Exit Sub
    End If
    If status = "Logout" Then
        loaded2 = True
    ElseIf status = "Logging In" Then
        WebBrowser2.Document.GetElementById("user_login").SetAttribute("value", user)
        'WebBrowser2.Document.GetElementById("user_login").SetAttribute("placeholder", Nothing)
        WebBrowser2.Document.GetElementById("user_password").SetAttribute("value", pass)
        'WebBrowser2.Document.GetElementById("user_password").SetAttribute("placeholder", Nothing)
        Dim allelements As HtmlElementCollection = WebBrowser2.Document.All
        For Each webpageelement As HtmlElement In allelements
            If webpageelement.GetAttribute("value") = "Login" Then
                status = "Loading"
                webpageelement.InvokeMember("click")
            End If
        Next

        loaded2 = True
End Sub

A: I can't get to that site from the PC i'm currently at, but the following works for me to login to Google:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    WebBrowser1.Navigate("https://accounts.google.com/ServiceLogin?hl=en&continue=https://www.google.com/")
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    WebBrowser1.Document.GetElementById("Email").InnerText = user.ToString
    WebBrowser1.Document.GetElementById("Passwd").InnerText = pass.ToString
    WebBrowser1.Document.GetElementById("signIn").InvokeMember("click")
End Sub

One other trick that might be helpful:
I've found when I'm having problems logging in through the webbrowser control on some desktop sites trying to the automate the login on the mobile version ie: https://www.slideshare.net/mobile/login sometimes works.


text:
Q: Difference of pixel value in Image between Matlab and Opencv I get frame from avi video and I open color image by Matlab and check pixel value of three channel R,G,B. (case  1)
After that, I use opencv2.4.3 to get frame and save pixel value by txt file. Then, I check txt file, I realize pixel value is different from Matlab (I know color image opened by opencv is BGR, and the index position of pixel must be minus 1 (in Matlab, pixel position(x,y).In c,pixelposition (x-1,y-1))). (case 2)
Finally, I use opencv to save frame by cvSaveImage function and then I open this frame by Matlab. In this case, pixel value is also different from two above case.
Why this happens?
Thank you for answering! Sorry about my English!
This is my code
http://www.scribd.com/doc/129263549/Code (you have to download it to read)

A: Matlab and OpenCV have different ways of storing pixel values. Matlab uses compression to save .jpeg images before storing them. So if you view the pixel data for similar images in Matlab and OpenCV, it will look different.
If you load and save the same source image in both Matlab and OpenCV, the former will be smaller in size than the later; even though you don't do any operations on the image.
There is no way you can make both image data to look same. Fortunately, any operations done on the image are not affected by this difference in the internal structure. For example, if you try to find the indices of certain pixels in Matlab and OpenCV, both will give correct values, though the values won't look the same.


text:
Q: Powershell script to create symbol directory from nuget directory/feed Unfortunatly we currently don't have the possibility of a convenient symbol server at hand.
So I try to write a powershell script which gets the nugets either directly from the feed or the local nuget package cache and create a symbol directory on that way.
I am strugging with a way to get the baked in GUID from the dll or pdb via powershell/cmdline.
Anyone ever done that and could provide some advice?


text:
Q: Does the shebang determine the shell which runs the script? This may be a silly question, but I ask it still. If I have declared a shebang
#!/bin/bash

in the beginning of my_shell_script.sh, so do I always have to invoke this script using bash
[my@comp]$bash my_shell_script.sh

or can I use e.g.
[my@comp]$sh my_shell_script.sh

and my script determines the running shell using the shebang? Is it the same happening with ksh shell? I'm using AIX.

A: The exec system call of the Linux kernel understands shebangs (#!) natively
I hadn't noticed that OP asked about AIX, I'm going to say what I know about Linux, and bet that there are strong analogies, or at least satisfy the majority of Googlers who are looking for Linux :-)
When you do on bash:
./something

on Linux, this calls the exec system call with the path ./something.
This line of the kernel gets called on the file passed to exec: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))

It reads the very first bytes of the file, and compares them to #!.
If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec call with path /usr/bin/env python and current file as the first argument:
/usr/bin/env python /path/to/script.py

and this works for any scripting language that uses # as a comment character.
And yes, you can make an infinite loop with:
printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a

Bash recognizes the error:
-bash: /a: /a: bad interpreter: Too many levels of symbolic links

#! just happens to be human readable, but that is not required.
If the file started with different bytes, then the exec system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46 (which also happens to be human readable for .ELF). Let's confirm that by reading the 4 first bytes of /bin/ls, which is an ELF executable:
head -c 4 "$(which ls)" | hd

output:
00000000  7f 45 4c 46                                       |.ELF|
00000004

So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: https://stackoverflow.com/questions/8352535/how-does-kernel-get-an-executable-binary-file-running-under-linux/31394861#31394861
Finally, you can add your own shebang handlers with the binfmt_misc mechanism. For example, you can add a custom handler for .jar files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.
I don't think POSIX specifies shebangs, however: https://unix.stackexchange.com/a/346214/32558, although it does mention it in rationale sections, and in the form "if executable scripts are supported by the system something may happen".

A: In fact, if you take it consequently, the executable noted in the shebang line, is just an executable. It makes sense to use some text interpreter as executable, but it is not necessary. Just for clarification and demonstration, i made a rather useless test:
#!/bin/cat
useless text
more useless text
still more useless text

Named the file test.txt and set the exectuable bit chmod u+x test.txt, then "called" it: ./test.txt. As expected, the contents of the file is output. In this case, cat does not ignore the shebang line. It simply outputs all lines. Any useful interpreter should thus be able to ignore this shebang line. For bash, perl and PHP, it is simply a comment line. So yes, these ignore the shebang line.

A: The shebang #! is an human readable instance of a magic number consisting of the byte string 0x23 0x21, which is used by the exec() family of functions to determine whether the file to be executed is a script or a binary. When the shebang is present, exec() will run the executable specified after the shebang instead.
Note that this means that if you invoke a script by specifying the interpreter on the command line, as is done in both cases given in the question, exec() will execute the interpreter specified on the command line, it won't even look at the script.
So, as others have noted, if you want exec() to invoke the interpreter specified on the shebang line, the script must have the executable bit set and invoked as ./my_shell_script.sh.
The behaviour is easy to demonstrate with the following script:
#!/bin/ksh
readlink /proc/$$/exe

Explanation:

*

*#!/bin/ksh defines ksh to be the interpreter.

*$$ holds the PID of the current process.

*/proc/pid/exe is a symlink to the executable of the process (at least on Linux; on AIX, /proc/$$/object/a.out is a link to the executable).

*readlink will output the value of the symbolic link.
Example:
Note: I'm demonstrating this on Ubuntu, where the default shell /bin/sh is a symlink to dash i.e. /bin/dash and /bin/ksh is a symlink to /etc/alternatives/ksh, which in turn is a symlink to /bin/pdksh.
$ chmod +x getshell.sh
$ ./getshell.sh
/bin/pdksh
$ bash getshell.sh
/bin/bash
$ sh getshell.sh
/bin/dash

A: Yes it does. By the way it is not a silly question. A reference for my answer is here.
 Starting a Script With #!

*

*It is called a shebang or a "bang" line.

*It is nothing but the absolute path to the Bash interpreter.

*It consists of a number sign and an exclamation point character (#!), followed by the
full path to the interpreter such as /bin/bash.
All scripts under Linux execute using the interpreter specified on a first line
Almost all bash scripts often begin with #!/bin/bash (assuming that Bash has been installed in /bin)
This ensures that Bash will be used to interpret the script, even if it is executed under another shell.
The shebang was introduced by Dennis Ritchie between Version 7 Unix and 8 at Bell Laboratories. It was then also added to the BSD line at Berkeley .
Ignoring An Interpreter Line (shebang)
If you do not specify an interpreter line, the default is usually the /bin/sh. But, it is recommended that you set #!/bin/bash line.

A: From what I gathered, whenever a file has an executable bit set and is invoked, the kernel analyzes the file header in order to determine how to proceed (as far as I know, you can add custom handlers for custom file formats via LKMs). If the file appears to be a text file with a #! combination in the beginning, its execution is dispatched to another executable (usually a shell of sorts), a path to which is to be specified directly after the said shebang, in the same line. The kernel then proceeds to execute the shell and pass the file for it to handle.
In short, it doesn't matter which shell you invoke the script with - the kernel will dispatch the execution to the appropriate one either way.


text:
Q: Why doesn't template.ParseFiles() detect this error? If I specify a non-existent template in my template file, the error is not detected by ParseFiles() but by ExecuteTemplate(). One would expect parsing to detect any missing templates. Detecting such errors during parsing could also lead to performance improvements.
{{define "test"}}

        <title> test </title>

 Hello, world!

        {{template "doesnotexist"}}

{{end}}

main.go
package main

import (
    "html/template"
    "os"
    "fmt"
)

func main() {
    t, err := template.ParseFiles("test.html")
    if err != nil {
        fmt.Printf("ParseFiles: %s\n", err)
        return
    }

    err = t.ExecuteTemplate(os.Stdout, "test", nil)
    if err != nil {
        fmt.Printf("ExecuteTemplate: %s\n", err)
    }
}

10:46:30 $ go run main.go
ExecuteTemplate: html/template:test.html:8:19: no such template "doesnotexist"
10:46:31 $

A: template.ParseFiles() doesn't report missing templates, because often not all the templates are parsed in a single step, and reporting missing templates (by template.ParseFiles()) would not allow this.
It's possible to parse templates using multiple calls, from multiple sources.
For example if you call the Template.Parse() method or your template, you can add more templates to it:
_, err = t.Parse(`{{define "doesnotexist"}}the missing piece{{end}}`)
if err != nil {
    fmt.Printf("Parse failed: %v", err)
    return
}

The above code will add the missing piece, and your template execution will succeed and generate the output (try it on the Go Playground):

        <title> test </title>

 Hello, world!

        the missing piece

Going further, not requiring all templates to be parsed and "presented" gives you optimization possibilities. It's possible there are admin pages which are never used by "normal" users, and are only required if an admin user starts or uses your app. In that case you can speed up startup and same memory by not having to parse admin pages (only when / if an admin user uses your app).
See related: Go template name


text:
Q: Prove that $(a,b)\to \mathbb{R}$ etc How do I prove that for $n\in \mathbb{N},f,g:(a,b)\to\mathbb{R}$ $n$ times differentiable and $c\in \mathbb{R}$
1st case:  $(f+g)^{(n)}=f^{(n)}+g^{(n)}$
2nd case: $(cf)^{(n)}=cf^{(n)}$
3rd case: $(fg)^{(n)}=\sum^n_{k=0}{n\choose k}f^{(k)}g^{(n-k)}$

A: You can prove all by induction, if you already know that $(f+g)' = f' + g'$, $(cf)' = cf'$ and $(fg)' = f'g + fg'$.
The first one and the second one are very easy ; the proof of the third is equivalent to the proof of the binomial theorem.

A: $\forall n \ge 1, f^{n} = (f^{n-1})'$ and $f^{(0)}=f$

Let $P_n:"(f+g)^{(n)} = f^{(n)}+g^{(n)}"$
$\cfrac{(f+g)(t+h)-(f+g)(t)}{h} = \cfrac{f(t+h)+g(t+h)-f(t)-f(h)}{h} = \cfrac{f(t+h)-f(t)}{h}+\cfrac{g(t+h)-g(t)}{h} \underset{h\to0}{\longrightarrow}f'(t)+g'(t)$
So $(f+g)'$ exists and $(f+g)'=f'+g'$ so $P_1$ is true.
Suppose $P_n$ true for $n\ge 1$
$(f+g)^{(n+1)} = ((f+g)^{(n)})' \underset{P_n}{=} (f^{(n)}+g^{(n)})' \underset{P_1}{=} (f^{(n)})' + (g^{(n)})' = f^{(n+1)}+g^{(n+1)}$ so $P_{n+1}$ is true.
Since $P_1$ is true and $P_n \Rightarrow P_{n+1}$, $\forall n \ge 1,P_n$ is true.

Let $Q_n:"(cf)^{(n)}=cf^{(n)}"$
$\cfrac{(cf)(t+h)-(cf)(t)}{h}=\cfrac{cf(t+h)-cf(t)}{h}= c\cfrac{f(t+h)-f(t)}{h}\underset{h\to0}{\longrightarrow}cf'(t)$
So $(cf)'$ exists and $(cf)'=cf'$ so $Q_1$ is true.
Suppose $Q_n$ is true for $n\ge 1$
$(cf)^{(n+1)}=((cf)^{(n)})'\underset{P_n}{=}(cf^{(n)})'\underset{P_1}{=}c(f^{(n)})'=cf^{(n+1)}$ so $Q_{n+1}$ is true.
Since $Q_1$ is true and $Q_n \Rightarrow Q_{n+1}$, $\forall n \ge 1,Q_n$ is true.

Let $R_n:"(fg)^{(n)}=\sum\limits^n_{k=0}{n\choose k}f^{(k)}g^{(n-k)}"$
$\cfrac{(fg)(t+h)-(fg)(t)}{h}=\cfrac{f(t+h)g(t+h)-f(t)g(t)}{h} = \cfrac{f(t+h)g(t+h)+f(t+h)g(t)-f(t+h)g(t)-f(t)g(t)}{h} = \cfrac{f(t+h)(g(t+h)-g(t))+g(t)(f(t+h)-f(t))}{h}=f(t+h)\cfrac{g(t+h)-g(t)}{h}+g(t)\cfrac{f(t+h)-f(t)}{h}\underset{h\to0}{\longrightarrow} f(t) g'(t) + g(t)f'(t)$
So $(fg)'$ exists and $(fg)'=f'g+fg'={1\choose 0}f^{(0)}g^{(1-0)}+{1\choose 1}f^{(1)}g^{(1-1)}=\sum\limits^1_{k=0}{1\choose k}f^{(k)}g^{(n-k)}$ so $R_1$ is true.
Suppose $R_n$ true for $n\ge 1$
$(fg)^{(n+1)}=((fg)^{(n)})'\underset{R_n}{=}(\sum\limits^n_{k=0}{n\choose k}f^{(k)}g^{(n-k)})'\underset{P_k}{=}\sum\limits^n_{k=0}({n\choose k}f^{(k)}g^{(n-k)})'\underset{Q_k}{=}\sum\limits^n_{k=0}{n\choose k}(f^{(k)}g^{(n-k)})'\underset{R_1}{=}\sum\limits^n_{k=0}{n\choose k}\left(f^{(k+1)}g^{(n-k)}+f^{(k)}g^{(n-k+1)}\right)=\sum\limits^n_{k=0}{n\choose k}f^{(k+1)}g^{(n-k)}+\sum\limits^n_{k=0}{n\choose k}f^{(k)}g^{(n-k+1)}=\sum\limits^{n+1}_{k=1}{n\choose k-1}f^{(k)}g^{(n-k+1)}+\sum\limits^n_{k=0}{n\choose k}f^{(k)}g^{(n-k+1)}={n\choose 0}f^{(0)}g^{(n-0+1)}+\sum\limits^n_{k=1}{n\choose k-1}f^{(k)}g^{(n-k+1)}+\sum\limits^{n}_{k=1}{n\choose k}f^{(k)}g^{(n-k+1)}+{n\choose n+1}f^{(n+1)}g^{(n-n-1+1)}=f^{(0)}g^{(n+1)}+\sum\limits^n_{k=1}({n\choose k-1}+{n\choose k})f^{(k)}g^{(n-k+1)}+f^{(n+1)}g^{(0)}={n+1\choose 0}f^{(0)}g^{(n+1)} + \sum\limits^n_{k=1}{n+1\choose k}f^{(k)}g^{(n-k+1)}+{n+1\choose n+1}f^{(n+1)}g^{(0)}=\sum\limits^{n+1}_{k=0}{n+1\choose k}f^{(k)}g^{(n-k)}$ so $R_{n+1}$ is true.
Since $R_1$ is true and $R_n \Rightarrow R_{n+1}$, $\forall n \ge 1,R_n$ is true.


text:
Q: Transpose rules and algebra A, B and P are all squared matrices of the same order ($nXn$).
It is given that:
$PP^{T}=I$
$B^{T}B=I$
$A=P^{T}BP$
Which of the following is correct:
$(1) A=B$
$(2) AA^{T}=I$
$(3) (PB)^{-1}=(PB)^{T}$
I have started with (2). This is what I've done:
$(P^{T}BP)(P^{T}BP)$
$P^{T}BB^{T}P$
Something is not right. Can I say that
$B^{T}B=BB^{T}$ ?
According to the book, (2) and (3) are correct while (1) is not. I can't figure out why.

A: To prove that (1) is false I will write a counterexample in terms of linear transformations  instead of matrices. Let $P(x_1,x_2,\cdots,x_n)=(x_1,0,\cdots,0)$, $A=0$ and $B=I-P$. Then $A \neq B$ but $A=P^{T}BP$.
(2) follows from $AA^{T}=(P^{T}BP)(P^{T}BP)^{T}=I$ because $(MN)^{T}=N^{T}M^{T}$. [Observe that $P^{T}P=I$ and $BB^{T}=I$].  To prove (3) it is enough to show that $(PB)(PB)^{T}=I$ which is true since LHS $=B^{T}P^{T}PB=B^{T}B=I$.

A: Hint: If $U$ and $V$ are square matrices (of the same size) , then
$UV=I \iff VU=I.$


text:
Q: Issue with images in spreadsheet and App Script I have an issue with apps script when I insert the image in spreadsheet and then convert it to pdf. The image doesn't appear in the document pdf.
My code is:
here insert the image
libro=SpreadsheetApp.openById('XXXXXXXXXXXXXXXXX');
hojaX=Libro.getSheetByName('Test');
hojax.insertImage("http://test.com/imagen.jpg", 3, 71, 0, 0);

here  convert the spreadsheet in pdf
var file = DriveApp.getFileById('XXXXXXXXXXXXXXXXX').getAs('application/pdf').getBytes();

here attach to email to send
var attach = {fileName:'name.pdf',content:file, mimeType:'application/pdf'};

MailApp.sendEmail(test@test.com, "title", "message" {attachments:[attach]});

I can't fix, the pdf send without image, could you help me?
regards

A: Here's how to insert an image in App Script.
function myFunction() {
  var SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/abcdefghiklmnopqrstopwxyz/edit#gid=0';
   var SHEET_NAME = 'Sheet1';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'http://i.imgur.com/PnJTXjN.png'); //url of the image
  var binaryData = response.getContent();

  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1); //this puts the image in A1 of the cell
}

Here's how to convert Image to PDF and attach in your email courtesy of Amit Agarwal. When you run this code, a message will be sent to your mail with the pdf attached.
function convertImageToPDF() {

 var image = UrlFetchApp.fetch('http://i.imgur.com/DS6bVac.png');

  // grab its bytes and base64-encode them.
  var base64 = Utilities.base64Encode(image.getBlob().getBytes());
  var html = '<img src="data:image/png;base64,'+base64+'" />';

  // create a blob, convert to PDF
  var blob = Utilities.newBlob(html, MimeType.HTML).setName('myImage' + ".pdf");

  //save to Google Drive
   var file = {
    title: 'myImage.pdf',
    mimeType: 'application/pdf'
  };
   file = Drive.Files.insert(file,blob.getAs(MimeType.PDF));
  Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);

  //send to email as attached file
  MailApp.sendEmail("youremail@gmail.com", "Image to PDF", "", {
    attachments:blob.getAs(MimeType.PDF)
  });

}


text:
Q: How to smoothly animate current position with a custom LocationSource in Google Maps SDK? I am using a custom LocationSource that provides updates every 300+ ms.
Below you can observe that the coordinates updates are making the blue dot (current position) move in quite a shaky way (I was moving slow to make the effect more obvious):

How can I make the blue dot's movement smoother, similar to the one in the Google Maps application? Less left-right shakes and smoother forward movement instead of "jumping" from point A to point B would be awesome.
There are some answers that recommend animating the camera or using an interpolator to animate movement between 2 known positions over a preset timeframe but that doesn't really apply to my situation.

A: Use SnapToRoad Api to get correct co-ordinates from one location to other location.

 public void animateMarker(int startPositionId, final LatLng toPosition, Marker marker, final boolean hideMarke) {

        final long start = SystemClock.uptimeMillis();
        Projection proj = routeMap.getProjection();
        Point startPoint = proj.toScreenLocation(marker.getPosition());
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1000;

        final Interpolator interpolator = new LinearInterpolator();
        runnable = new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;

                float t = interpolator.getInterpolation((float) elapsed
                        / duration);

                Log.d("run:t", String.valueOf(t));

                double lng = t * toPosition.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * toPosition.latitude + (1 - t)
                        * startLatLng.latitude;

                Log.d("run:lat", String.valueOf(lat));
                Log.d("run:lng", String.valueOf(lng));
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    // Post again 16ms later.

                    handlerSetPosition.postDelayed(this, 8);

                } else {
                    if (hideMarke) {
                        marker.setVisible(false);
                    } else {
                        marker.setVisible(true);
                        pointId = startPositionId + 1;
                        getSnappedRout(pointId);

                    }
                }
            }
        };
        handlerSetPosition.post(runnable);

    }


text:
Q: How to change the data type of a column from STRING to TEXT in ORM Symfony 4? I have my table information defined via the annotation of the entity. So I would like to change the following column to a TEXT instead of a STRING. So I had this:
    /**
     * @ORM\Column(type="string", length=255)
     */
    private $category;

And I changed it to this:
    /**
     * @ORM\Column(type="text")
     */
    private $category;

I expected it to become a TEXT, so after migrating I checked my database and it says it's a LONGTEXT. I have no idea how this is possible, but before referting my migrations, I would like to know how to make it a TEXT and not a LONGTEXT.
EDIT: I'm looking inside the migration file and I see this:
$this->addSql('ALTER TABLE cabinet CHANGE category category LONGTEXT NOT NULL');
I never typed LONGTEXT so I have no clue where Doctrine is getting that from.

A: The answer seems to be to give the length of TEXT as well (I thought it was defined as a fixed value), so instead of @ORM\Column(type="text") you should do @ORM\Column(type="text", length=65535). I was able to find this answer because of this other SO question.

A: If you want to change with migrations you need notate that converting to text will base on the current column length;
$table = $schema->getTable("tablename");
$column = $table->getColumn("columnname");
 /** There you need set size of text that you want to use
  *  To TINYTEXT => length =  0 - 255
  *  To TEXT => length = 256 - 65535
  *  To MEDIUMTEXT = 65536 - 16777215
  **/
$column->setLength('65535');
$column->setType(Type::getType(Types::TEXT))

It will change current type only if current type is not been Types::TEXT. If your text is tinytext and you need to set it to text, you need first to change type to string, set length and only then set it back to text.


text:
Q: Debug exceptions in compiled GWT? I was getting a NoSuchElementException in my GWT and I had no idea where it came from.
I've explored plenty of hints on how to get stack traces for exceptions in GWT, but got none to work. My solution's below (though I welcome any easier ways!)

A: Note: I'm on OS X Yosemite, running chrome version 45.0.2454.85 (64-bit), using GWT 2.7.0. I don't know if this will work for anything else.
My solution was eventually to put this code in, at the beginning of my onModuleLoad function:
native void openDebuggerWhenExceptionsCreated() /*-{
    window['captureStackTrace'] = function(throwable, reference) {
        debugger;
    };
}-*/;

public void onModuleLoad() {
    openDebuggerWhenExceptionsCreated();
    ...

Then run it in compiled javascript mode (with -style PRETTY), open the app in chrome, open the console (for me on mac, command + option + i) and then reproduce the error. If it hits the debugger; statement while the console is open then chrome's debugger will break there.
This works because when GWT creates an exception, it calls the captureStackTrace() function, which we replace here. It's still a mystery to me why that function existed if it does nothing, but either way, overwriting it seemed to be safe.
That window['captureStackTrace'] is needed instead of just captureStackTrace because GWT actually changes the name of its own captureStackTrace if it sees us using a variable by that name.


text:
Q: Windows 7 keeps highlighting a particular item in start menu Windows 7 highlights newly installed items in start menu. When I click/run the newly installed item from the start menu, windows removes the highlight. I am fine with this behavior.
But sometimes windows keeps highlighting the new item even after I click/run it for many times. And windows keeps highlighting it for DAYS! This is annoying.
I don't want to turn off highlighting completely. What is wrong with this particular item? How do I turn off highlight for this particular item?


text:
Q: Compiling .scss file with Compass Compiler gets me a strange error I am working on a .scss file and when I compile with Compass I get this error:
unrecognized file type: png

It claims that this is the line that is wrong:
    $factor : image-height(sprite-path($ico-retina-sprites)) / image-height(sprite-path($ico-sprites));

I am pretty sure that there is nothing wrong with the code because other people are able to compile their projects just fine, so I was wondering if you knew of another reason why this could happen (ie installation of Ruby version or something)?
Thanks!

A: I figured out the answer. It don't entirely know why this solved it, but I just did a hard reset my local repository and cleared my compass cache and the error went away!


text:
Q: Grunt LiveReload is really slow This is probably an affect of my inefficient setup and not a problem with grunt/livereload.
Here's my watch test in my grunfile.js:
watch: {
    images: {
        files: ['images/**/*.{png,jpg,gif}', 'images/*.{png,jpg,gif}'],
        tasks: ['imagemin'],
        options: {
            spawn: false
        }
    },
    js: {
        files: ['js/*.js','js/**/*.js'],
        tasks: ['jshint'],
        options: {
            spawn: false
        }
    },
    svgs: {
        files: ['images/*.svg','images/**/*.svg'],
        task: ['svgmin'],
        options: {
            span: false
        }
    },
    scss: {
        files: ['sass/*.scss', 'sass/**/*.scss'],
        tasks: ['sass','autoprefixer'],
        sourceComments: 'normal',
        options: {
            nospawn: true,
            livereload: true
        }
    }
},

This will recompile my SASS and the reload the page, but it takes 5-6 seconds to complete the CSS compilation, then it does a full page refresh, instead of just reloading the CSS file that changed.
So my questions are this:

*

*How do I keep it from taking so long to compile the SASS and refresh the page, or am I just being to picky, and this is an inherit part of grunt?

*How keep if from reloading the entire page, and just reload the CSS file that changed from my SASS compilation?

A: Check my other answer: Fastest way to compile SCSS (Compass) + refresh the browser?
grunt-contrib-sass uses Ruby sass which is very slow, it has nothing to do with grunt itself.
Use grunt-sass instead, it uses libsass which is lighting fast c implementation of sass.
Read this article:
http://benfrain.com/lightning-fast-sass-compiling-with-libsass-node-sass-and-grunt-sass/

A: The best solution is to move from grunt-contrib-sass to grunt-sass, but if you don't have much time to fix this, i think, you should move your 'autoprefixer' task from watch section to deploy section.
scss: {
    files: ['sass/*.scss', 'sass/**/*.scss'],
    tasks: ['sass',
    sourceComments: 'normal',
    options: {
        nospawn: true,
        livereload: true
    }
}

In my project this trick help me, because 'autoprefixer' task works very slowly

A: Or you could use a live reloader tool, like fast-live-reload, in combination with the ruby sass compiler.
Note that they offer their own watcher that is very fast (e.g. for compass run: compass watch).
Disclaimer: I am the creator of fast-live-reload.


text:
Q: Displaying more long column names Is there a way to display more characters in a string column of a data table in Rstudio.
For instance:
library(data.table)

dt <- data.table(StringVar1 = c('This is a very very very very very very very very very very very very very very very very long string'),
                 StringVar1 = c('This is a short string'))

View(dt)

The output will be:

How can I display the entire content of StringVar1?


text:
Q: ( maven 2.0.5 ) Failed to activate local (project-level) build profiles: Cannot parse profiles.xml while trying to do mvn -e clean install -Dmaven.test.skip=true -Denv=$ENVIRONMENT
for a webapp project on my VM, i get error:
Maven version: 2.0.5
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).

Project ID: unknown:web

Reason: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web

[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.reactor.MavenExecutionException: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.DefaultMaven.getProjects(DefaultMaven.java:373)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:286)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:123)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:272)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.project.ProjectBuildingException: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.project.DefaultMavenProjectBuilder.assembleLineage(DefaultMavenProjectBuilder.java:1025)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildInternal(DefaultMavenProjectBuilder.java:697)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildFromSourceFileInternal(DefaultMavenProjectBuilder.java:431)
    at org.apache.maven.project.DefaultMavenProjectBuilder.build(DefaultMavenProjectBuilder.java:195)
    at org.apache.maven.DefaultMaven.getProject(DefaultMaven.java:523)
    at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:455)
    at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:499)
    at org.apache.maven.DefaultMaven.getProjects(DefaultMaven.java:359)
    ... 11 more
Caused by: org.apache.maven.profiles.activation.ProfileActivationException: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.project.DefaultMavenProjectBuilder.loadProjectExternalProfiles(DefaultMavenProjectBuilder.java:1296)
    at org.apache.maven.project.DefaultMavenProjectBuilder.assembleLineage(DefaultMavenProjectBuilder.java:1017)
    ... 18 more
Caused by: org.codehaus.plexus.util.xml.pull.XmlPullParserException: expected = after attribute name (position: START_DOCUMENT seen ...         http://maven.apache.org/xsd/maven-4.0.0.xsd" profilesXml>... @5:80)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseAttribute(MXParser.java:2001)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseStartTag(MXParser.java:1796)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseProlog(MXParser.java:1476)
    at org.codehaus.plexus.util.xml.pull.MXParser.nextImpl(MXParser.java:1392)
    at org.codehaus.plexus.util.xml.pull.MXParser.next(MXParser.java:1090)
    at org.apache.maven.profiles.io.xpp3.ProfilesXpp3Reader.read(ProfilesXpp3Reader.java:1187)
    at org.apache.maven.profiles.io.xpp3.ProfilesXpp3Reader.read(ProfilesXpp3Reader.java:1201)
    at org.apache.maven.profiles.DefaultMavenProfilesBuilder.buildProfiles(DefaultMavenProfilesBuilder.java:77)
    at org.apache.maven.project.DefaultMavenProjectBuilder.loadProjectExternalProfiles(DefaultMavenProjectBuilder.java:1268)
    ... 19 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Mon May 06 18:57:37 EDT 2013
[INFO] Final Memory: 2M/57M
[INFO] ------------------------------------------------------------------------
Building Gryphon...
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).

Project ID: unknown:web

Reason: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web

[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.reactor.MavenExecutionException: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.DefaultMaven.getProjects(DefaultMaven.java:373)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:286)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:123)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:272)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.project.ProjectBuildingException: Failed to activate local (project-level) build profiles: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.project.DefaultMavenProjectBuilder.assembleLineage(DefaultMavenProjectBuilder.java:1025)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildInternal(DefaultMavenProjectBuilder.java:697)
    at org.apache.maven.project.DefaultMavenProjectBuilder.buildFromSourceFileInternal(DefaultMavenProjectBuilder.java:431)
    at org.apache.maven.project.DefaultMavenProjectBuilder.build(DefaultMavenProjectBuilder.java:195)
    at org.apache.maven.DefaultMaven.getProject(DefaultMaven.java:523)
    at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:455)
    at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:499)
    at org.apache.maven.DefaultMaven.getProjects(DefaultMaven.java:359)
    ... 11 more
Caused by: org.apache.maven.profiles.activation.ProfileActivationException: Cannot parse profiles.xml resource from directory: /extra/co/workspace/vm-devqa01-g/web
    at org.apache.maven.project.DefaultMavenProjectBuilder.loadProjectExternalProfiles(DefaultMavenProjectBuilder.java:1296)
    at org.apache.maven.project.DefaultMavenProjectBuilder.assembleLineage(DefaultMavenProjectBuilder.java:1017)
    ... 18 more
Caused by: org.codehaus.plexus.util.xml.pull.XmlPullParserException: expected = after attribute name (position: START_DOCUMENT seen ...         http://maven.apache.org/xsd/maven-4.0.0.xsd" profilesXml>... @5:80)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseAttribute(MXParser.java:2001)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseStartTag(MXParser.java:1796)
    at org.codehaus.plexus.util.xml.pull.MXParser.parseProlog(MXParser.java:1476)
    at org.codehaus.plexus.util.xml.pull.MXParser.nextImpl(MXParser.java:1392)
    at org.codehaus.plexus.util.xml.pull.MXParser.next(MXParser.java:1090)
    at org.apache.maven.profiles.io.xpp3.ProfilesXpp3Reader.read(ProfilesXpp3Reader.java:1187)
    at org.apache.maven.profiles.io.xpp3.ProfilesXpp3Reader.read(ProfilesXpp3Reader.java:1201)
    at org.apache.maven.profiles.DefaultMavenProfilesBuilder.buildProfiles(DefaultMavenProfilesBuilder.java:77)
    at org.apache.maven.project.DefaultMavenProjectBuilder.loadProjectExternalProfiles(DefaultMavenProjectBuilder.java:1268)
    ... 19 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Mon May 06 18:57:38 EDT 2013
[INFO] Final Memory: 2M/57M
[INFO] ------------------------------------------------------------------------

A: appended:
<profilesXml xmlns="http://maven.apache.org/PROFILES/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/PROFILES/1.0.0 http://maven.apache.org/xsd/profiles-1.0.0.xsd">
<profiles>
<profile>
...
</profile>
</profiles>
</profilesXml>

its working now


text:
Q: How to structure my own client side functions in meteor? Having started with meteor.js, I am already using boilerplates to structure my templates, my client and serverside and shared code.
What I do not know yet is:

*

*Where to save my own Javascript functions, that might be reused?

*How to write the files which contain functions that might be reused, while avoiding name conflicts?

I know there are many ways in Javascript to write a function or a method.

*

*Simply a function declaration

*An objetc with a function

*A modelation of static functions

Code Snippet for static functions:
function MyClass(){}
MyClass.myStaticFunction = function(){};

A: It is important to note that all Javascript files in the /client folder will be loaded in by the client. All of the files will be load in depth-first, then alphabetical order. They are also wrapped in a function so that each file will not populate the global scope. If your file has function a() {} then a is only callable from within the file.
If you instead, change that to this.a = function() {}, a is callable from any other file that is loaded after this file or has code that runs after initial load.
For JavaScript files that will be reused by the client, I recommend structuring your /client folder so that common code gets loaded first, and that you use the this.functionName = function() {} style.