Programs & Examples On #Video camera

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

Create directory if it does not exist

From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
    # Select all the Revision folders from the project folder.
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory

    # The next revision number is just going to be one more than the highest number.
    # You need to cast the string in the first pipeline to an int so Sort-Object works.
    # If you sort it descending the first number will be the biggest so you select that one.
    # Once you have the highest revision number you just add one to it.
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1

    # Now in this we kill two birds with one stone.
    # It will create the "Reports" folder but it also creates "Revision#" folder too.
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory

    # Move on to the next project folder.
    # This untested example loop requires PowerShell version 3.0.
}

PowerShell 3.0 installation.

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

How to change the JDK for a Jenkins job?

If you have a multi-config (matrix) job, you do not have a JDK dropdown but need to configure the jdk as build axis.

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

Java 8 Streams FlatMap method example

It doesn't make sense to flatMap a Stream that's already flat, like the Stream<Integer> you've shown in your question.

However, if you had a Stream<List<Integer>> then it would make sense and you could do this:

Stream<List<Integer>> integerListStream = Stream.of(
    Arrays.asList(1, 2), 
    Arrays.asList(3, 4), 
    Arrays.asList(5)
);

Stream<Integer> integerStream = integerListStream .flatMap(Collection::stream);
integerStream.forEach(System.out::println);

Which would print:

1
2
3
4
5

To do this pre-Java 8 you just need a loops:

List<List<Integer>> integerLists = Arrays.asList(
    Arrays.asList(1, 2), 
    Arrays.asList(3, 4), 
    Arrays.asList(5)
)

List<Integer> flattened = new ArrayList<>();

for (List<Integer> integerList : integerLists) {
    flattened.addAll(integerList);
}

for (Integer i : flattened) {
    System.out.println(i);
}

DateTime.TryParse issue with dates of yyyy-dd-MM format

You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                   "MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into

try
{
    dateValue = DateTime.ParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
                                    DateTimeStyles.None);
    Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
    Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}                                               

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

Webpack how to build production code and how to use it

Use these plugins to optimize your production build:

  new webpack.optimize.CommonsChunkPlugin('common'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.

new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
})

Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.

.gitignore all the .DS_Store files in every folder and subfolder

I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.

You have to manually remove the .DS_Store files that were added to your repository. You can use

git rm --cached .DS_Store

Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store. Don't forget the period!

git rm --cached .DS_Store

removes only .DS_Store from the current directory. You can use

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

to remove all .DS_Stores from the repository.

Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g.

echo .DS_Store >> ~/.gitignore_global

Now tell git to use it for all repositories:

git config --global core.excludesfile ~/.gitignore_global

This page helped me answer your question.

Clear data in MySQL table with PHP?

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.

Hash function that produces short hashes?

You can use the hashlib library for Python. The shake_128 and shake_256 algorithms provide variable length hashes. Here's some working code (Python3):

import hashlib
>>> my_string = 'hello shake'
>>> hashlib.shake_256(my_string.encode()).hexdigest(5)
'34177f6a0a'

Notice that with a length parameter x (5 in example) the function returns a hash value of length 2x.

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

How do I add a resources folder to my Java project in Eclipse

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I just thought I'd chip in on this one. It's been answered perfectly well by others though.

The full main method declaration should be :

 public static void main(final String[] args) throws Exception {

 }

The args are declared final because technically they should not be altered. They are console parameters given by the user.

You should usually specify that main throws Exception so that stack traces can be echoed to console easily without needing to do e.printStackTrace() etc.

As for Array Syntax. I prefer it this way. I suppose that it's a little bit like the difference between french and english. In English it's "a black car", in french it's "a car black". Which is the important noun, car, or black?

I don't like this sort of thing :

String blah[] = {};

What's important here is that it's a String array, so it should be

String[] blah = {};

blah is just a name. I personally think it's a bit of a mistake in Java that arrays can sometimes be declared in that manner.

Write lines of text to a file in R

I suggest:

writeLines(c("Hello","World"), "output.txt")

It is shorter and more direct than the current accepted answer. It is not necessary to do:

fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)

Because the documentation for writeLines() says:

If the con is a character string, the function calls file to obtain a file connection which is opened for the duration of the function call.

# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How to connect HTML Divs with Lines?

Check my fiddle from this thread: Draw a line connecting two clicked div columns

The layout is different, but basically the idea is to create invisible divs between the boxes and add corresponding borders with jQuery (the answer is only HTML and CSS)

How to check if object has been disposed in C#

The reliable solution is catching the ObjectDisposedException.

The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.

Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.

Making button go full-width?

Why not use the Bootstrap predefined class input-block-level that does the job?

<a href="#" class="btn input-block-level">Full-Width Button</a> <!-- BS2 -->
<a href="#" class="btn form-control">Full-Width Button</a> <!-- BS3 -->

<!-- And let's join both for BS# :) -->
<a href="#" class="btn input-block-level form-control">Full-Width Button</a>

Learn more here in the Control Sizing^ section.

jQuery animate margin top

check this same effect with less code

$(".item").mouseover(function(){
    $('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
}); 

View recent fiddle

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

command/usr/bin/codesign failed with exit code 1- code sign error

I have Solved This Problem. If your project has .xcdatamodeld file (mean you are using coreData) then make sure the entities you formed go its Data Model Inspector and check Class has codegen, manual/None or classdefination. if it is class defination then make it manual/None and clean the project and run again. screenshots are given below:

enter image description here

enter image description here

'gulp' is not recognized as an internal or external command

In my case, this problem occured because I did npm install with another system user in my project folder before. Gulp was already installed globally. After deleting folder /node_modules/ in my project, and running npm install with the current user, it worked.

Apache HttpClient Interim Error: NoHttpResponseException

Solution: change the ReuseStrategy to never

Since this problem is very complex and there are so many different factors which can fail I was happy to find this solution in another post: How to solve org.apache.http.NoHttpResponseException

Never reuse connections: configure in org.apache.http.impl.client.AbstractHttpClient:

httpClient.setReuseStrategy(new NoConnectionReuseStrategy());

The same can be configured on a org.apache.http.impl.client.HttpClientBuilder builder:

builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());

Tools to generate database tables diagram with Postgresql?

I love schemaspy for schema visualisations. Look at the sample output they provide, and drool. Note the tabs!

You'll need to download the JDBC driver here, then your command should look something like:

java -jar schemaspy-6.0.0-rc2.jar -t pgsql -db database_name -host myhost -u username -p password -o ./schemaspy -dp postgresql-9.3-1100.jdbc3.jar -s public -noads

Sometimes using options -port will not working if your database has diferrent port, so you have to add manual port after host parameter, for example:

java -jar schemaspy-6.0.0-rc2.jar -t pgsql -db database_name -host myhost:myport -u username -p password -o ./schemaspy -dp postgresql-9.3-1100.jdbc3.jar -s public -noads

You'll need to install graphviz as well if you want graphics (apt-get install graphviz for debian based distros).

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

