Programs & Examples On #Compressed folder

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

LINQ order by null column where order is ascending and nulls should be last

I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:

var newList = objList.Where(m=>m.Column != null)
                     .OrderBy(m => m.Column)
                     .Concat(objList.where(m=>m.Column == null));

AngularJS ngClass conditional

There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.

<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>

Happy Coding, Nimantha Perera

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

How to call multiple JavaScript functions in onclick event?

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

What are unit tests, integration tests, smoke tests, and regression tests?

  • Unit test: an automatic test to test the internal workings of a class. It should be a stand-alone test which is not related to other resources.
  • Integration test: an automatic test that is done on an environment, so similar to unit tests but with external resources (db, disk access)
  • Regression test: after implementing new features or bug fixes, you re-test scenarios which worked in the past. Here you cover the possibility in which your new features break existing features.
  • Smoke testing: first tests on which testers can conclude if they will continue testing.

How can I run Tensorboard on a remote server?

For anyone who must use the ssh keys (for a corporate server).

Just add -i /.ssh/id_rsa at the end.

$ ssh -N -f -L localhost:8211:localhost:6007 myname@servername -i /.ssh/id_rsa

what is trailing whitespace and how can I handle this?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after pass:

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

Plotting in a non-blocking way with Matplotlib

Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot command that was not there when I was just doing show:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.

Here's the code that worked for me:

def plt_show():
    '''Text-blocking version of plt.show()
    Use this instead of plt.show()'''
    plt.draw()
    plt.pause(0.001)
    input("Press enter to continue...")
    plt.close()

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

Find all packages installed with easy_install/pip?

If Debian behaves like recent Ubuntu versions regarding pip install default target, it's dead easy: it installs to /usr/local/lib/ instead of /usr/lib (apt default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

I am an ArchLinux user and as I experimented with pip I met this same problem. Here's how I solved it in Arch.

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

Key here is /usr/lib/python2.7/site-packages, which is the directory pip installs to, YMMV. pacman -Qo is how Arch's pac kage man ager checks for ownership of the file. No package is part of the return it gives when no package owns the file: error: No package owns $FILENAME. Tricky workaround: I'm querying about __init__.py because pacman -Qo is a little bit ignorant when it comes to directories :(

In order to do it for other distros, you have to find out where pip installs stuff (just sudo pip install something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S) and what is the "no package owns that path" return (Debian/Ubuntu is no path found matching pattern). Debian/Ubuntu users, beware: dpkg -S will fail if you give it a symbolic link. Just resolve it first by using realpath. Like this:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora users can try (thanks @eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

How do I line up 3 divs on the same row?

here are two samples: http://jsfiddle.net/H5q5h/1/

one uses float:left and a wrapper with overflow:hidden. the wrapper ensures the sibling of the wrapper starts below the wrapper.

the 2nd one uses the more recent display:inline-block and wrapper can be disregarded. but this is not generally supported by older browsers so tread lightly on this one. also, any white space between the items will cause an unnecessary "margin-like" white space on the left and right of the item divs.

How to make a gui in python

Just look at the python GUI programming options at http://wiki.python.org/moin/GuiProgramming. But, Consider Wxpython for your GUI application as it is cross platform. And,from above link you could also get some IDE to work upon.

Align two divs horizontally side by side center to the page using bootstrap css

The response provided by Ranveer (second answer above) absolutely does NOT work.

He says to use col-xx-offset-#, but that is not how offsets are used.

If you wasted your time trying to use col-xx-offset-#, as I did based on his answer, the solution is to use offset-xx-#.

Amazon Interview Question: Design an OO parking lot

you would need a parking lot, that holds a multi-dimensional array (specified in the constructor) of a type "space". The parking lot can keep track of how many spaces are taken via calls to functions that fill and empty spaces.Space can hold an enumerated type that tells what kind of space it is. Space also has a method taken(). for the valet parking, just find the first space thats open and put the car there. You will also need a Car object to put in the space, that holds whether it is a handicapped, compact, or regular vehicle.


class ParkingLot
{
    Space[][] spaces;

    ParkingLot(wide, long); // constructor

    FindOpenSpace(TypeOfCar); // find first open space where type matches
}

enum TypeOfSpace = {compact, handicapped, regular };
enum TypeOfCar = {compact, handicapped, regular };

class Space
{
    TypeOfSpace type;
    bool empty;
    // gets and sets here
    // make sure car type
}

class car
{
    TypeOfCar type;
}

Java: Detect duplicates in ArrayList?

Improved code to return the duplicate elements

  • Can find duplicates in a Collection
  • return the set of duplicates
  • Unique Elements can be obtained from the Set

public static <T> List getDuplicate(Collection<T> list) {

    final List<T> duplicatedObjects = new ArrayList<T>();
    Set<T> set = new HashSet<T>() {
    @Override
    public boolean add(T e) {
        if (contains(e)) {
            duplicatedObjects.add(e);
        }
        return super.add(e);
    }
    };
   for (T t : list) {
        set.add(t);
    }
    return duplicatedObjects;
}


public static <T> boolean hasDuplicate(Collection<T> list) {
    if (getDuplicate(list).isEmpty())
        return false;
    return true;
}

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

afunc<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

What is the difference between Integer and int in Java?

Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.

What is a mutex?

When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.

The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.

How to use them is language specific, but is often (if not always) based on a operating system mutex.

Some languages doesn't need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).

How to remove "Server name" items from history of SQL Server Management Studio

In Windows Server 2008 standard with SQL Express 2008, the "SqlStudio.bin" file lives here:

%UserProfile%\Microsoft\Microsoft SQL Server\100\Tools\Shell\

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Replacing some characters in a string with another character

read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter

^use as many of these as you need, and you can make your own BASIC encryption

How to create RecyclerView with multiple view type?

Create different ViewHolder for different layout

enter image description here
RecyclerView can have any number of viewholders you want but for better readability lets see how to create one with two ViewHolders.

It can be done in three simple steps

  1. Override public int getItemViewType(int position)
  2. Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  3. Populate View based on the itemViewType in onBindViewHolder() method

Here is a small code snippet

public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

   private static final int LAYOUT_ONE= 0;
   private static final int LAYOUT_TWO= 1;

   @Override
   public int getItemViewType(int position)
   {
      if(position==0)
        return LAYOUT_ONE;
      else
        return LAYOUT_TWO;
   }

   @Override
   public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

      View view =null;
      RecyclerView.ViewHolder viewHolder = null;

      if(viewType==LAYOUT_ONE)
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
          viewHolder = new ViewHolderOne(view);
      }
      else
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
          viewHolder= new ViewHolderTwo(view);
      }

      return viewHolder;
   }

   @Override
   public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

      if(holder.getItemViewType()== LAYOUT_ONE)
      {
            // Typecast Viewholder 
            // Set Viewholder properties 
            // Add any click listener if any 
      }
      else {

        ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
        vaultItemHolder.name.setText(displayText);
        vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
            .......
           }
         });

       }

   }

  //****************  VIEW HOLDER 1 ******************//

   public class ViewHolderOne extends RecyclerView.ViewHolder {

      public TextView name;

      public ViewHolderOne(View itemView) {
         super(itemView);
         name = (TextView)itemView.findViewById(R.id.displayName);
     }
   }


   //****************  VIEW HOLDER 2 ******************//

   public class ViewHolderTwo extends RecyclerView.ViewHolder{

      public ViewHolderTwo(View itemView) {
         super(itemView);

        ..... Do something
      }
   }
}

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

Lets see one example to prove my point. If you want to show two layout at alternate positions do this

@Override
public int getItemViewType(int position)
{
   if(position%2==0)       // Even position 
     return LAYOUT_ONE;
   else                   // Odd position 
     return LAYOUT_TWO;
}

Relevant Links:

Check out the project where I have implemented this

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

I think the least intrusive way of doing this is as follows:

  1. Check if the user-agent is that of an iPhone/iPod Touch
  2. Check for an appInstalled cookie
  3. If the cookie exists and is set to true, set window.location to your-uri:// (or do the redirect server side)
  4. If the cookie doesn't exist, open a "Did you know Your Site Name has an iPhone application?" modal with a "Yep, I've already got it", "Nope, but I'd love to try it", and "Leave me alone" button.
    1. The "Yep" button sets the cookie to true and redirects to your-uri://
    2. The "Nope" button redirects to "http://itunes.com/apps/yourappname" which will open the App Store on the device
    3. The "Leave me alone" button sets the cookie to false and closes the modal

The other option I've played with but found a little clunky was to do the following in Javascript:

setTimeout(function() {
  window.location = "http://itunes.com/apps/yourappname";
}, 25);

// If "custom-uri://" is registered the app will launch immediately and your
// timer won't fire. If it's not set, you'll get an ugly "Cannot Open Page"
// dialogue prior to the App Store application launching
window.location = "custom-uri://";

How to leave space in HTML

As others already answered, $nbsp; will output no-break space character. Here is w3 docs for &nbsp and others.

However there is other ways to do it and nowdays i would prefer using CSS stylesheets. There is also w3c tutorials for beginners.

With CSS you can do it like this:

<html>
    <head>
        <title>CSS test</title>
        <style type="text/css">
            p { word-spacing: 40px; }
        </style>
    </head>
    <body>
        <p>Hello World! Enough space between words, what do you think about it?</p>
    </body>
</html>

What does %5B and %5D in POST requests stand for?

Not least important is why these symbols occur in url. See https://www.php.net/manual/en/function.parse-str.php#76792, specifically:

parse_str('foo[]=1&foo[]=2&foo[]=3', $bar);

the above produces:

$bar = ['foo' => ['1', '2', '3'] ];

and what is THE method to separate query vars in arrays (in php, at least).

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

Mailx send html message

I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:

mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html

This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.

Instead of relying on hacking the subject line, I now use a bash subshell:

(
    echo -e "Content-Type: text/html\n"
    cat mail.html
 ) | mail -s "The Subject" -t [email protected]

And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by @dogbane:

(
    echo "To: [email protected]"
    echo "Subject: The Subject"
    echo "Content-Type: text/html"
    echo
    cat mail.html
) | sendmail -t

The use of bash subshells avoids having to create a temporary file.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

What is the difference between procedural programming and functional programming?

To Understand the difference, one needs to to understand that "the godfather" paradigm of both procedural and functional programming is the imperative programming.

Basically procedural programming is merely a way of structuring imperative programs in which the primary method of abstraction is the "procedure." (or "function" in some programming languages). Even Object Oriented Programming is just another way of structuring an imperative program, where the state is encapsulated in objects, becoming an object with a "current state," plus this object has a set of functions, methods, and other stuff that let you the programmer manipulate or update the state.

Now, in regards to functional programming, the gist in its approach is that it identifies what values to take and how these values should be transferred. (so there is no state, and no mutable data as it takes functions as first class values and pass them as parameters to other functions).

PS: understanding every programming paradigm is used for should clarify the differences between all of them.

PSS: In the end of the day, programming paradigms are just different approaches to solving problems.

PSS: this quora answer has a great explanation.

How to make HTTP Post request with JSON body in Swift

    var request = URLRequest(url: URL(string:  "your URL")!)
    request.httpMethod = "POST"


    let postString =  String(format: "email=%@&lang=%@", arguments: [txt_emailVirify.text!, language!])
    print(postString)

    emailString = txt_emailVirify.text!

    request.httpBody = postString.data(using: .utf8)
    request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")


    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil
            else
        {
            print("error=\(String(describing: error))")
            return
        }

        do
        {

            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
            print(dictionary)

            let status = dictionary.value(forKey: "status") as! String
            let sts = Int(status)
            DispatchQueue.main.async()
                {
                    if sts == 200
                    {
                        print(dictionary)


                    }
                    else
                    {
                       self.alertMessageOk(title: self.Alert!, message: dictionary.value(forKey: "message") as! String)


                    }
            }
        }
        catch
        {
            print(error)
        }

    }
    task.resume()

.bashrc: Permission denied

If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:

nano ~/.bashrc

or

gedit ~/.bashrc

And in general, for any type of file:

xdg-open ~/.bashrc

Writing only ~/.bashrc in terminal, this will try to execute that file, but .bashrc file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:

source ~/.bashrc

or simple:

. ~/.bashrc 

Count the number of all words in a string

require(stringr)
str_count(x,"\\w+")

will be fine with double/triple spaces between words

All other answers have issues with more than one space between the words.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

I was trying to do this but having problems with Kjetil Watnedal's solution because I don't use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom IComparer.

My solution ended up like this:

Given an IQueryable query like so:

List<DATA__Security__Team> teams = TeamManager.GetTeams();
var query = teams.Where(team => team.ID < 10).AsQueryable();

And given a run-time sort field argument:

string SortField; // Set at run-time to "Name"

The dynamic OrderBy looks like so:

query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));

And that's using a little helper method called GetReflectedPropertyValue():

public static string GetReflectedPropertyValue(this object subject, string field)
{
    object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
    return reflectedValue != null ? reflectedValue.ToString() : "";
}

One last thing - I mentioned that I wanted the OrderBy to use custom IComparer - because I wanted to do Natural sorting.

To do that, I just alter the OrderBy to:

query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());

See this post for the code for NaturalSortComparer().

Get unique values from a list in python

def setlist(lst=[]):
   return list(set(lst))

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

How to count days between two dates in PHP?

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Source: http://www.php.net/manual/en/datetime.diff.php

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Changing navigation title programmatically

and also if you will try to create Navigation Bar manually this code will help you

func setNavBarToTheView() {
    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64.0))
    self.view.addSubview(navBar);
    let navItem = UINavigationItem(title: "Camera");
    let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(CameraViewController.onClickBack));
    navItem.leftBarButtonItem = doneItem;
    navBar.setItems([navItem], animated: true);
}

get all the images from a folder in php

This answer is specific for WordPress:

$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );

$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';

$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();

foreach ( $image_paths as $image ) {
    $image_names[] = str_replace( $media_dir, '', $image );
    $image_urls[] = str_replace( $media_dir, $media_url, $image );
}

// --- You now have:

// $image_paths ... list of absolute file paths 
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg

// $image_urls ... list of absolute file URLs 
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg

// $image_names ... list of filenames only
// e.g. sample.jpg

Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:

From Uploads directory:

// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );

From Parent-Theme

// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );

From Child-Theme

// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );

iOS - Calling App Delegate method from ViewController

Sounds like you just need a UINavigationController setup?

You can get the AppDelegate anywhere in the program via

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];

In your app delegate you should have your navigation controller setup, either via IB or in code.

In code, assuming you've created your 'House overview' viewcontroller already it would be something like this in your AppDelegate didFinishLaunchingWithOptions...

self.m_window = [[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds] autorelease];
self.m_navigationController = [[[UINavigationController alloc]initWithRootViewController:homeViewController]autorelease];
[m_window addSubview:self.m_navigationController.view];