Python: Number of rows affected by cursor.execute("SELECT ...)

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = (len(cursor.fetchall))

View's getWidth() and getHeight() returns 0

As Ian states in this Android Developers thread:

Anyhow, the deal is that layout of the contents of a window happens after all the elements are constructed and added to their parent views. It has to be this way, because until you know what components a View contains, and what they contain, and so on, there's no sensible way you can lay it out.

Bottom line, if you call getWidth() etc. in a constructor, it will return zero. The procedure is to create all your view elements in the constructor, then wait for your View's onSizeChanged() method to be called -- that's when you first find out your real size, so that's when you set up the sizes of your GUI elements.

Be aware too that onSizeChanged() is sometimes called with parameters of zero -- check for this case, and return immediately (so you don't get a divide by zero when calculating your layout, etc.). Some time later it will be called with the real values.

C++ Compare char array with string

There is more stable function, also gets rid of string folding.

// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
    /*
     * This function wraps string comparison with string pointers
     * (and also works around 'string folding', as I said).
     * Converts pointers to std::string
     * for make use of string equality operator (==).
     * Parameters use 'const' for prevent possible object corruption.
     */
    std::string var0 = (std::string) arg0;
    std::string var1 = (std::string) arg1;
    if (var0 == var1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

And add declaration to header

// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);

For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.

if (string_equal (var1, "dev"))
{
    // It is equal, do what needed here.
}
else
{
    // It is not equal, do what needed here (optional).
}

Source: sinatramultimedia/fl32 codec (it's written by myself)

Get specific objects from ArrayList when objects were added anonymously?

List.indexOf() will give you what you want, provided you know precisely what you're after, and provided that the equals() method for Party is well-defined.

Party searchCandidate = new Party("FirstParty");
int index = cave.parties.indexOf(searchCandidate);

This is where it gets interesting - subclasses shouldn't be examining the private properties of their parents, so we'll define equals() in the superclass.

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof CaveElement)) {
        return false;
    }

    CaveElement that = (CaveElement) o;

    if (index != that.index) {
        return false;
    }
    if (name != null ? !name.equals(that.name) : that.name != null) {
        return false;
    }

    return true;
}

It's also wise to override hashCode if you override equals - the general contract for hashCode mandates that, if x.equals(y), then x.hashCode() == y.hashCode().

@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + index;
    return result;
}

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

How to echo out the values of this array?

you need the set key and value in foreach loop for that:

foreach($item AS $key -> $value) {
echo $value;
}

this should do the trick :)

What does the colon (:) operator do?

The colon actually exists in conjunction with ?

int minVal = (a < b) ? a : b;

is equivalent to:

int minval;
if(a < b){ minval = a;} 
else{ minval = b; }

Also in the for each loop:

for(Node n : List l){ ... }

literally:

for(Node n = l.head; n.next != null; n = n.next)

Web scraping with Java

HTMLUnit can be used to do web scraping, it supports invoking pages, filling & submitting forms. I have used this in my project. It is good java library for web scraping. read here for more

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

The only way to do explicit scaling in CSS is to use tricks such as found here.

IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.

If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).

Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto after your width: 75px rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.

I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).

Good luck!

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

ng-change not working on a text input

One can also bind a function with ng-change event listener, if they need to run a bit more complex logic.

<div ng-app="myApp" ng-controller="myCtrl">      
        <input type='text' ng-model='name' ng-change='change()'>
        <br/> <span>changed {{counter}} times </span>
 </div>

...

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
      $scope.name = 'Australia';
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
});

https://jsfiddle.net/as0nyre3/1/

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

What's the quickest way to multiply multiple cells by another number?

  1. Enter the multiplier in a cell
  2. Copy that cell to the clipboard
  3. Select the range you want to multiply by the multiplier
  4. (Excel 2003 or earlier) Choose Edit | Paste Special | Multiply

    (Excel 2007 or later) Click on the Paste down arrow | Paste Special | Multiply

How to get textLabel of selected row in swift?

If you're in a class inherited from UITableViewController, then this is the swift version:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    NSLog("did select and the text is \(cell?.textLabel?.text)")
}

Note that cell is an optional, so it must be unwrapped - and the same for textLabel. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that both cell and textLabel are both not nil:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.cellForRowAtIndexPath(indexPath)
    let text = cell?.textLabel?.text
    if let text = text {
        NSLog("did select and the text is \(text)")
    }
}

Windows Scheduled task succeeds but returns result 0x1

I found that I have ticked "Run whether user is logged on or not" and it returns a silent failure.

When I changed tick "Run only when user is logged on" instead it works for me.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

The other answers didn't work for me so here I share my solution in case it might help somebody else:

My problem was that I was configuring the Podfile of my XCode-Project for the wrong platform. Changing "platform :ios" at the beginning of my Podfile to "platform :macos" worked for me to get rid of the error.

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

You can do the folllwoing: import the jar file inside you class:

import javax.servlet.http.HttpServletResponse

add the Apache Tomcat library as follow:

Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok

Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.

I think this will solve your error

Control cannot fall through from one case label

You missed break statements. Don't forget to use break-statements even in the default case.

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
        break;
    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
        break;
    default:
        Console.WriteLine("Default case handling");
        break;
}

The activity must be exported or contain an intent-filter

Just Select App from dropdown menu with Run(green play icon). it will run the whole the App not the specific Activity. if it doesn't help try to use in that activity in ManiFest.xml file. thankyou

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

What's the difference between Thread start() and Runnable run()

run method : - is an abstract method originally created in the Runnable interface and overridden in the Thread class as well as Thread subclasses (As Thread implements Runnable in its source code) and any other implementing classes of Runnable interface. - It is used to load the thread (runnable object) with the task it is intended to do thus you override it to write that task.

start method : - is defined in Thread class. When start method is called on a Thread object 1- it calls internally native (nonjava) method called start0(); method.

start0(); method: is responsible for low processing (stack creation for a thread and allocating thread in processor queue) at this point we have a thread in Ready/Runnable state.

2- At a time when Thread scheduler decides that a thread enters a processor core acorrding to (thread priority as well as OS scheduling algorithm) run method is invoked on the Runnable object (whether it is the current Runnable thread object or the Runnable object passed to the thread constructor) here a thread enters a Running state and starts executing its task (run method)

Why are empty catch blocks a bad idea?

I find the most annoying with empty catch statements is when some other programmer did it. What I mean is when you need to debug code from somebody else any empty catch statements makes such an undertaking more difficult then it need to be. IMHO catch statements should always show some kind of error message - even if the error is not handled it should at least detect it (alt. on only in debug mode)

How to view user privileges using windows cmd?

You can use the following commands:

whoami /priv
whoami /all

For more information, check whoami @ technet.

bash "if [ false ];" returns true instead of false -- why?

as noted by @tripleee, this is tangential, at best.

still, in case you arrived here searching for something like that (as i did), here is my solution

having to deal with user acessible configuration files, i use this function :

function isTrue() {
    if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
    return 1
    }

wich can be used like that

if isTrue "$whatever"; then..

You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".

note that the '^^' provides case insensivity

Breaking a list into multiple columns in Latex

I don't know if it would work, but maybe you could break the page into columns using the multicol package.

\usepackage{multicol}

\begin{document}
\begin{multicols}{2}[Your list here]
\end{multicols}

Android Studio does not show layout preview

Sometimes layout preview not show only in your current project, try open other project if in other project layout preview work well then the problem in your current project. in your current project try clean project, rebuild project, if still not working try make changes in your build.gradle app file, such add some implementation then gradle sync , check your layout preview works.

Pointers, smart pointers or shared pointers?

the term "smart pointer" includes shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer.

Dumb pointers (T*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent.

Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns.

Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself.

For an essential counterpart to shared pointers, look up weak pointers too.

Why doesn't file_get_contents work?

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).

I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

twitter bootstrap typeahead ajax example

Try this if your service is not returning the right application/json content type header:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            var json = JSON.parse(data); // string to json
            return process(json.options);
        });
    }
});

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

To embed a signature on an email, I would use the long version:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

The reason is that not many email readers use html5, so it's always better use old html styles. Actually, it's better to use tables than divs + css as well.

Show constraints on tables command

There is also a tool that oracle made called mysqlshow

If you run it with the --k keys $table_name option it will display the keys.

SYNOPSIS
   mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
·   --keys, -k
   Show table indexes.

example:

?-?  mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database  Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field           | Type             | Collation          | Null | Key | Default | Extra          | Privileges                      | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id              | int(10) unsigned |                    | NO   | PRI |         | auto_increment | select,insert,update,references |         |
| token           | text             | utf8mb4_unicode_ci | NO   |     |         |                | select,insert,update,references |         |
| user_id         | int(10) unsigned |                    | NO   | MUL |         |                | select,insert,update,references |         |
| expires_in      | datetime         |                    | YES  |     |         |                | select,insert,update,references |         |
| created_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
| updated_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table  | Non_unique | Key_name                 | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0          | PRIMARY                  | 1            | id          | A         | 2           |          |        |      | BTREE      |         |               |
| tokens | 1          | tokens_user_id_foreign   | 1            | user_id     | A         | 2           |          |        |      | BTREE      |         |               |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

How to check if type of a variable is string?

The type module also exists if you are checking more than ints and strings. http://docs.python.org/library/types.html

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

How can I return the difference between two lists?

First convert list to sets.

// create an empty set 
Set<T> set = new HashSet<>(); 

// Add each element of list into the set 
for (T t : list) 
    set.add(t); 

You can use Sets.difference(Set1, Set2), which returns extra items present in Set1.
You can use Sets.difference(Set2, Set1), which returns extra items present in Set2.

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

Set height of <div> = to height of another <div> through .css

It seems like what you're looking for is a variant on the CSS Holy Grail Layout, but in two columns. Check out the resources at this answer for more information.

how to convert string to numerical values in mongodb

db.user.find().toArray().filter(a=>a.age>40)

Image resizing client-side with JavaScript before upload to the server

In my experience, this example has been the best solution for uploading a resized picture: https://zocada.com/compress-resize-images-javascript-browser/

It uses the HTML5 Canvas feature.

The code is as 'simple' as this:

compress(e) {
    const fileName = e.target.files[0].name;
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = event => {
        const img = new Image();
        img.src = event.target.result;
        img.onload = () => {
                const elem = document.createElement('canvas');
                const width = Math.min(800, img.width);
                const scaleFactor = width / img.width;
                elem.width = width;
                elem.height = img.height * scaleFactor;

                const ctx = elem.getContext('2d');
                // img.width and img.height will contain the original dimensions
                ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);
                ctx.canvas.toBlob((blob) => {
                    const file = new File([blob], fileName, {
                        type: 'image/jpeg',
                        lastModified: Date.now()
                    });
                }, 'image/jpeg', 1);
            },
            reader.onerror = error => console.log(error);
    };
}

There are two downsides with this solution.

The first one is related with the image rotation, due to ignoring EXIF data. I couldn't tackle this issue, and wasn't so important in my use case, but will be glad to hear any feedback.

The second downside is the lack of support foe IE/Edge (not the Chrome based version though), and I won't put any time on that.

Laravel Eloquent Sum of relation's column

Also using query builder

DB::table("rates")->get()->sum("rate_value")

To get summation of all rate value inside table rates.

To get summation of user products.

DB::table("users")->get()->sum("products")

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

Calculate average in java

for 1. the number of integers read in, you can just use length property of array like :

int count = args.length

which gives you no of elements in an array. And 2. to calculate average value : you are doing in correct way.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Note that this last variable allows you to for example run Android Studio with Java 7 on OSX (which normally picks Java 6 from the version specified in Info.plist):

$ export STUDIO_JDK=/Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk

$ open /Applications/Android\ Studio.app

Worked for me

How do I get the last four characters from a string in C#?

I threw together some code modified from various sources that will get the results you want, and do a lot more besides. I've allowed for negative int values, int values that exceed the length of the string, and for end index being less than the start index. In that last case, the method returns a reverse-order substring. There are plenty of comments, but let me know if anything is unclear or just crazy. I was playing around with this to see what all I might use it for.

    /// <summary>
    /// Returns characters slices from string between two indexes.
    /// 
    /// If start or end are negative, their indexes will be calculated counting 
    /// back from the end of the source string. 
    /// If the end param is less than the start param, the Slice will return a 
    /// substring in reverse order.
    /// 
    /// <param name="source">String the extension method will operate upon.</param>
    /// <param name="startIndex">Starting index, may be negative.</param>
    /// <param name="endIndex">Ending index, may be negative).</param>
    /// </summary>
    public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
    {
        // If startIndex or endIndex exceeds the length of the string they will be set 
        // to zero if negative, or source.Length if positive.
        if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
        if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;

        // Negative values count back from the end of the source string.
        if (startIndex < 0) startIndex = source.Length + startIndex;
        if (endIndex < 0) endIndex = source.Length + endIndex;         

        // Calculate length of characters to slice from string.
        int length = Math.Abs(endIndex - startIndex);
        // If the endIndex is less than the startIndex, return a reversed substring.
        if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();

        return source.Substring(startIndex, length);
    }

    /// <summary>
    /// Reverses character order in a string.
    /// </summary>
    /// <param name="source"></param>
    /// <returns>string</returns>
    public static string Reverse(this string source)
    {
        char[] charArray = source.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }

    /// <summary>
    /// Verifies that the index is within the range of the string source.
    /// </summary>
    /// <param name="source"></param>
    /// <param name="index"></param>
    /// <returns>bool</returns>
    public static bool ExceedsLength(this string source, int index)
    {
        return Math.Abs(index) > source.Length ? true : false;
    }

So if you have a string like "This is an extension method", here are some examples and results to expect.

var s = "This is an extension method";
// If you want to slice off end characters, just supply a negative startIndex value
// but no endIndex value (or an endIndex value >= to the source string length).
Console.WriteLine(s.Slice(-5));
// Returns "ethod".
Console.WriteLine(s.Slice(-5, 10));
// Results in a startIndex of 22 (counting 5 back from the end).
// Since that is greater than the endIndex of 10, the result is reversed.
// Returns "m noisnetxe"
Console.WriteLine(s.Slice(2, 15));
// Returns "is is an exte"

Hopefully this version is helpful to someone. It operates just like normal if you don't use any negative numbers, and provides defaults for out of range params.

How to check if text fields are empty on form submit using jQuery?

A simple solution would be something like this

$( "form" ).on( "submit", function() { 

   var has_empty = false;

   $(this).find( 'input[type!="hidden"]' ).each(function () {

      if ( ! $(this).val() ) { has_empty = true; return false; }
   });

   if ( has_empty ) { return false; }
});

Note: The jQuery.on() method is only available in jQuery version 1.7+, but it is now the preferred method of attaching event handlers.

This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one).

Or, you could look at the jQuery validate plugin. It does this and a lot more.