After this you just need a viewcontroller per 'room' and invoke the following when a button click event is picked up...

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];
[blah.m_navigationController pushViewController:newRoomViewController animated:YES];

I've not tested the above code so forgive any syntax errors but hope the pseudo code is of help...

What characters are forbidden in Windows and Linux directory names?

In Windows 10 (2019), the following characters are forbidden by an error when you try to type them:

A file name can't contain any of the following characters:

\ / : * ? " < > |

Android Studio - How to increase Allocated Heap Size

Go in the Gradle Scripts -> local.properties and paste this

`org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m`

, if you want to change it to 512. Hope it works !

How do Python's any and all functions work?

How do Python's any and all functions work?

any and all take iterables and return True if any and all (respectively) of the elements are True.

>>> any([0, 0.0, False, (), '0']), all([1, 0.0001, True, (False,)])
(True, True)            #   ^^^-- truthy non-empty string
>>> any([0, 0.0, False, (), '']), all([1, 0.0001, True, (False,), {}])
(False, False)                                                #   ^^-- falsey

If the iterables are empty, any returns False, and all returns True.

>>> any([]), all([])
(False, True)

I was demonstrating all and any for students in class today. They were mostly confused about the return values for empty iterables. Explaining it this way caused a lot of lightbulbs to turn on.

Shortcutting behavior

They, any and all, both look for a condition that allows them to stop evaluating. The first examples I gave required them to evaluate the boolean for each element in the entire list.

(Note that list literal is not itself lazily evaluated - you could get that with an Iterator - but this is just for illustrative purposes.)

Here's a Python implementation of any and all:

def any(iterable):
    for i in iterable:
        if i:
            return True
    return False # for an empty iterable, any returns False!

def all(iterable):
    for i in iterable:
        if not i:
            return False
    return True  # for an empty iterable, all returns True!

Of course, the real implementations are written in C and are much more performant, but you could substitute the above and get the same results for the code in this (or any other) answer.

all

all checks for elements to be False (so it can return False), then it returns True if none of them were False.

>>> all([1, 2, 3, 4])                 # has to test to the end!
True
>>> all([0, 1, 2, 3, 4])              # 0 is False in a boolean context!
False  # ^--stops here!
>>> all([])
True   # gets to end, so True!

any