NB: This type of technique should always be used in conjunction with server side validation.

Is it possible to use "return" in stored procedure?

In Stored procedure, you return the values using OUT parameter ONLY. As you have defined two variables in your example:

   outstaticip OUT VARCHAR2, outcount OUT NUMBER

Just assign the return values to the out parameters i.e. outstaticip and outcount and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.

If you want to have RETURN value as return from the PL/SQL call, then use FUNCTION. Please note that in case, you would be able to return only one variable as return variable.

How to merge remote master to local branch

git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master> 

If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

Counting duplicates in Excel

If you perhaps also want to eliminate all of the duplicates and keep only a single one of each

Change the formula =COUNTIF(A:A,A2) to =COUNIF($A$2:A2,A2) and drag the formula down. Then autofilter for anything greater than 1 and you can delete them.

Waiting for HOME ('android.process.acore') to be launched

This problem occurs because while creating the AVD manager in the "Create new Android virtual device(AVD)" dialog window ,"Snapshot" was marked as "Enabled" by me.

Solution:

Create a new AVD manager with the "Enabled" checkbox not checked and then try running the project with the newly created AVD manager as "Target" , the problem will not occur anymore

anchor jumping by using javascript

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

On the .html file I have:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.

I use Google Chrome.

Note: This idea comes from linking on the same page using

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?

Why Git is not allowing me to commit even after configuration?

Do you have a local user.name or user.email that's overriding the global one?

git config --list --global | grep user
  user.name=YOUR NAME
  user.email=YOUR@EMAIL
git config --list --local | grep user
  user.name=YOUR NAME
  user.email=

If so, remove them

git config --unset --local user.name
git config --unset --local user.email

The local settings are per-clone, so you'll have to unset the local user.name and user.email for each of the repos on your machine.

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Hide div by default and show it on click with bootstrap

Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.

  1. You need to make sure the target div has an ID.
  2. Bootstrap has a class "collapse", this will hide your block by default. If you want your div to be collapsible AND be shown by default you need to add "in" class to the collapse. Otherwise the toggle behavior will not work properly.
  3. Then, on your hyperlink (also works for buttons), add an href attribute that points to your target div.
  4. Finally, add the attribute data-toggle="collapse" to instruct Bootstrap to add an appropriate toggle script to this tag.

Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):

<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
    This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
    This div (Bar) is shown by default and can toggle
</div>

Using Python's ftplib to get a directory listing, portably

There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.

Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.

How do I run a simple bit of code in a new thread?

There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.

There is a good async method article at the Code Project web site that describes the various methods and provides sample code.

Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

single line comment in HTML

No, <!-- ... --> is the only comment syntax in HTML.

How to specify test directory for mocha?

If you are using nodejs, in your package.json under scripts

  1. For global (-g) installations: "test": "mocha server-test" or "test": "mocha server-test/**/*.js" for subdocuments
  2. For project installations: "test": "node_modules/mocha/bin/mocha server-test" or "test": "node_modules/mocha/bin/mocha server-test/**/*.js" for subdocuments

Then just run your tests normally as npm test

How do I list all the columns in a table?

For MS SQL Server:

select * from information_schema.columns where table_name = 'tableName'

How to SUM two fields within an SQL query

SUM is used to sum the value in a column for multiple rows. You can just add your columns together:

select tblExportVertexCompliance.TotalDaysOnIncivek + tblExportVertexCompliance.IncivekDaysOtherSource AS [Total Days on Incivek]

How to block users from closing a window in Javascript?

This will pop a dialog asking the user if he really wants to close or stay, with a message.

var message = "You have not filled out the form.";
window.onbeforeunload = function(event) {
    var e = e || window.event;
    if (e) {
        e.returnValue = message;
    }
    return message;
};

You can then unset it before the form gets submitted or something else with

window.onbeforeunload = null;

Keep in mind that this is extremely annoying. If you are trying to force your users to fill out a form that they don't want to fill out, then you will fail: they will find a way to close the window and never come back to your mean website.

A project with an Output Type of Class Library cannot be started directly

Error solutions is that you have already open your project but by mistake you have selected another class library .. that's reason this error is showing ... so what u need to do you u just select u r project then right click on u r project

after right click u can see the list box and select the "Set as start up project " option .

Saikat Banik

adding 30 minutes to datetime php/mysql

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);

Check Whether a User Exists

Using sed:

username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
    echo "User [$username] already exists"
else
    echo "User [$username] doesn't exist"
fi

python object() takes no parameters error

I struggled for a while about this. Stupid rule for __init__. It is two "_" together to be "__"

Maximum Length of Command Line String

Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.

MongoDB query with an 'or' condition

Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

How to run stored procedures in Entity Framework Core?

To execute the stored procedures, use FromSql method which executes RAW SQL queries

e.g.

    var products= context.Products
        .FromSql("EXECUTE dbo.GetProducts")
        .ToList();

To use with parameters

    var productCategory= "Electronics";

    var product = context.Products
        .FromSql("EXECUTE dbo.GetProductByCategory {0}", productCategory)
        .ToList();

or

    var productCategory= new SqlParameter("productCategory", "Electronics");

    var product = context.Product
        .FromSql("EXECUTE dbo.GetProductByName  @productCategory", productCategory)
        .ToList();

There are certain limitations to execute RAW SQL queries or stored procedures. You can’t use it for INSERT/UPDATE/DELETE. if you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand

    var categoryName = "Electronics";
    dataContext.Database
               .ExecuteSqlCommand("dbo.InsertCategory @p0", categoryName);

Get the data received in a Flask request

If the body is recognized as form data, it will be in request.form. If it's JSON, it will be in request.get_json(). Otherwise the raw data will be in request.data. If you're not sure how data will be submitted, you can use an or chain to get the first one with data.

def get_request_data():
    return (
        request.args
        or request.form
        or request.get_json(force=True, silent=True)
        or request.data
    )

request.args contains args parsed from the query string, regardless of what was in the body, so you would remove that from get_request_data() if both it and a body should data at the same time.

What does "while True" mean in Python?

In this context, I suppose it could be interpreted as

do
...
while cmd  != 'e' 

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

Using pointer to char array, values in that array can be accessed?

When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:

printf("\nvalue:%c", (*ptr)[0]); , which is the same as *((*ptr)+0)

Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.

char arr[5] = {'a','b','c','d','e',0}; 
char *ptr = arr; //same as char *ptr = &arr[0]

printf("\nvalue:%c", ptr[0]);

How to use Collections.sort() in Java?

Use the method that accepts a Comparator when you want to sort in something other than natural order.

Collections.sort(List, Comparator)

Writing a Python list of lists to a csv file

Python's built-in CSV module can handle this easily:

import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

Update for Python 3

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

Cookie blocked/not saved in IFRAME in Internet Explorer

A better solution would be to make an Ajax call inside the iframe to the page that would get/set cookies...

Border around each cell in a range

xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid

Using BufferedReader to read Text File

Maybe you mean this:

public class Reader {

public static void main(String[]args) throws IOException{

    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);
    String line = br.readLine();
    while (line!=null) {
        System.out.println(line);
        line = br.readLine();
    }
    in.close();

}

How to get last key in an array?

As of PHP7.3 you can directly access the last key in (the outer level of) an array with array_key_last()

The definitively puts much of the debate on this page to bed. It is hands-down the best performer, suffers no side effects, and is a direct, intuitive, single-call technique to deliver exactly what this question seeks.

A rough benchmark as proof: https://3v4l.org/hO1Yf

array_slice() + key():  1.4
end() + key():         13.7
array_key_last():       0.00015

*test array contains 500000 elements, microtime repeated 100x then averaged then multiplied by 1000 to avoid scientific notation. Credit to @MAChitgarha for the initial benchmark commented under @TadejMagajna's answer.

This means you can retrieve the value of the final key without:

  1. moving the array pointer (which requires two lines of code) or
  2. sorting, reversing, popping, counting, indexing an array of keys, or any other tomfoolery

This function was long overdue and a welcome addition to the array function tool belt that improves performance, avoids unwanted side-effects, and enables clean/direct/intuitive code.

Here is a demo:

$array = ["a" => "one", "b" => "two", "c" => "three"];
if (!function_exists('array_key_last')) {
    echo "please upgrade to php7.3";
} else {
    echo "First Key: " , key($array) , "\n";
    echo "Last Key: " , array_key_last($array) , "\n";
    next($array);                 // move array pointer to second element
    echo "Second Key: " , key($array) , "\n";
    echo "Still Last Key: " , array_key_last($array);
}

Output:

First Key: a
Last Key: c     // <-- unaffected by the pointer position, NICE!
Second Key: b
Last Key: c     // <-- unaffected by the pointer position, NICE!

Some notes:

  • array_key_last() is the sibling function of array_key_first().
  • Both of these functions are "pointer-ignorant".
  • Both functions return null if the array is empty.
  • Discarded sibling functions (array_value_first() & array_value_last()) also would have offered the pointer-ignorant access to bookend elements, but they evidently failed to garner sufficient votes to come to life.

Here are some relevant pages discussing the new features:

p.s. If anyone is weighing up some of the other techniques, you may refer to this small collection of comparisons: (Demo)

Duration of array_slice() + key():     0.35353660583496
Duration of end() + key():             6.7495584487915
Duration of array_key_last():          0.00025749206542969
Duration of array_keys() + end():      7.6123380661011
Duration of array_reverse() + key():   6.7875385284424
Duration of array_slice() + foreach(): 0.28870105743408

Android Gradle Could not reserve enough space for object heap

Faced this issue on Android studio 4.1, windows 10.

The solution that worked for me:

1 - Go to gradle.properties file which is in the root directory of the project.

2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.

3 - Now close any open project from File -> close project.

4 - On the Welcome window, Go to Configure > Settings.

5 - Go to Build, Execution, Deployment > Compiler

6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.

Now close the android studio and restart it. The issue will be gone.

How to detect query which holds the lock in Postgres?

Since 9.6 this is a lot easier as it introduced the function pg_blocking_pids() to find the sessions that are blocking another session.

So you can use something like this:

select pid, 
       usename, 
       pg_blocking_pids(pid) as blocked_by, 
       query as blocked_query
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;

How to disable Home and other system buttons in Android?

It used to be possible to disable the Home button, but now it isn't. It's due to malicious software that would trap the user.

You can see more detailes here: Disable Home button in Android 4.0+

Finally, the Back button can be disabled, as you can see in this other question: Disable back button in android

Length of array in function argument

This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:

void func(int A[]) 
// should be instead: void func(int * A, const size_t elemCountInA)

They are very few cases, where you don't need this, like when you're using multidimensional arrays:

void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"

Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:

void vec_add(float out[3], float in0[3], float in1[3])

is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):

void vec_add(float * out, float * in0, float * in1)

If you were to use C++, then you can actually capture the array size and get what you expect:

template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
    for (size_t i = 0; i < N; i++) 
        out[i] = in0[i] + in1[i];
}

In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.

JPG vs. JPEG image formats

There's no difference between the file extensions, and they are used interchangeably. I guess the 3-letter version stems from the DOS era...

However, there are different "flavors" of JPEG files. Most notably the JFIF standard and the EXIF standard. Most often these just use .jpg or .jpeg as file extensions, JFIF sometimes uses .jif or .jfif.

How to copy a file from remote server to local machine?

I would recommend to use sftp, use this command sftp -oPort=7777 user@host where -oPort is custom port number of ssh , in case if u changed it to 7777, then u can use -oPort, else if use only port 22 then plain sftp user@host which asks for the password , then u can log in, and u can navigate to required location using cd /home/user then a simple command get table u can download it, If u want to download a directory/folder get -r someDirectory will do it. If u want the file permissions also to exist then get -Pr someDirectory. For uploading on to remote change get to put in above commands.

Why does Vim save files with a ~ extension?

The only option that worked for me was to put this line in my ~/.vimrc file

set noundofile

The other options referring to backup files did not prevent the creation of the temp files ending in ~ (tilde)

How to use curl in a shell script?

url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

How to get the Development/Staging/production Hosting Environment in ConfigureServices

You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    ...your code here...
    CurrentEnvironment = env;
}

private IHostingEnvironment CurrentEnvironment{ get; set; } 

public void ConfigureServices(IServiceCollection services)
{
    string envName = CurrentEnvironment.EnvironmentName;
    ... your code here...
}

How do I determine if a port is open on a Windows server?

On a Windows machine you can use PortQry from Microsoft to check whether an application is already listening on a specific port using the following command:

portqry -n 11.22.33.44 -p tcp -e 80

Get pixel color from canvas, on mousemove

Merging various references found here in StackOverflow (including the article above) and in other sites, I did so using javascript and JQuery:

<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var img = new Image();
        img.src = 'photo_apple.jpg';
        context.drawImage(img, 0, 0);
    };

    function findPos(obj){
    var current_left = 0, current_top = 0;
    if (obj.offsetParent){
        do{
            current_left += obj.offsetLeft;
            current_top += obj.offsetTop;
        }while(obj = obj.offsetParent);
        return {x: current_left, y: current_top};
    }
    return undefined;
    }

    function rgbToHex(r, g, b){
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
    }

$('#myCanvas').click(function(e){
    var position = findPos(this);
    var x = e.pageX - position.x;
    var y = e.pageY - position.y;
    var coordinate = "x=" + x + ", y=" + y;
    var canvas = this.getContext('2d');
    var p = canvas.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>

This is my complete solution. Here I only used canvas and one image, but if you need to use <map> over the image, it's possible too.

How to calculate the sum of the datatable column in asp.net?

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))

json_decode returns NULL after webservice call

EDIT: Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as ? here.

Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).

string(62) "?{"action":"set","user":"123123123123","status":"OK"}"
            ^
            |
            This is the UTF-8 BOM

As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

How can I rename a project folder from within Visual Studio?

I often had the same problem of renaming a project in Visual Studio and editing the folder name, project name, and .sln file in order to accomplish that. I just wrote a VBScript script that accomplishes all that. You have to be careful with the strings you choose for replacing.

You just have to put the .vbs file in the same directory as the .sln file of the solution.

' Script parameters'
Solution = "Rename_Visual_Studio_Project" '.sln'
Project = "Rename_Visual_Studio_Project" '.csproj'
NewProject = "SUCCESS"

Const ForReading = 1
Const ForWriting = 2

Set objFso = CreateObject("Scripting.FileSystemObject")
scriptDirr = objFso.GetParentFolderName(wscript.ScriptFullName)