The way any works is that it checks for elements to be True (so it can return True), then it returnsFalseif none of them wereTrue`.

>>> any([0, 0.0, '', (), [], {}])     # has to test to the end!
False
>>> any([1, 0, 0.0, '', (), [], {}])  # 1 is True in a boolean context!
True   # ^--stops here!
>>> any([])
False   # gets to end, so False!

I think if you keep in mind the short-cutting behavior, you will intuitively understand how they work without having to reference a Truth Table.

Evidence of all and any shortcutting:

First, create a noisy_iterator:

def noisy_iterator(iterable):
    for i in iterable:
        print('yielding ' + repr(i))
        yield i

and now let's just iterate over the lists noisily, using our examples:

>>> all(noisy_iterator([1, 2, 3, 4]))
yielding 1
yielding 2
yielding 3
yielding 4
True
>>> all(noisy_iterator([0, 1, 2, 3, 4]))
yielding 0
False

We can see all stops on the first False boolean check.

And any stops on the first True boolean check:

>>> any(noisy_iterator([0, 0.0, '', (), [], {}]))
yielding 0
yielding 0.0
yielding ''
yielding ()
yielding []
yielding {}
False
>>> any(noisy_iterator([1, 0, 0.0, '', (), [], {}]))
yielding 1
True

The source

Let's look at the source to confirm the above.

Here's the source for any:

static PyObject *
builtin_any(PyObject *module, PyObject *iterable)
{
    PyObject *it, *item;
    PyObject *(*iternext)(PyObject *);
    int cmp;

    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;
    iternext = *Py_TYPE(it)->tp_iternext;

    for (;;) {
        item = iternext(it);
        if (item == NULL)
            break;
        cmp = PyObject_IsTrue(item);
        Py_DECREF(item);
        if (cmp < 0) {
            Py_DECREF(it);
            return NULL;
        }
        if (cmp > 0) {
            Py_DECREF(it);
            Py_RETURN_TRUE;
        }
    }
    Py_DECREF(it);
    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }
    Py_RETURN_FALSE;
}

And here's the source for all:

static PyObject *
builtin_all(PyObject *module, PyObject *iterable)
{
    PyObject *it, *item;
    PyObject *(*iternext)(PyObject *);
    int cmp;

    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;
    iternext = *Py_TYPE(it)->tp_iternext;

    for (;;) {
        item = iternext(it);
        if (item == NULL)
            break;
        cmp = PyObject_IsTrue(item);
        Py_DECREF(item);
        if (cmp < 0) {
            Py_DECREF(it);
            return NULL;
        }
        if (cmp == 0) {
            Py_DECREF(it);
            Py_RETURN_FALSE;
        }
    }
    Py_DECREF(it);
    if (PyErr_Occurred()) {
        if (PyErr_ExceptionMatches(PyExc_StopIteration))
            PyErr_Clear();
        else
            return NULL;
    }
    Py_RETURN_TRUE;
}

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

How to set up default schema name in JPA configuration?

For those who uses last versions of spring boot will help this:

.properties:

spring.jpa.properties.hibernate.default_schema=<name of your schema>

.yml:

spring:
    jpa:
        properties:
            hibernate:
                default_schema: <name of your schema>

How to set up gradle and android studio to do release build?

This is a procedure to configure run release version

1- Change build variants to release version.

enter image description here

2- Open project structure. enter image description here

3- Change default config to $signingConfigs.release enter image description here

Transpose/Unzip Function (inverse of zip)?

Since it returns tuples (and can use tons of memory), the zip(*zipped) trick seems more clever than useful, to me.

Here's a function that will actually give you the inverse of zip.

def unzip(zipped):
    """Inverse of built-in zip function.
    Args:
        zipped: a list of tuples

    Returns:
        a tuple of lists

    Example:
        a = [1, 2, 3]
        b = [4, 5, 6]
        zipped = list(zip(a, b))

        assert zipped == [(1, 4), (2, 5), (3, 6)]

        unzipped = unzip(zipped)

        assert unzipped == ([1, 2, 3], [4, 5, 6])

    """

    unzipped = ()
    if len(zipped) == 0:
        return unzipped

    dim = len(zipped[0])

    for i in range(dim):
        unzipped = unzipped + ([tup[i] for tup in zipped], )

    return unzipped

Error ITMS-90717: "Invalid App Store Icon"

I was able to get around the Mac Sierra OS issue by duplicating the file, dragging the new file onto my desktop, open in preview, then click the export option (in the File menu) , then the option to save it without “alpha” comes up

How to use lodash to find and return an object from Array?

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

savedViews.find(el => el.description === view)

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

How do I edit a file after I shell to a Docker container?

You can open existing file with

cat filename.extension

and copy all the existing text on clipboard.

Then delete old file with

rm filename.extension

or rename old file with

mv old-filename.extension new-filename.extension

Create new file with

cat > new-file.extension

Then paste all text copied on clipboard, press Enter and exit with save by pressing ctrl+z. And voila no need to install any kind of editors.

How would I create a UIAlertView in Swift?

Here is a funny example in Swift:

private func presentRandomJoke() {
  if let randomJoke: String = jokesController.randomJoke() {
    let alertController: UIAlertController = UIAlertController(title:nil, message:randomJoke, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title:"Done", style:UIAlertActionStyle.Default, handler:nil))
    presentViewController(alertController, animated:true, completion:nil)
  }
}

Fixed positioning in Mobile Safari

This fixed position div can be achieved in just 2 lines of code which moves the div on scroll to the bottom of the page.

window.onscroll = function() {
  document.getElementById('fixedDiv').style.top =
     (window.pageYOffset + window.innerHeight - 25) + 'px';
};

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

How do I compile a .c file on my Mac?

You can use gcc, in Terminal, by doing gcc -c tat.c -o tst

however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from http://developer.apple.com

Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...

http://connect.apple.com/cgi-bin/WebObjects/MemberSite.woa/wo/5.1.17.2.1.3.3.1.0.1.1.0.3.3.3.3.1

How to get controls in WPF to fill available space?

Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():

  • Measure() determines the size of the panel and each of its children
  • Arrange() determines the rectangle where each control renders

The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.

The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.

A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.

You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().

See this article for a simple example.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

i have found that similar issue on my system, and that was from skype installed before xampp installed. i got similar error. for fixing the error i followed these,

  1. logged out to skype for a while ,
  2. restarted apache from xampp control panel,
  3. checked on browser, whether it worked or not, by http://localhost/
  4. got it worked,
  5. signed in again to skype,
  6. all working great, as simple as that

i wasn't need nothing to install or uninstall, and this worked for me in less then 1 minute.

cheers

Why is __dirname not defined in node REPL?

Though its not the solution to this problem I would like to add it as it may help others.

You should have two underscores before dirname, not one underscore (__dirname not _dirname).

NodeJS Docs

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

How to set default font family in React Native?

For React Native 0.56.0+ check if defaultProps is defined first:

Text.defaultProps = Text.defaultProps || {}

Then add:

Text.defaultProps.style =  { fontFamily: 'some_font' }

Add the above in the constructor of the App.js file (or any root component you have).

In order to override the style you can create a style object and spread it then add your additional style (e.g { ...baseStyle, fontSize: 16 })

What is the difference between ( for... in ) and ( for... of ) statements?

A see a lot of good answers, but I decide to put my 5 cents just to have good example:

For in loop

iterates over all enumerable props

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
  console.log( key );_x000D_
}
_x000D_
_x000D_
_x000D_

For of loop

iterates over all iterable values

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
  console.log( node.toString() );_x000D_
}
_x000D_
_x000D_
_x000D_

Fixed height and width for bootstrap carousel

Apply following style to carousel listbox.

_x000D_
_x000D_
<div class="carousel-inner" role="listbox" style=" width:100%; height: 500px !important;">_x000D_
_x000D_
..._x000D_
_x000D_
</div
_x000D_
_x000D_
_x000D_

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

List all sequences in a Postgres db 8.1 with SQL

sequence info : max value

SELECT * FROM information_schema.sequences;

sequence info : last value

SELECT * FROM <sequence_name>

Generate a random number in the range 1 - 10

If by numbers between 1 and 10 you mean any float that is >= 1 and < 10, then it's easy:

select random() * 9 + 1

This can be easily tested with:

# select min(i), max(i) from (
    select random() * 9 + 1 as i from generate_series(1,1000000)
) q;
       min       |       max
-----------------+------------------
 1.0000083274208 | 9.99999571684748
(1 row)

If you want integers, that are >= 1 and < 10, then it's simple:

select trunc(random() * 9 + 1)

And again, simple test:

# select min(i), max(i) from (
    select trunc(random() * 9 + 1) as i from generate_series(1,1000000)
) q;
 min | max
-----+-----
   1 |   9
(1 row)

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

How to change fontFamily of TextView in Android

What you want is not possible. You must need to set TypeFace in your Code.

In XML what you can do is

android:typeface="sans" | "serif" | "monospace"

other then this you can not play much with the Fonts in XML. :)

For Arial you need to set type face in your code.

Boto3 to download all files from a S3 Bucket

I have the same needs and created the following function that download recursively the files.

The directories are created locally only if they contain files.

import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            dest_pathname = os.path.join(local, file.get('Key'))
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)

The function is called that way:

def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')

phpMyAdmin on MySQL 8.0

As many pointed out in other answers, changing the default authentication plugin of MySQL to native does the trick.

Still, since I can't use the new caching_sha2_password plugin, I'll wait until compatibility is developed to close the topic.

Using @property versus getters and setters

Here is an excerpts from "Effective Python: 90 Specific Ways to Write Better Python" (Amazing book. I highly recommend it).

Things to Remember

? Define new class interfaces using simple public attributes and avoid defining setter and getter methods.

? Use @property to define special behavior when attributes are accessed on your objects, if necessary.

? Follow the rule of least surprise and avoid odd side effects in your @property methods.

? Ensure that @property methods are fast; for slow or complex work—especially involving I/O or causing side effects—use normal methods instead.

One advanced but common use of @property is transitioning what was once a simple numerical attribute into an on-the-fly calculation. This is extremely helpful because it lets you migrate all existing usage of a class to have new behaviors without requiring any of the call sites to be rewritten (which is especially important if there’s calling code that you don’t control). @property also provides an important stopgap for improving interfaces over time.

I especially like @property because it lets you make incremental progress toward a better data model over time.
@property is a tool to help you address problems you’ll come across in real-world code. Don’t overuse it. When you find yourself repeatedly extending @property methods, it’s probably time to refactor your class instead of further paving over your code’s poor design.

? Use @property to give existing instance attributes new functionality.

? Make incremental progress toward better data models by using @property.

? Consider refactoring a class and all call sites when you find yourself using @property too heavily.

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

In my case, the app main Target's Team was different from Tests' Target Team. Changing the Tests' Team to the same Team as main Target's solves the issue.

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

R: rJava package install failing

The problem was rJava wont install in RStudio (Version 1.0.136). The following worked for me (macOS Sierra version 10.12.6) (found here):

Step-1: Download and install javaforosx.dmg from here

Step-2: Next, run the command from inside RStudio:

install.packages("rJava", type = 'source')

Flask raises TemplateNotFound error even though template file exists

(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)

Also..

In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Hope this helps

Android: ProgressDialog.show() crashes with getApplicationContext

I am using Android version 2.1 with API Level 7. I faced with this (or similar) problem and solved by using this:

Dialog dialog = new Dialog(this);

instead of this:

Dialog dialog = new Dialog(getApplicationContext());

Hope this helps :)

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

jQuery click event not working in mobile browsers

You can use jQuery Mobile vclick event:

Normalized event for handling touchend or mouse click events on touch devices.

$(document).ready(function(){
   $('.publications').vclick(function() {
       $('#filter_wrapper').show();
   });
 });

jQuery $.ajax(), pass success data into separate function

this is how I do it

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

remove / reset inherited css from an element

Only set the relevant / important CSS properties.

Example (only change the attributes which may cause your div to look completely different):

background: #FFF;
border: none;
color: #000;
display: block;
font: initial;
height: auto;
letter-spacing: normal;
line-height: normal;
margin: 0;
padding: 0;
text-transform: none;
visibility: visible;
width: auto;
word-spacing: normal;
z-index: auto;

Choose a very specific selector, such as div#donttouchme, <div id="donttouchme"></div>. Additionally, you can add `!important before every semicolon in the declaration. Your customers are deliberately trying to mess up your lay-out when this option fails.

How to define Gradle's home in IDEA?

I had to setup the Project SDK before selecting gradle path. Once that was set correctly, I had to choose "Use default gradle wrapper (recommended) in "Import Project from Gradle" dialog.

Still works if I remove gradle using brew:

$ brew remove gradle

enter image description here

How to unit test abstract classes: extend with stubs?

Write a Mock object and use them just for testing. They usually are very very very minimal (inherit from the abstract class) and not more.Then, in your Unit Test you can call the abstract method you want to test.

You should test abstract class that contain some logic like all other classes you have.

How to get first item from a java.util.Set?

Vector has some handy features:

Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();

But I do agree - this may have unintended consequences, since the underling set is not guaranteed to be ordered.

How to avoid pressing Enter with getchar() for reading a single character only?

By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush:

while((c=getchar())!= EOF)      
{
    putchar(c);
    fflush(stdout);
}

React JS - Uncaught TypeError: this.props.data.map is not a function

what worked for me is converting the props.data to an array using data = Array.from(props.data); then I could use the data.map() function

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

A solution that accept exceptions(passed by parameters):

Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);

(function($) {
    $.fn.maskOwnName = function(not_capitalize) {
            not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;

        $(this).keypress(function(e){
            if(e.altKey || e.ctrlKey)
                return;

            var new_char = String.fromCharCode(e.which).toLowerCase();

            if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
                var start = this.selectionStart,
                    end = this.selectionEnd;

                if(e.keyCode == 8){
                    if(start == end)
                        start--;

                    new_char = '';
                }

                var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
                var maxlength = this.getAttribute('maxlength');
                var words = new_value.split(' ');
                start += new_char.length;
                end = start;

                if(maxlength === null || new_value.length <= maxlength)
                    e.preventDefault();
                else
                    return;

                for (var i = 0; i < words.length; i++){
                    words[i] = words[i].toLowerCase();

                    if(not_capitalize.indexOf(words[i]) == -1)
                        words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
                }

                this.value = words.join(' ');
                this.setSelectionRange(start, end);
            }
        });
    }

    $.fn.maskLowerName = function(pos) {
        $(this).css('text-transform', 'lowercase').bind('blur change', function(){
            this.value = this.value.toLowerCase();
        });
    }

    $.fn.maskUpperName = function(pos) {
        $(this).css('text-transform', 'uppercase').bind('blur change', function(){
            this.value = this.value.toUpperCase();
        });
    }
})(jQuery);

Python Requests and persistent sessions

This will work for you in Python;

# Call JIRA API with HTTPBasicAuth
import json
import requests
from requests.auth import HTTPBasicAuth

JIRA_EMAIL = "****"
JIRA_TOKEN = "****"
BASE_URL = "https://****.atlassian.net"
API_URL = "/rest/api/3/serverInfo"

API_URL = BASE_URL+API_URL

BASIC_AUTH = HTTPBasicAuth(JIRA_EMAIL, JIRA_TOKEN)
HEADERS = {'Content-Type' : 'application/json;charset=iso-8859-1'}

response = requests.get(
    API_URL,
    headers=HEADERS,
    auth=BASIC_AUTH
)

print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Getting the "real" Facebook profile picture URL from graph API

function getFacebookImageFromURL($url)
{
  $headers = get_headers($url, 1);
  if (isset($headers['Location']))
  {
    return $headers['Location'];
  }
}

$url = 'https://graph.facebook.com/zuck/picture?type=large';
$imageURL = getFacebookImageFromURL($url);

Full width layout with twitter bootstrap