' Rename the all project references in the .sln file'
Set objFile = objFso.OpenTextFile(scriptDirr + "\" + Solution + ".sln", ForReading)
fileText = objFile.ReadAll
newFileText = Replace(fileText, Project, NewProject)
Set objFile = objFSO.OpenTextFile(scriptDirr + "\" + Solution + ".sln", ForWriting)
objFile.WriteLine(newFileText)
objFile.Close

' Rename the .csproj file'
objFso.MoveFile scriptDirr + "\" + Project + "\" + Project + ".csproj", scriptDirr + "\" + Project + "\" + NewProject + ".csproj"

' Rename the folder of the .csproj file'
objFso.MoveFolder scriptDirr + "\" + Project, scriptDirr + "\" + NewProject

I forgot the password I entered during postgres installation

This is what worked for me on windows:

Edit the pg_hba.conf file locates at C:\Program Files\PostgreSQL\9.3\data.

# IPv4 local connections: host all all 127.0.0.1/32 trust

Change the method from trust to md5 and restart the postgres service on windows.

After that, you can login using postgres user without password by using pgadmin. You can change password using File->Change password.

If postgres user does not have superuser privileges , then you cannot change the password. In this case , login with another user(pgsql)with superuser access and provide privileges to other users by right clicking on users and selecting properties->Role privileges.

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

For the Eclipse running on IBM JDK the following 2 lines are mandatory in eclipse.ini after -vmargs:

-Dhttps.protocols=TLSv1.1,TLSv1.2
-Dcom.ibm.jsse2.overrideDefaultTLS=true

Tips for debugging .htaccess rewrite rules

as pointed out by @JCastell, the online tester does a good job of testing individual redirects against an .htaccess file. However, more interesting is the api exposed which can be used to batch test a list of urls using a json object. However, to make it more useful, I have written a small bash script file which makes use of curl and jq to submit a list of urls and parse the json response into a CSV formated output with the line number and rule matched in the htaccess file along with the redirected url, making it quite handy to compare a list of urls in a spreadsheet and quickly determine which rules are not working.

Working with TIFFs (import, export) in Python using numpy

PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images(): 
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)

You can install PyLibTiff with

pip3 install numpy libtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

Any way to select without causing locking in MySQL?

Use

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.

Version 5.0 Docs are here.

Version 5.1 Docs are here.

Concat scripts in order with Gulp

For me I had natualSort() and angularFileSort() in pipe which was reordering the files. I removed it and now it works fine for me

$.inject( // app/**/*.js files
    gulp.src(paths.jsFiles)
      .pipe($.plumber()), // use plumber so watch can start despite js errors
      //.pipe($.naturalSort())
      //.pipe($.angularFilesort()),
    {relative: true}))

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

"Eliminate render-blocking CSS in above-the-fold content"

How I got a 99/100 on Google Page Speed (for mobile)

TLDR: Compress and embed your entire css script between your <style></style> tags.


I've been chasing down that elusive 100/100 score for about a week now. Like you, the last remaining item was was eliminating "render-blocking css for above the fold content."

Surely there is an easy solve?? Nope. I tried out Filament group's loadCSS solution. Too much .js for my liking.

What about async attributes for css (like js)? They don't exist.

I was ready to give up. Then it dawned on me. If linking the script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.

It seemed absolutely WRONG to embed 1263 lines of CSS in my style tag. But I gave it a whirl. I compressed it (and prefixed it) first using:

postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/ See the NPM postcss package.

Now it was just one LONG line of space-less css. I plopped the css in <style>your;great-wall-of-china-long;css;here</style> tags on my home page. Then I re-analyzed with page speed insights.

I went from 90/100 to 99/100 on mobile!!!

This goes against everything in me (and probably you). But it SOLVED the problem. I'm just using it on my home page for now and including the compressed css programmatically via a PHP include.

YMMV (your mileage may vary) pending on the length of your css. Google may ding you for too much above the fold content. But don't assume; test!

Notes

  1. I'm only doing this on my home page for now so people get a FAST render on my most important page.

  2. Your css won't get cached. I'm not too worried though. The second they hit another page on my site, the .css will get cached (see Note 1).

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

Windows error 2 occured while loading the Java VM

We could not uninstall a program, stuck with the "Windows error 2 cannot load Java VM". Added the Java path to the PATH variable, uninstalled and re-installed Java 8, the problem would not go away.

Then I found this solution online and it worked for us on the first shot: - Uninstall Java 8 - Install Java 6

Whatever the reason, with Java 6, the error went away, we uninstalled the program, and re-installed Java 8.

Catching "Maximum request length exceeded"

It can be checked via:

        var httpException = ex as HttpException;
        if (httpException != null)
        {
            if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
            {
                // Request too large

                return;

            }
        }

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID

OR

global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();

How to SELECT by MAX(date)?

SELECT report_id, computer_id, date_entered
FROM reports
WHERE date_entered = (
    SELECT date_entered 
    FROM reports 
    ORDER date_entered 
    DESC LIMIT 1
)

Take a screenshot via a Python script on Linux

Just for completeness: Xlib - But it's somewhat slow when capturing the whole screen:

from Xlib import display, X
import Image #PIL

W,H = 200,200
dsp = display.Display()
try:
    root = dsp.screen().root
    raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
    image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")
    image.show()
finally:
    dsp.close()

One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.


Edit: We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:

#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c

void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) 
{
   Display *display = XOpenDisplay(NULL);
   Window root = DefaultRootWindow(display);

   XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);

   unsigned long red_mask   = image->red_mask;
   unsigned long green_mask = image->green_mask;
   unsigned long blue_mask  = image->blue_mask;
   int x, y;
   int ii = 0;
   for (y = 0; y < H; y++) {
       for (x = 0; x < W; x++) {
         unsigned long pixel = XGetPixel(image,x,y);
         unsigned char blue  = (pixel & blue_mask);
         unsigned char green = (pixel & green_mask) >> 8;
         unsigned char red   = (pixel & red_mask) >> 16;

         data[ii + 2] = blue;
         data[ii + 1] = green;
         data[ii + 0] = red;
         ii += 3;
      }
   }
   XDestroyImage(image);
   XDestroyWindow(display, root);
   XCloseDisplay(display);
}

And then the python-file:

import ctypes
import os
from PIL import Image

LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)

def grab_screen(x1,y1,x2,y2):
    w, h = x2-x1, y2-y1
    size = w * h
    objlength = size * 3

    grab.getScreen.argtypes = []
    result = (ctypes.c_ubyte*objlength)()

    grab.getScreen(x1,y1, w, h, result)
    return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
    
if __name__ == '__main__':
  im = grab_screen(0,0,1440,900)
  im.show()

How to position background image in bottom right corner? (CSS)

Voilà:

body {
   background-color: #000; /*Default bg, similar to the background's base color*/
   background-image: url("bg.png");
   background-position: right bottom; /*Positioning*/
   background-repeat: no-repeat; /*Prevent showing multiple background images*/
}

The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position

C# - Simplest way to remove first occurrence of a substring from another string

string myString = sourceString.Remove(sourceString.IndexOf(removeString),removeString.Length);

EDIT: @OregonGhost is right. I myself would break the script up with conditionals to check for such an occurence, but I was operating under the assumption that the strings were given to belong to each other by some requirement. It is possible that business-required exception handling rules are expected to catch this possibility. I myself would use a couple of extra lines to perform conditional checks and also to make it a little more readable for junior developers who may not take the time to read it thoroughly enough.