In Bootstrap 3, columns are specified using percentages. (In Bootstrap 2, this was only the case if a column/span was within a .row-fluid element, but that's no longer necessary and that class no longer exists.) If you use a .container, then @Michael is absolutely right that you'll be stuck with a fixed-width layout. However, you should be in good shape if you just avoid using a .container element.

<body>
  <div class="row">
    <div class="col-lg-4">...</div>
    <div class="col-lg-8">...</div>
  </div>
</body>

The margin for the body is already 0, so you should be able to get up right to the edge. (Columns still have a 15px padding on both sides, so you may have to account for that in your design, but this shouldn't stop you, and you can always customize this when you download Bootstrap.)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

As per the SLF4J Error Codes

Failed to load class org.slf4j.impl.StaticLoggerBinder This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

Note that slf4j-api versions 2.0.x and later use the ServiceLoader mechanism. Backends such as logback 1.3 and later which target slf4j-api 2.x, do not ship with org.slf4j.impl.StaticLoggerBinder. If you place a logging backend which targets slf4j-api 2.0.x, you need slf4j-api-2.x.jar on the classpath. See also relevant faq entry.

SINCE 1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.

If you are responsible for packaging an application and do not care about logging, then placing slf4j-nop.jar on the class path of your application will get rid of this warning message. Note that embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api. When a library declares a compile-time dependency on a SLF4J binding, it imposes that binding on the end-user, thus negating SLF4J's purpose.

Set start value for column with autoincrement

Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:

SET IDENTITY_INSERT Orders ON

-- do inserts here

SET IDENTITY_INSERT Orders OFF

This insert will reset the identity to the last inserted value. From MSDN:

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

Extension gd is missing from your system - laravel composer Update

PHP 7.4.2 (cli) (built: Feb 5 2020 16:50:21) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.2, Copyright (c), by Zend Technologies

For Php 7.4.2

  1. sudo apt-get install php7.4-gd
  2. sudo phpenmod gd

How to retrieve Jenkins build parameters using the Groovy API?

In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:

def myParam = env.getProperty(dynamicParamName)

In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:

def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName

Reset MySQL root password using ALTER USER statement after install on Mac

If this is NOT your first time setting up the password, try this method:

mysql> UPDATE mysql.user SET Password=PASSWORD('your_new_password')
           WHERE User='root'; 

And if you get the following error, there is a high chance that you have never set your password before:

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement. 

To set up your password for the first time:

mysql> SET PASSWORD = PASSWORD('your_new_password');
Query OK, 0 rows affected, 1 warning (0.01 sec)

Reference: https://dev.mysql.com/doc/refman/5.6/en/alter-user.html

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

Generate SQL Create Scripts for existing tables with Query

Here's a slight variation on @Devart 's answer so you can get the CREATE script for a temp table.

Please note that since the @SQL variable is an NVARCHAR(MAX) data type you might not be able to copy it from the result using just only SSMS. Please see this question to see how to get the full value of a MAX field.

DECLARE @temptable_objectid INT = OBJECT_ID('tempdb..#Temp');

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT  
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM tempdb.sys.objects o WITH (NOWAIT)
JOIN tempdb.sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE object_id = @temptable_objectid

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM tempdb.sys.index_columns ic WITH (NOWAIT)
    JOIN tempdb.sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
),
fk_columns AS 
(
     SELECT 
          k.constraint_object_id
        , cname = c.name
        , rcname = rc.name
    FROM tempdb.sys.foreign_key_columns k WITH (NOWAIT)
    JOIN tempdb.sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id 
    JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id
    WHERE k.parent_object_id = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM tempdb.sys.columns c WITH (NOWAIT)
    JOIN tempdb.sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN tempdb.sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN tempdb.sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN tempdb.sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM tempdb.sys.index_columns ic WITH (NOWAIT)
                         JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM tempdb.sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)
    + ISNULL((SELECT (
        SELECT CHAR(13) +
             'ALTER TABLE ' + @object_name + ' WITH' 
            + CASE WHEN fk.is_not_trusted = 1 
                THEN ' NOCHECK' 
                ELSE ' CHECK' 
              END + 
              ' ADD CONSTRAINT [' + fk.name  + '] FOREIGN KEY(' 
              + STUFF((
                SELECT ', [' + k.cname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')' +
              ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] ('
              + STUFF((
                SELECT ', [' + k.rcname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')'
            + CASE 
                WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' 
                WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL'
                WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' 
                ELSE '' 
              END
            + CASE 
                WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE'
                WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL'
                WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT'  
                ELSE '' 
              END 
            + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name  + ']' + CHAR(13)
        FROM tempdb.sys.foreign_keys fk WITH (NOWAIT)
        JOIN tempdb.sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
        WHERE fk.parent_object_id = @object_id
        FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '')
    + ISNULL(((SELECT
         CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END 
                + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' +
                STUFF((
                SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END
                FROM index_column c
                WHERE c.is_included_column = 0
                    AND c.index_id = i.index_id
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'  
                + ISNULL(CHAR(13) + 'INCLUDE (' + 
                    STUFF((
                    SELECT ', [' + c.name + ']'
                    FROM index_column c
                    WHERE c.is_included_column = 1
                        AND c.index_id = i.index_id
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '')  + CHAR(13)
        FROM tempdb.sys.indexes i WITH (NOWAIT)
        WHERE i.[object_id] = @object_id
            AND i.is_primary_key = 0
            AND i.[type] = 2
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
    ), '')

SELECT @SQL

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

Does Visual Studio Code have box select/multi-line edit?

The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right

To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu FilePreferencesKeyboard shortcuts).

{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
                                     "when": "editorTextFocus" }

How can I enable MySQL's slow query log without restarting MySQL?

MySQL Manual - slow-query-log-file

This claims that you can run the following to set the slow-log file (5.1.6 onwards):

set global slow_query_log_file = 'path';

The variable slow_query_log just controls whether it is enabled or not.

How to increment a pointer address and pointer's value?

With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++); is actually well defined and does what you're asking for, e.g.:

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.

Get property value from C# dynamic object by string (reflection?)

Did you see ExpandoObject class?

Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."

With it you can write code like this:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

What's the proper way to compare a String to an enum value?

This is my solution in java 8:

 public static Boolean isValidCity(String cityCode) {
        return Arrays.stream(CITY_ENUM.values())
                .map(CITY_ENUM::getCityCode)
                .anyMatch(cityCode::equals);
 }

"The system cannot find the file specified" when running C++ program

This is a first step for somebody that is a beginner. Same thing happened to me:

Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp file there. You can do the same by looking the .cpp file where the .sln file for the project is stored. If there is not one, then you will get that error.

When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp file to the project.

Add CSS or JavaScript files to layout head from views or partial views

I tried to solve this issue.

My answer is here.

"DynamicHeader" - http://dynamicheader.codeplex.com/, https://nuget.org/packages/DynamicHeader

For example, _Layout.cshtml is:

<head>
@Html.DynamicHeader()
</head>
...

And, you can register .js and .css files to "DynamicHeader" anywhere you want.

For example, the code block in AnotherPartial.cshtml is:

@{
  DynamicHeader.AddSyleSheet("~/Content/themes/base/AnotherPartial.css");
  DynamicHeader.AddScript("~/some/myscript.js");
}

Result HTML output for this sample is:

<html>
  <link href="/myapp/Content/themes/base/AnotherPartial.css" .../>
  <script src="/myapp/some/myscript.js" ...></script>
</html>
...

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

For me the issue seems to have been caused by power failure. Restarting the server computer solved it.

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Detecting real time window size changes in Angular 4

The answer is very simple. write the below code

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
 selector: "app-login",
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;

@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
      this.scrHeight = window.innerHeight;
      this.scrWidth = window.innerWidth;
      console.log(this.scrHeight, this.scrWidth);
}

// Constructor
constructor() {
    this.getScreenSize();
}
}

Calling ASP.NET MVC Action Methods from JavaScript

You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;

How do I move an existing Git submodule within a Git repository?

[Update: 2014-11-26] As Yar summarizes nicely below, before you do anything, make sure you know the URL of the submodule. If unknown, open .git/.gitmodules and examine the keysubmodule.<name>.url.

What worked for me was to remove the old submodule using git submodule deinit <submodule> followed by git rm <submodule-folder>. Then add the submodule again with the new folder name and commit. Checking git status before committing shows the old submodule renamed to the new name and .gitmodule modified.

$ git submodule deinit foo
$ git rm foo
$ git submodule add https://bar.com/foo.git new-foo
$ git status
renamed:    foo -> new-foo
modified:   .gitmodules
$ git commit -am "rename foo submodule to new-foo"

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

jQuery animated number counter from zero to value

This worked for me

HTML CODE

<span class="number-count">841</span>

jQuery Code

$('.number-count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });

How do you configure an OpenFileDialog to select folders?

The Ookii Dialogs for WPF library has a class that provides an implementation of a folder browser dialog for WPF.

https://github.com/augustoproiete/ookii-dialogs-wpf

Ookii Folder Browser Dialog

There's also a version that works with Windows Forms.

Convert Promise to Observable

You can also use a Subject and trigger its next() function from promise. See sample below:

Add code like below ( I used service )

_x000D_
_x000D_
class UserService {_x000D_
  private createUserSubject: Subject < any > ;_x000D_
_x000D_
  createUserWithEmailAndPassword() {_x000D_
    if (this.createUserSubject) {_x000D_
      return this.createUserSubject;_x000D_
    } else {_x000D_
      this.createUserSubject = new Subject < any > ();_x000D_
      firebase.auth().createUserWithEmailAndPassword(email,_x000D_
          password)_x000D_
        .then(function(firebaseUser) {_x000D_
          // do something to update your UI component_x000D_
          // pass user object to UI component_x000D_
          this.createUserSubject.next(firebaseUser);_x000D_
        })_x000D_
        .catch(function(error) {_x000D_
          // Handle Errors here._x000D_
          var errorCode = error.code;_x000D_
          var errorMessage = error.message;_x000D_
          this.createUserSubject.error(error);_x000D_
          // ..._x000D_
        });_x000D_
    }_x000D_
_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Create User From Component like below

_x000D_
_x000D_
class UserComponent {_x000D_
  constructor(private userService: UserService) {_x000D_
    this.userService.createUserWithEmailAndPassword().subscribe(user => console.log(user), error => console.log(error);_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

"Too many characters in character literal error"

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Why is it not advisable to have the database and web server on the same machine?

Ok! Here is the thing, it is more Secure to have your DB Server installed on another Machine and your Application on the Web Server. You then connect your application to the DB with a Web Link. Thanks it.

What does the keyword "transient" mean in Java?

Transient variables in Java are never serialized.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Altering column size in SQL Server

Running ALTER COLUMN without mentioning attribute NOT NULL will result in the column being changed to nullable, if it is already not. Therefore, you need to first check if the column is nullable and if not, specify attribute NOT NULL. Alternatively, you can use the following statement which checks the nullability of column beforehand and runs the command with the right attribute.

IF COLUMNPROPERTY(OBJECT_ID('Employee', 'U'), 'Salary', 'AllowsNull')=0
    ALTER TABLE [Employee]
        ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL
ELSE        
    ALTER TABLE [Employee]
        ALTER COLUMN [Salary] NUMERIC(22,5) NULL

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

SQL Server query to find all current database names

I don't recommend this method... but if you want to go wacky and strange:

EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName'

or

EXEC sp_MSForEachDB 'Print ''?'''

Using find command in bash script

Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

The one you're looking for is -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

The Bash FAQ has lots of other excellent tips about programming in bash.

javascript onclick increment number

Simple HTML + Thymeleaf version. Code with Controller

<form action="/" method="post">
                <input type="hidden" th:value="${post.getId_post()}" name="id_post">
                <input type="hidden" th:value="-1" name="valueForChange">
                <input type="submit" value="-">
</form>

This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Wait until boolean value changes it state

How about wait-notify

private Boolean bool = true;
private final Object lock = new Object();

private Boolean getChange(){
  synchronized(lock){
    while (bool) {
      bool.wait();
    }
   }
  return bool;
}
public void setChange(){
   synchronized(lock){
       bool = false;
       bool.notify();
   }
}

php $_POST array empty upon form submission

Not the most convenient solution perhaps, but I figured it out that if I set the form action attribute to the root domain, index.php can be accessed and gets the posted variables. However if I set a rewritten URL as action, it does not work.

What is a method group in C#?

The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.

Changing factor levels with dplyr mutate

Maybe you are looking for this plyr::revalue function:

mutate(dat, x = revalue(x, c("A" = "B")))

You can see plyr::mapvalues too.

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

List all devices, partitions and volumes in Powershell

This is pretty old, but I found following worth noting:

PS N:\> (measure-command {Get-WmiObject -Class Win32_LogicalDisk|select -property deviceid|%{$_.deviceid}|out-host}).totalmilliseconds
...
928.7403
PS N:\> (measure-command {gdr -psprovider 'filesystem'|%{$_.name}|out-host}).totalmilliseconds
...
169.474

Without filtering properties, on my test system, 4319.4196ms to 1777.7237ms. Unless I need a PS-Drive object returned, I'll stick with WMI.

EDIT: I think we have a winner: PS N:> (measure-command {[System.IO.DriveInfo]::getdrives()|%{$_.name}|out-host}).to??talmilliseconds 110.9819

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

How can I make an "are you sure" prompt in a Windows batchfile?

Here a bit easier:

@echo off
set /p var=Are You Sure?[Y/N]: 
if %var%== Y goto ...
if not %var%== Y exit

or

@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no

Show all current locks from get_lock

Reference taken from this post:

You can also use this script to find lock in MySQL.

SELECT 
    pl.id
    ,pl.user
    ,pl.state
    ,it.trx_id 
    ,it.trx_mysql_thread_id 
    ,it.trx_query AS query
    ,it.trx_id AS blocking_trx_id
    ,it.trx_mysql_thread_id AS blocking_thread
    ,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl 
INNER JOIN information_schema.innodb_trx AS it
    ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
    ON it.trx_id = ilw.requesting_trx_id 
        AND it.trx_id = ilw.blocking_trx_id

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.

Move SQL data from one table to another

It will create a table and copy all the data from old table to new table

SELECT * INTO event_log_temp FROM event_log

And you can clear the old table data.

DELETE FROM event_log

How to insert an item at the beginning of an array in PHP?

Use array_unshift($array, $item);

$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);

will give you

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

Python | change text color in shell

This is so simple to do on a PC: Windows OS: Send the os a command to change the text: import os

os.system('color a') #green text
print 'I like green' 
raw_input('do you?')

Flutter.io Android License Status Unknown

  1. Open Android Studio.
  2. Go to File->Settings.
  3. Search for AndroidSDK.
  4. Update your API Level to latest version.
  5. Then reload Android Studio.

Detect if a page has a vertical scrollbar?

var hasScrollbar = window.innerWidth > document.documentElement.clientWidth;

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

if the full message is:

kernel panic - not syncing: Attempted to kill inint !
PId: 1, comm: init not tainted 2.6.32.-279-5.2.e16.x86_64 #1

then you should have disabled selinux and after that you have rebooted the system.

The easier way is to use a live OS and re-enable it

vim /etc/selinux/config
    ...
    SELINUX=enforcing
    ...

Second choice is to disable selinux in the kernel arguments by adding selinux=0

vim /boot/grub/grub.conf
    ...
    kernel /boot/vmlinuz-2.4.20-selinux-2003040709 ro root=/dev/hda1 nousb selinux=0
    ...

source kernel panic - not syncing: Attempted to kill inint !

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Running a cron every 30 seconds

Why not just adding 2 consecutive command entries, both starting at different second?

0 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'''
30 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'''

How to instantiate a File object in JavaScript?

According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.

So to create a empty file do:

var f = new File([""], "filename");
  • The first argument is the data provided as an array of lines of text;
  • The second argument is the filename ;
  • The third argument looks like:

    var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
    

It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.

jQuery: read text file from file system

A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

html:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <script type="text/javascript">
    function loadData() {
      // getData() will return the string of data...
      document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
    }
  </script>
</head>

<body onload='loadData()'>
  <h1>check out the data!</h1>
  <div id='data'></div>
</body>

</html>

script.js:

// function wrapper, just return the string of data (csv etc)
function getData () {
    return 'look at this line of data\n\
oh, look at this line'
}

See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').

Taking screenshot on Emulator from Android Studio

Starting with Android Studio 2.0 you can do it with the new emulator:

New Android Emulator from Android Studio 2.0

Just click 3 "Take Screenshot". Standard location is the desktop.

Or

  1. Select "More"
  2. Under "Settings", specify the location for your screenshot
  3. Take your screenshot

UPDATE 22/07/2020

If you keep the emulator in Android Studio as possible since Android Studio 4.1 click here to save the screenshot in your standard location:

enter image description here

Replace console output in Python

A more elegant solution could be:

def progressBar(current, total, barLength = 20):
    percent = float(current) * 100 / total
    arrow   = '-' * int(percent/100 * barLength - 1) + '>'
    spaces  = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')

call this function with value and endvalue, result should be

Progress: [------------->      ] 69 %

Note: Python 2.x version here.

Delete a row in Excel VBA

Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

dim rng as range
dim rDel as range

for each rng in {the range you're searching}
   if {Conditions to be met} = true then
      if not rDel is nothing then
         set rDel = union(rng,rDel)
      else
         set rDel = rng
      end if
   end if
 next
 
 rDel.entirerow.delete

That way you don't have to worry about sorting or things being at the bottom.

How do you simulate Mouse Click in C#?

An example I found somewhere here in the past. Might be of some help:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class Form1 : Form
{
   [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
   public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
   //Mouse actions
   private const int MOUSEEVENTF_LEFTDOWN = 0x02;
   private const int MOUSEEVENTF_LEFTUP = 0x04;
   private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
   private const int MOUSEEVENTF_RIGHTUP = 0x10;

   public Form1()
   {
   }

   public void DoMouseClick()
   {
      //Call the imported function with the cursor's current position
      uint X = (uint)Cursor.Position.X;
      uint Y = (uint)Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
   }

   //...other code needed for the application
}

Android: How to stretch an image to the screen width while maintaining aspect ratio?

I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)

<FrameLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

     <ImageView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:adjustViewBounds="true"
          android:scaleType="centerCrop"
          android:src="@drawable/whatever" />
</FrameLayout>

std::cin input with spaces?

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

THE C++ WAY

gets is removed in c++11.

[Recommended]:You can use getline(cin,name) which is in string.h or cin.getline(name,256) which is in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}

onchange file input change img src and change image color

Simple Solution. No Jquery

_x000D_
_x000D_
<img id="output" src="" width="100" height="100">_x000D_
_x000D_
<input name="photo" type="file" accept="image/*" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
_x000D_
_x000D_
_x000D_

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].updateValue(selected.id);
}

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

How to get the unique ID of an object which overrides hashCode()?

Just to augment the other answers from a different angle.

If you want to reuse hashcode(s) from 'above' and derive new ones using your class' immutatable state, then a call to super will work. While this may/may not cascade all the way up to Object (i.e. some ancestor may not call super), it will allow you to derive hashcodes by reuse.

@Override
public int hashCode() {
    int ancestorHash = super.hashCode();
    // now derive new hash from ancestorHash plus immutable instance vars (id fields)
}

Exporting data In SQL Server as INSERT INTO

Just updating screenshots to help others as I am using a newer v18, circa 2019.

Right click DB: Tasks > Generate Scripts

Here you can select certain tables or go with the default of all.

Here you can select certain tables or go with the default of all. For my own needs I'm indicating just the one table.

Next, there's the "Scripting Options" where you can choose output file, etc. As in multiple answers above (again, I'm just dusting off old answers for newer, v18.4 SQL Server Management Studio) what we're really wanting is under the "Advanced" button. For my own purposes, I need just the data.

General output options, including output to file. Advanced options including data!

Finally, there's a review summary before execution. After executing a report of operations' status is shown. Review summary.

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

How to get the first line of a file in a bash script?

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null

Close iOS Keyboard by touching anywhere using Swift

for Swift 3 it is very simple

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

if you want to hide keyboard on pressing RETURN key

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

but in second case you will also need to pass delegate from all textFields to the ViewController in the Main.Storyboard

MySQL config file location - redhat linux server

Just found it, it is /etc/my.cnf

Pip - Fatal error in launcher: Unable to create process using '"'

I installed python 2 and python 3 both in my windows 7. After having both versions of python, I moved to download PIP.

After downloading pip via downloading the get-pip.py file and run into the command prompt and navigate to the folder containing get-pip.py file.

I Run the following command:

python get-pip.py

after downloading PIP, I was getting the following error, Fatal error in launcher: Unable to create process using '"' SOLUTION **Then what worked for me is: I just run the following below command

python3 -m pip install --upgrade pip

And my pip started working. Hope it helps !**

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

How to call codeigniter controller function from view

it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('script');
        $this->load->model('alert');

    }public function pledge_ph(){
        $this->script->phpledge();
    }
}
?>

This is the controller class Iris.php and the model class with the function pointed to from the controller class.

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
    public function __construct() {
        parent::__construct();
        // Your own constructor code
    }public function ghpledge(){
        $gh_id = uniqid(rand(1,11));
        $date=date("y-m-d");
        $gh_member = $_SESSION['member_id'];
        $amount= 10000;
        $data = array(
            'gh_id'=> $gh_id,
            'gh_member'=> $gh_member,
            'amount'=> $amount,
            'date'=> $date
        );
        $this->db->insert('iris_gh',$data);
    } 
}
?>

On the view instead of a button just use the anchor link with the controller name and method name.

<html>
    <head></head>
    <body>
        <a href="<?php echo base_url(); ?>index.php/iris/pledge_ph" class="btn btn-success">PLEDGE PH</a>
    </body>
</html>

'ls' is not recognized as an internal or external command, operable program or batch file

If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.

PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.

The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

This worked for me;

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php 

Line No : 614

Replace two codes :

Replace:

(count($analyzed_sql_results[‘select_expr’] == 1)

With:

(count($analyzed_sql_results[‘select_expr’]) == 1)

AND

Replace:

($analyzed_sql_results[‘select_expr’][0] == ‘*’)))

With:

($analyzed_sql_results[‘select_expr’][0] == ‘*’))

save, exit and run

sudo service apache2 restart

Lightweight XML Viewer that can handle large files

I like Microsoft's XML Notepad 2007, but I don't know how it handles very large files, sorry.

mysql_fetch_array() expects parameter 1 to be resource problem

You are not doing error checking after the call to mysql_query:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
    die('Invalid query: ' . mysql_error());
}

In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.

How to get the focused element with jQuery?

$( document.activeElement )

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

Go back button in a page

There's a few ways, this is one:

window.history.go(-1);

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $(".classname").hide();
  });
</script>

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

Python: Open file in zip without temporarily extracting it

In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
    image = pygame.image.load(imgfile, 'img_01.png')
finally:
    imgfile.close()

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

Check if an element is a child of a parent

In addition to the other answers, you can use this less-known method to grab elements of a certain parent like so,

$('child', 'parent');

In your case, that would be

if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);

Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes

$('child, parent');

you'd have an object containing both objects, regardless of whether they exist in their document trees.

pass JSON to HTTP POST Request

I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js

Which uses the following format:

request({
    url: url,
    method: "POST",
    headers: {
        "content-type": "application/json",
        },
    json: requestData
//  body: JSON.stringify(requestData)
    }, function (error, resp, body) { ...

proper name for python * operator?

The Python Tutorial simply calls it 'the *-operator'. It performs unpacking of arbitrary argument lists.

creating list of objects in Javascript

Going off of tbradley22's answer, but using .map instead:

var a = ["car", "bike", "scooter"];
a.map(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    return singleObj;
});

Most efficient way to get table row count

try this

Execute this SQL:

SHOW TABLE STATUS LIKE '<tablename>'

and fetch the value of the field Auto_increment

spring autowiring with unique beans: Spring expected single matching bean but found 2

If you have 2 beans of the same class autowired to one class you shoud use @Qualifier (Spring Autowiring @Qualifier example).

But it seems like your problem comes from incorrect Java Syntax.

Your object should start with lower case letter

SuggestionService suggestion;

Your setter should start with lower case as well and object name should be with Upper case

public void setSuggestion(final Suggestion suggestion) {
    this.suggestion = suggestion;
}

Using atan2 to find angle between two vectors

I think a better formula was posted here: http://www.mathworks.com/matlabcentral/answers/16243-angle-between-two-vectors-in-3d

angle = atan2(norm(cross(a,b)), dot(a,b))

So this formula works in 2 or 3 dimensions. For 2 dimensions this formula simplifies to the one stated above.

Install an apk file from command prompt?

You can do this by using adb command line tools OR gradle commands: See this Guide.

Setup command line adb

export PATH=/Users/mayurik/Library/Android/sdk/platform-tools/adb:/Users/mayurik/Library/Android/sdk/tool

Gradle commands to build and install.

 #Start Build Process
    echo "\n\n\nStarting"
    ./gradlew clean

    ./gradlew build

    ./gradlew assembleDebug

    #Install APK on device / emulator
    echo "installDebug...\n"

    ./gradlew installDebug

You can also uninstall any previous versions using

  `./gradlew uninstallDebug`

You can launch your main activity on device/emulator like below

#Launch Main Activity
adb shell am start -n "com.sample.androidbuildautomationsample/com.sample.androidbuildautomationsample.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

Input and Output binary streams using JERSEY?

Another sample code where you can upload a file to the REST service, the REST service zips the file, and the client downloads the zip file from the server. This is a good example of using binary input and output streams using Jersey.

https://stackoverflow.com/a/32253028/15789

This answer was posted by me in another thread. Hope this helps.

View JSON file in Browser

In Chrome use JSONView or Firefox use JSONView

postgresql - replace all instances of a string within text field

You can use the replace function

UPDATE your_table SET field = REPLACE(your_field, 'cat','dog')

The function definition is as follows (got from here):

replace(string text, from text, to text)

and returns the modified text. You can also check out this sql fiddle.

How do you clear a slice in Go?

It all depends on what is your definition of 'clear'. One of the valid ones certainly is:

slice = slice[:0]

But there's a catch. If slice elements are of type T:

var slice []T

then enforcing len(slice) to be zero, by the above "trick", doesn't make any element of

slice[:cap(slice)]

eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".