How to send a POST request from node.js Express?

in your server side the code looks like:

var request = require('request');

app.post('/add', function(req, res){
  console.log(req.body);
  request.post(
    {
    url:'http://localhost:6001/add',
    json: {
      unit_name:req.body.unit_name,
      unit_price:req.body.unit_price
        },
    headers: {
        'Content-Type': 'application/json'
    }
    },
  function(error, response, body){
    // console.log(error);
    // console.log(response);
    console.log(body);
    res.send(body);
  });
  // res.send("body");
});

in receiving end server code looks like:

app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});

Schema is just two properties unit_name and unit_price.

How to build x86 and/or x64 on Windows from command line with CMAKE?

This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.

To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.

For CMake 3.13 or newer, run the following commands:

cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release

For earlier versions of CMake, run the following commands:

mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release

CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build followed by the build directory. The --config option specifies the build configuration.

How to check for file lock?

You could call LockFile via interop on the region of file you are interested in. This will not throw an exception, if it succeeds you will have a lock on that portion of the file (which is held by your process), that lock will be held until you call UnlockFile or your process dies.

Is there an equivalent of 'which' on the Windows command line?

Here is a function which I made to find executable similar to the Unix command 'WHICH`

app_path_func.cmd:

@ECHO OFF
CLS

FOR /F "skip=2 tokens=1,2* USEBACKQ" %%N IN (`reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\%~1" /t REG_SZ  /v "Path"`) DO (
 IF /I "%%N" == "Path" (
  SET wherepath=%%P%~1
  GoTo Found
 )
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES(x86)%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%WINDIR%" %~1`) DO (
 SET wherepath=%%F
 GoTo Found
)

:Found
SET %2=%wherepath%
:End

Test:

@ECHO OFF
CLS

CALL "app_path_func.cmd" WINWORD.EXE PROGPATH
ECHO %PROGPATH%

PAUSE

Result:

C:\Program Files (x86)\Microsoft Office\Office15\
Press any key to continue . . .

https://www.freesoftwareservers.com/display/FREES/Find+Executable+via+Batch+-+Microsoft+Office+Example+-+WINWORD+-+Find+Microsoft+Office+Path

What is the proper way to comment functions in Python?

Use docstrings.

This is the built-in suggested convention in PyCharm for describing function using docstring comments:

def test_function(p1, p2, p3):
    """
    test_function does blah blah blah.

    :param p1: describe about parameter p1
    :param p2: describe about parameter p2
    :param p3: describe about parameter p3
    :return: describe what it returns
    """ 
    pass

C++ performance vs. Java/C#

I don't know either...my Java programs are always slow. :-) I've never really noticed C# programs being particularly slow, though.

How do I create a ListView with rounded corners in Android?

There are different ways to achieve it. The latest approach is using CardView for each ListItem component. Here are some steps.

  1. Create a layout resource file; let's name it "listitem.xml
  2. Copy and paste the under enclosed Listitem.xml layout body into it.
  3. Create RowItem class for each listitem data; later you will instantiate this to assign values for each list item. Check Code below, RowItem.class.
  4. Create a custom ListAdapter; let's name it ListAdapter.class, and inflate this (#1) list item layout for each list item (Check the second code snippet for this one)
  5. Set this adapter (#3) the way you set default adapters inside an activity the listview belongs to. maybe the only difference would be you first have to instantiate RowItem class with values and add RowItem object to your adapter then notify your adapter that the data is changed.
**listitem.xml**
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:alignmentMode="alignMargins"
            android:columnCount="1"
            android:columnOrderPreserved="false"
            android:rowCount="1">
            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:layout_margin="6dp"
                app:cardCornerRadius="8dp"
                app:cardElevation="6dp">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">
                    <ImageView
                        android:id="@+id/sampleiconimageID"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:padding="5dp"/>
                    <LinearLayout android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
                        <TextView
                            android:id="@+id/titleoflistview"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Main Heading"
                            android:textStyle="bold" />
                        <TextView
                            android:id="@+id/samplesubtitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Sub Heading"
                           />
                        </LinearLayout>
                </LinearLayout>
            </androidx.cardview.widget.CardView>
        </GridLayout>
    </LinearLayout>

RowItem.Class

public class RowItem {
    private String heading;
    private String subHeading;
    private int smallImageName;
    private String datetime;
    private int count;

    public void setHeading( String theHeading ) {
        this.heading = theHeading;
    }

    public String getHeading() {
        return this.heading;
    }
    public void setSubHeading( String theSubHeading ) {

        this.subHeading = theSubHeading;

    }

    public String getSubHeading( ) {

        return this.subHeading;

    }

    public void setSmallImageName(int smallName) {

        this.smallImageName = smallName;

    }

    public int getSmallImageName() {

        return this.smallImageName;

    }

    public void setDate(String datetime) {
        this.datetime = datetime;
    }

    public String getDate() {
        return this.datetime;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getCount() {
        return this.count;
    }

}

Sample ListAdapter

public class ListAdapter extends BaseAdapter {
    private ArrayList<RowItem> singleRow;
    private LayoutInflater thisInflater;

    public ListAdapter(Context context, ArrayList<RowItem> aRow){

        this.singleRow = aRow;
        thisInflater = ( LayoutInflater.from(context) );
    }
    @Override
    public int getCount() {
        return singleRow.size();    }

    @Override
    public Object getItem(int position) {
        return singleRow.get( position );    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            view = thisInflater.inflate( R.layout.mylist2, parent, false );
            //set listview objects here
            //example

            TextView titleText = (TextView) view.findViewById(R.id.titleoflistview);
           
            RowItem currentRow = (RowItem) getItem(position);
            
            titleText.setText( currentRow.getHeading() );
          
        }

        return view;

//        LayoutInflater inflater=.getLayoutInflater();
//        View rowView=inflater.inflate(R.layout.mylist, null,true);
//

//        titleText.setText(maintitle[position]);
//        subtitleText.setText(subtitle[position]);

//        return null;

    };
}

sudo in php exec()

The best secure method is to use the crontab. ie Save all your commands in a database say, mysql table and create a cronjob to read these mysql entreis and execute via exec() or shell_exec(). Please read this link for more detailed information.

          • killProcess.php

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

MySQL match() against() - order by relevance and column?

Just adding for who might need.. Don't forget to alter the table!

ALTER TABLE table_name ADD FULLTEXT(column_name);

How to replace innerHTML of a div using jQuery?

There are already answers which give how to change Inner HTML of element.

But I would suggest, you should use some animation like Fade Out/ Fade In to change HTML which gives good effect of changed HTML rather instantly changing inner HTML.

Use animation to change Inner HTML

$('#regTitle').fadeOut(500, function() {
    $(this).html('Hello World!').fadeIn(500);
});

If you have many functions which need this, then you can call common function which changes inner Html.

function changeInnerHtml(elementPath, newText){
    $(elementPath).fadeOut(500, function() {
        $(this).html(newText).fadeIn(500);
    });
}

Errors: Data path ".builders['app-shell']" should have required property 'class'

Try update the package.json file from

  "@angular-devkit/build-angular": "^0.800.1" 

to

  "@angular-devkit/build-angular": "^0.12.4"

Then run npm install in the command line.

CSS Grid Layout not working in IE11 even with prefixes

To support IE11 with auto-placement, I converted grid to table layout every time I used the grid layout in 1 dimension only. I also used margin instead of grid-gap.

The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/

Replace missing values with column mean

A one-liner using tidyr's replace_na is

library(tidyr)
replace_na(mtcars,as.list(colMeans(mtcars,na.rm=T)))

If your df has columns that are non-numeric, this takes a little bit more work than a one-liner.

mean_to_fill <- select_if(ungroup(df), is.numeric) %>%
 colMeans(na.rm=T)

bind_cols(select(df, group1, group2, group3),
          select_if(ungroup(df), is.numeric) %>% 
            tidyr::replace_na(as.list(mean_to_fill))
          ) 

Automatically set appsettings.json for dev and release environments in asp.net core?

You may use conditional compilation:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
#if SOME_BUILD_FLAG_A
    .AddJsonFile($"appsettings.flag_a.json", optional: true)
#else
    .AddJsonFile($"appsettings.no_flag_a.json", optional: true)
#endif
    .AddEnvironmentVariables();
    this.configuration = builder.Build();
}

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

Simplest way to download and unzip files in Node.js cross-platform?

I tried a few of the nodejs unzip libraries including adm-zip and unzip, then settled on extract-zip which is a wrapper around yauzl. Seemed the simplest to implement.

https://www.npmjs.com/package/extract-zip

var extract = require('extract-zip')
extract(zipfile, { dir: outputPath }, function (err) {
   // handle err
})

Select values from XML field in SQL Server 2008

Given that the XML field is named 'xmlField'...

SELECT 
[xmlField].value('(/person//firstName/node())[1]', 'nvarchar(max)') as FirstName,
[xmlField].value('(/person//lastName/node())[1]', 'nvarchar(max)') as LastName
FROM [myTable]

How can I compile my Perl script so it can be executed on systems without perl installed?

On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV

See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL

failed to find target with hash string 'android-22'

Just click on the link written in the error:

Open Android SDK Manager

and it will show you the dialogs that will help you to install the required sdk for your project.

Convert string to int array using LINQ

Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();

Is it possible to make desktop GUI application in .NET Core?

I'm working on a project that might help: https://github.com/gkmo/CarloSharp

The following application is written in .NET with the UI in HTML, JavaScript, and CSS (Angular).

Enter image description here

How to remove all duplicate items from a list

Use set():

woduplicates = set(lseparatedOrblist)

Returns a set without duplicates. If you, for some reason, need a list back:

woduplicates = list(set(lseperatedOrblist))

This will, however, have a different order than your original list.

Replace Multiple String Elements in C#

There is one thing that may be optimized in the suggested solutions. Having many calls to Replace() makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.

LinkButton Send Value to Code Behind OnClick

Try and retrieve the text property of the link button in the code behind:

protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
   string val = ((LinkButton)sender).Text
}

SSL InsecurePlatform error when using Requests package

Requests 2.6 introduced this warning for users of python prior to 2.7.9 with only stock SSL modules available.

Assuming you can't upgrade to a newer version of python, this will install more up-to-date python SSL libraries:

pip install --upgrade ndg-httpsclient 

HOWEVER, this may fail on some systems without the build-dependencies for pyOpenSSL. On debian systems, running this before the pip command above should be enough for pyOpenSSL to build:

apt-get install python-dev libffi-dev libssl-dev

How to center a (background) image within a div?

This works for me :

<style>
   .WidgetBody
        {   
            background: #F0F0F0;
            background-image:url('images/mini-loader.gif');
            background-position: 50% 50%;            
            background-repeat:no-repeat;            
        }
</style>        

Is there a max array length limit in C++?

i would go around this by making a 2d dynamic array:

long long** a = new long long*[x];
for (unsigned i = 0; i < x; i++) a[i] = new long long[y];

more on this here https://stackoverflow.com/a/936702/3517001

Arduino error: does not name a type?

More recently, I have found that other factors will also cause this error. I had an AES.h, AES.cpp containing a AES class and it gave this same unhelpful error. Only when I renamed to Encryption.h, Encryption.cpp and Encryption as the class name did it suddenly start working. There were no other code changes.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Try to set Silverlight Application Project as as a startup project: right click on project -> 'Set As Startup project. Then press F5 and see if you can catch breakpoints...

Try to delete browsing/temp data in your browser each time You make changes to silverlight application

How to Use -confirm in PowerShell

Here's a solution I've used, similiar to Ansgar Wiechers' solution;

$title = "Lorem"
$message = "Ipsum"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "This means Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "This means No"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $Options, 0)

Switch ($result)
     {
          0 { "You just said Yes" }
          1 { "You just said No" }
     }

Start script missing error when running npm start

In my case, it wasn't working because I used "scripts" twice. After combining - it is ok.

"scripts": {
  "test": "make test",
  "start": "node index.js"
}

No resource found - Theme.AppCompat.Light.DarkActionBar

If you are using Android Studio then just add the dependency

dependencies {
     implementation 'com.android.support:appcompat-v7:25.0.1'
}

to app/build.gradle. And that will work

Create an ArrayList of unique values

Use Set

      ...
      Set<String> list = new HashSet<>();
      while (s.hasNext()){
         list.add(s.next());
      }
      ...

how to define ssh private key for servers fetched by dynamic inventory in files

I'm using the following configuration:

#site.yml:
- name: Example play
  hosts: all
  remote_user: ansible
  become: yes
  become_method: sudo
  vars:
    ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"

Proxy setting for R

For RStudio just you have to do this:

Firstly, open RStudio like always, select from the top menu:

Tools-Global Options-Packages

Uncheck the option: Use Internet Explorer library/proxy for HTTP

And then close the Rstudio, furthermore you have to:

  1. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents. Note that if it does not exist you can creat it just by writing this command in RStudio:

    file.edit('~/.Renviron')
    
  2. Add these two lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy="http://user_id:password@your_proxy:your_port"
    

And that's it..??!!!

How to remove indentation from an unordered list item?

Add this to your CSS:

ul { list-style-position: inside; }

This will place the li elements in the same indent as other paragraphs and text.

Ref: http://www.w3schools.com/cssref/pr_list-style-position.asp

How do I print my Java object without getting "SomeType@2f92e0f4"?

If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is

    public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.

How to make git mark a deleted and a new file as a file move?

git diff -M or git log -M should automatically detect such changes as a rename with minor changes as long as they indeed are. If your minor changes are not minor, you can reduce the similarity threashold, e.g.

$ git log -M20 -p --stat

to reduce it from the default 50% to 20%.

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

Removing "http://" from a string

Use look behinds in preg_replace to remove anything before //.

preg_replace('(^[a-z]+:\/\/)', '', $url); 

This will only replace if found in the beginning of the string, and will ignore if found later

Prevent any form of page refresh using jQuery/Javascript

Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.

However, a better solution is to synchronize the two sessions if possible like in google docs.

Remote debugging a Java application

I'd like to emphasize that order of arguments is important.

For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar command opens debugger port,

but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 command doesn't.

Binding objects defined in code-behind

Make your property "windowname" a DependencyProperty and keep the remaining same.

What is the most efficient way to create HTML elements using jQuery?

I am using jquery.min v2.0.3 . It's for me better to use following:

var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);

as following:

var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);

Processing time of first code is much lower than second code.