Programs & Examples On #Outliner

Displaying the Indian currency symbol on a website

If you are using font awesome icons, then you can use this:

To import font-awesome:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

Usage:

Current Price: <i class="fa fa-inr"></i> 400.00

will show as:

Imgur

how to destroy bootstrap modal window completely?

From what i understand, you don't wanna remove it, nor hide it ? Because you might wanna reuse it later ..but don't want it to have the old content if ever you open it up again ?

<div class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn">Close</a>
        <a href="#" class="btn btn-primary">Save changes</a>
    </div>
</div>

If you wanna use it as a dynamic template just do something like

$(selector).modal({show: true})

....

$(selector).modal({show: false})
$(".modal-body").empty()

....

$(".modal-body").append("new stuff & text")
$(selector).modal({show: true})

Where to find htdocs in XAMPP Mac

Go to Volumes Tab and click Mount

enter image description here

You can find it under Locations in the Sidebar. Click on it.

enter image description here

Open this folder: Lamp

enter image description here

You can find the htdocs folder inside Lamp, just like the below screenshot:

enter image description here

Note: I am using macOS Catalina.

What's the difference between ng-model and ng-bind

tosh's answer gets to the heart of the question nicely. Here's some additional information....

Filters & Formatters

ng-bind and ng-model both have the concept of transforming data before outputting it for the user. To that end, ng-bind uses filters, while ng-model uses formatters.

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

<div ng-bind="mystring | uppercase"></div>,

or more simply:

<div>{{mystring | uppercase}}</div>

Note that uppercase is a built-in angular filter, although you can also build your own filter.

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

Angular 1.3 also has getter/setter support for ngModel

Notepad++ add to every line

  1. Move your cursor to the start of the first line
  2. Hold down Alt + Shift and use the cursor down key to extend the selection to the end of the block

This allows you to type on every line simultaneously.

I found the solution above here.

I think this is much easier than using regex.

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

Deep copy of a dict in python

dict.copy() is a shallow copy function for dictionary
id is built-in function that gives you the address of variable

First you need to understand "why is this particular problem is happening?"

In [1]: my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}

In [2]: my_copy = my_dict.copy()

In [3]: id(my_dict)
Out[3]: 140190444167808

In [4]: id(my_copy)
Out[4]: 140190444170328

In [5]: id(my_copy['a'])
Out[5]: 140190444024104

In [6]: id(my_dict['a'])
Out[6]: 140190444024104

The address of the list present in both the dicts for key 'a' is pointing to same location.
Therefore when you change value of the list in my_dict, the list in my_copy changes as well.


Solution for data structure mentioned in the question:

In [7]: my_copy = {key: value[:] for key, value in my_dict.items()}

In [8]: id(my_copy['a'])
Out[8]: 140190444024176

Or you can use deepcopy as mentioned above.

How to make the 'cut' command treat same sequental delimiters as one?

With versions of cut I know of, no, this is not possible. cut is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'

The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\ is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?

BACKUP DATABASE go4sharepoint_1384_8481 
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT

Note there is no space between ' and C:

How to save a Seaborn plot into a file

Its also possible to just create a matplotlib figure object and then use plt.savefig(...):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

How to get C# Enum description from value?

Update

The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

In Enums.NET you'd use:

string description = ((MyEnum)value).AsString(EnumFormat.Description);

Original post

I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description

I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

How to extract Month from date in R

Her is another R base approach:

From your example: Some date:

Some_date<-"01/01/1979"

We tell R, "That is a Date"

Some_date<-as.Date(Some_date)

We extract the month:

months(Some_date)

output: [1] "January"

Finally, we can convert it to a numerical variable:

as.numeric(as.factor(months(Some_date)))

outpt: [1] 1

Turning off eslint rule for a specific line

To disable next line:

// eslint-disable-next-line no-use-before-define
var thing = new Thing();

Or use the single line syntax:

var thing = new Thing(); // eslint-disable-line no-use-before-define

See the eslint docs

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:

=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1 

This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:

=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1

For weeks beginning on Tuesday, use:

=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1

etc.

I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

Set Page Title using PHP

What about using something like:

<?php 
    $page_title = "Your page tile";
    include("navigation.php");             // if required
    echo("<title>$page_title</title>");
?>

Why a function checking if a string is empty always returns true?

PHP evaluates an empty string to false, so you can simply use:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}

Running the new Intel emulator for Android

If everything else fails, it's good to try my option and download a HAXM installer.

It needs to be copied to HAXM installation folder and then started from command line (start CMD as an Administrator). After restarting computer HAXM will be installed. It perfectly worked for me as I was having problems with installing it on my laptop.

After all simply type sc query intelhaxm in your cmd in order to check whether HAXM is installed properly.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

I was facing the same problem because some of the images are grey scale images in my data set, so i solve my problem by doing this

    from PIL import Image
    img = Image.open('my_image.jpg').convert('RGB')
    # a line from my program
    positive_images_array = np.array([np.array(Image.open(img).convert('RGB').resize((150, 150), Image.ANTIALIAS)) for img in images_in_yes_directory])

What is the difference between char s[] and char *s?

As an addition, consider that, as for read-only purposes the use of both is identical, you can access a char by indexing either with [] or *(<var> + <index>) format:

printf("%c", x[1]);     //Prints r

And:

printf("%c", *(x + 1)); //Prints r

Obviously, if you attempt to do

*(x + 1) = 'a';

You will probably get a Segmentation Fault, as you are trying to access read-only memory.

Is it possible to print a variable's type in standard C++?

Copying from this answer: https://stackoverflow.com/a/56766138/11502722

I was able to get this somewhat working for C++ static_assert(). The wrinkle here is that static_assert() only accepts string literals; constexpr string_view will not work. You will need to accept extra text around the typename, but it works:

template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
    static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
    static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
    }
}

MSVC Output:

error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...

CSS: On hover show and hide different div's at the same time?

Have you tried somethig like this?

.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}

<div class="showhim">HOVER ME
  <div class="showme">hai</div>
  <div class="hideme">bye</div>
</div>

I dont know any reason why it shouldn't be possible.

In-place type conversion of a NumPy array

Update: This function only avoids copy if it can, hence this is not the correct answer for this question. unutbu's answer is the right one.


a = a.astype(numpy.float32, copy=False)

numpy astype has a copy flag. Why shouldn't we use it ?

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

Press Ctrl+Alt+Down or Ctrl+Alt+Up to insert cursors below or above.

When should we use intern method of String on String literals

http://en.wikipedia.org/wiki/String_interning

string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

position: fixed doesn't work on iPad and iPhone

In my case, it was because the fixed element was being shown by using an animation. As stated in this link:

in Safari 9.1, having a position:fixed-element inside an animated element, may cause the position:fixed-element to not appear.

Why is Spring's ApplicationContext.getBean considered bad?

You should to use: ConfigurableApplicationContext instead of for ApplicationContext

How do I ignore files in Subversion?

You can also set a global ignore pattern in SVN's configuration file.

Forward host port to docker container

If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.

You do not need the -p option in order to expose ports from container to host. By default, all port are exposed. The -p option allows you to expose a port from the container to the outside of the host.

So, my guess is that you do not need -p at all and it should be working fine :)

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

how to zip a folder itself using java

Enhanced Java 8+ example (Forked from Nikita Koksharov's answer)

public static void pack(String sourceDirPath, String zipFilePath) throws IOException {
    Path p = Files.createFile(Paths.get(zipFilePath));
    Path pp = Paths.get(sourceDirPath);
    try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p));
        Stream<Path> paths = Files.walk(pp)) {
        paths
          .filter(path -> !Files.isDirectory(path))
          .forEach(path -> {
              ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
              try {
                  zs.putNextEntry(zipEntry);
                  Files.copy(path, zs);
                  zs.closeEntry();
            } catch (IOException e) {
                System.err.println(e);
            }
          });
    }
}

Files.walk has been wrapped in try with resources block so that stream can be closed. This resolves blocker issue identified by SonarQube. Thanks @Matt Harrison for pointing this.

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

How to convert a Hibernate proxy to a real entity object

I've written following code which cleans object from proxies (if they are not already initialized)

public class PersistenceUtils {

    private static void cleanFromProxies(Object value, List<Object> handledObjects) {
        if ((value != null) && (!isProxy(value)) && !containsTotallyEqual(handledObjects, value)) {
            handledObjects.add(value);
            if (value instanceof Iterable) {
                for (Object item : (Iterable<?>) value) {
                    cleanFromProxies(item, handledObjects);
                }
            } else if (value.getClass().isArray()) {
                for (Object item : (Object[]) value) {
                    cleanFromProxies(item, handledObjects);
                }
            }
            BeanInfo beanInfo = null;
            try {
                beanInfo = Introspector.getBeanInfo(value.getClass());
            } catch (IntrospectionException e) {
                // LOGGER.warn(e.getMessage(), e);
            }
            if (beanInfo != null) {
                for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                    try {
                        if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                            Object fieldValue = property.getReadMethod().invoke(value);
                            if (isProxy(fieldValue)) {
                                fieldValue = unproxyObject(fieldValue);
                                property.getWriteMethod().invoke(value, fieldValue);
                            }
                            cleanFromProxies(fieldValue, handledObjects);
                        }
                    } catch (Exception e) {
                        // LOGGER.warn(e.getMessage(), e);
                    }
                }
            }
        }
    }

    public static <T> T cleanFromProxies(T value) {
        T result = unproxyObject(value);
        cleanFromProxies(result, new ArrayList<Object>());
        return result;
    }

    private static boolean containsTotallyEqual(Collection<?> collection, Object value) {
        if (CollectionUtils.isEmpty(collection)) {
            return false;
        }
        for (Object object : collection) {
            if (object == value) {
                return true;
            }
        }
        return false;
    }

    public static boolean isProxy(Object value) {
        if (value == null) {
            return false;
        }
        if ((value instanceof HibernateProxy) || (value instanceof PersistentCollection)) {
            return true;
        }
        return false;
    }

    private static Object unproxyHibernateProxy(HibernateProxy hibernateProxy) {
        Object result = hibernateProxy.writeReplace();
        if (!(result instanceof SerializableProxy)) {
            return result;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private static <T> T unproxyObject(T object) {
        if (isProxy(object)) {
            if (object instanceof PersistentCollection) {
                PersistentCollection persistentCollection = (PersistentCollection) object;
                return (T) unproxyPersistentCollection(persistentCollection);
            } else if (object instanceof HibernateProxy) {
                HibernateProxy hibernateProxy = (HibernateProxy) object;
                return (T) unproxyHibernateProxy(hibernateProxy);
            } else {
                return null;
            }
        }
        return object;
    }

    private static Object unproxyPersistentCollection(PersistentCollection persistentCollection) {
        if (persistentCollection instanceof PersistentSet) {
            return unproxyPersistentSet((Map<?, ?>) persistentCollection.getStoredSnapshot());
        }
        return persistentCollection.getStoredSnapshot();
    }

    private static <T> Set<T> unproxyPersistentSet(Map<T, ?> persistenceSet) {
        return new LinkedHashSet<T>(persistenceSet.keySet());
    }

}

I use this function over result of my RPC services (via aspects) and it cleans recursively all result objects from proxies (if they are not initialized).

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

Sublime Text 3 how to change the font size of the file sidebar?

Some limited flexibility is available if your using the Afterglow Theme.

https://github.com/YabataDesign/afterglow-theme

You can edit your user preferences in the following way.

Sublime Text -> Preferences -> Settings - User:

{
    "sidebar_size_14": true
}

https://github.com/YabataDesign/afterglow-theme#sidebar-size-options

Can I get div's background-image url?

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

Simulating a click in jQuery/JavaScript on a link

Just

$("#your_item").trigger("click");

using .trigger() you can simulate many type of events, just passing it as the parameter.

C# string does not contain possible?

bool isFirst = compareString.Contains(firstString);
bool isSecond = compareString.Contains(secondString );

Convert Swift string to array

You can also create an extension:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

Rails: How to run `rails generate scaffold` when the model already exists?

Great answer by Lee Jarvis, this is just the command e.g; we already have an existing model called User:

rails g scaffold_controller User

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

I was trying to up the limit Wordpress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.

I did the following:

Created a (php.ini) file in WP ADMIN with the following integers:

upload_max_filesize = 2000MB
post_max_size = 2100MV
memory_limit = 2300MB

I immediately received this error when trying to log into my Wordpress dashboard to check if it worked:

“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)"

The above information in this chain helped me tremendously. (Stack usually does BTW)

I modified the PHP.ini file to the following:

upload_max_filesize = 2000M
post_max_size = 2100M
memory_limit = 536870912M

The major difference was only use M, not MB, and set that memory limit high.

As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.

I went in and checked media uploads, ands bang:

Image showing twordpress media folder “Add New” box, with limits stated as “MAXIMUM UPLOAD FILE SIZE: 2 GB”

I haven't restarted Apache yet… but all looks good.

Thanks everyone.

How to pass command line arguments to a rake task

To run rake tasks with traditional arguments style:

rake task arg1 arg2

And then use:

task :task do |_, args|
  puts "This is argument 1: #{args.first}"
end

Add following patch of rake gem:

Rake::Application.class_eval do

  alias origin_top_level top_level

  def top_level
    @top_level_tasks = [top_level_tasks.join(' ')]
    origin_top_level
  end

  def parse_task_string(string) # :nodoc:
    parts = string.split ' '
    return parts.shift, parts
  end

end

Rake::Task.class_eval do

  def invoke(*args)
    invoke_with_call_chain(args, Rake::InvocationChain::EMPTY)
  end

end

How to run the sftp command with a password from Bash script?

EXPECT is a great program to use.

On Ubuntu install it with:

sudo apt-get install expect

On a CentOS Machine install it with:

yum install expect

Lets say you want to make a connection to a sftp server and then upload a local file from your local machine to the remote sftp server

#!/usr/bin/expect

spawn sftp [email protected]
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact

This opens a sftp connection with your password to the server.

Then it goes to the directory where you want to upload your file, in this case "logdirectory"

This uploads a log file from the local directory found at /var/log/ with the files name being file.log to the "logdirectory" on the remote server

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

Angular 2 change event on every keypress

Use ngModelChange by breaking up the [(x)] syntax into its two pieces, i.e., property databinding and event binding:

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />
{{mymodel}}
valuechange(newValue) {
  mymodel = newValue;
  console.log(newValue)
}

It works for the backspace key too.

How can I uninstall npm modules in Node.js?

You can delete a Node.js module manually. For Windows,

  1. Go to the node_modules directory of your repository.

  2. Delete the Node.js module you don't want.

  3. Don't forget to remove the reference to the module in your package.json file! Your project may still run with the reference, but you may get an error. You also don't want to leave unused references in your package.json file that can cause confusion later.

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Follow the following steps if you are using proxy server:

  1. Open Eclipse
  2. Window >> Android SDK Manager >> Option
  3. Input your proxy server and port.

Hope this helps.

break out of if and foreach

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ):
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

Python IndentationError: unexpected indent

You can't mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don't mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn't match the following identations!

Installing Python 2.7 on Windows 8

System variables usually require a restart to become effective. Does it still not work after a restart?

Log exception with traceback

You can get the traceback using a logger, at any level (DEBUG, INFO, ...). Note that using logging.exception, the level is ERROR.

# test_app.py
import sys
import logging

logging.basicConfig(level="DEBUG")

def do_something():
    raise ValueError(":(")

try:
    do_something()
except Exception:
    logging.debug("Something went wrong", exc_info=sys.exc_info())
DEBUG:root:Something went wrong
Traceback (most recent call last):
  File "test_app.py", line 10, in <module>
    do_something()
  File "test_app.py", line 7, in do_something
    raise ValueError(":(")
ValueError: :(

EDIT:

This works too (using python 3.6)

logging.debug("Something went wrong", exc_info=True)

What is ":-!!" in C code?

Well, I am quite surprised that the alternatives to this syntax have not been mentioned. Another common (but older) mechanism is to call a function that isn't defined and rely on the optimizer to compile-out the function call if your assertion is correct.

#define MY_COMPILETIME_ASSERT(test)              \
    do {                                         \
        extern void you_did_something_bad(void); \
        if (!(test))                             \
            you_did_something_bad(void);         \
    } while (0)

While this mechanism works (as long as optimizations are enabled) it has the downside of not reporting an error until you link, at which time it fails to find the definition for the function you_did_something_bad(). That's why kernel developers starting using tricks like the negative sized bit-field widths and the negative-sized arrays (the later of which stopped breaking builds in GCC 4.4).

In sympathy for the need for compile-time assertions, GCC 4.3 introduced the error function attribute that allows you to extend upon this older concept, but generate a compile-time error with a message of your choosing -- no more cryptic "negative sized array" error messages!

#define MAKE_SURE_THIS_IS_FIVE(number)                          \
    do {                                                        \
        extern void this_isnt_five(void) __attribute__((error(  \
                "I asked for five and you gave me " #number))); \
        if ((number) != 5)                                      \
            this_isnt_five();                                   \
    } while (0)

In fact, as of Linux 3.9, we now have a macro called compiletime_assert which uses this feature and most of the macros in bug.h have been updated accordingly. Still, this macro can't be used as an initializer. However, using by statement expressions (another GCC C-extension), you can!

#define ANY_NUMBER_BUT_FIVE(number)                           \
    ({                                                        \
        typeof(number) n = (number);                          \
        extern void this_number_is_five(void) __attribute__(( \
                error("I told you not to give me a five!"))); \
        if (n == 5)                                           \
            this_number_is_five();                            \
        n;                                                    \
    })

This macro will evaluate its parameter exactly once (in case it has side-effects) and create a compile-time error that says "I told you not to give me a five!" if the expression evaluates to five or is not a compile-time constant.

So why aren't we using this instead of negative-sized bit-fields? Alas, there are currently many restrictions of the use of statement expressions, including their use as constant initializers (for enum constants, bit-field width, etc.) even if the statement expression is completely constant its self (i.e., can be fully evaluated at compile-time and otherwise passes the __builtin_constant_p() test). Further, they cannot be used outside of a function body.

Hopefully, GCC will amend these shortcomings soon and allow constant statement expressions to be used as constant initializers. The challenge here is the language specification defining what is a legal constant expression. C++11 added the constexpr keyword for just this type or thing, but no counterpart exists in C11. While C11 did get static assertions, which will solve part of this problem, it wont solve all of these shortcomings. So I hope that gcc can make a constexpr functionality available as an extension via -std=gnuc99 & -std=gnuc11 or some such and allow its use on statement expressions et. al.

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

How do I serialize an object and save it to a file in Android?

Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm. You should change it to your own class name. Android interface Serializable is not sufficient to save your objects to the file, it only creates streams.

// Constant with a file name
public static String fileName = "createResumeForm.ser";

// Serializes an object and saves it to a file
public void saveToFile(Context context) {
    try {
        FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(this);
        objectOutputStream.close();
        fileOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
    CreateResumeForm createResumeForm = null;
    try {
        FileInputStream fileInputStream = context.openFileInput(fileName);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        createResumeForm = (CreateResumeForm) objectInputStream.readObject();
        objectInputStream.close();
        fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return createResumeForm;
}

Use it like this in your Activity:

form = CreateResumeForm.readFromFile(this);

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

New .NET 5 Solution:

In .NET 5, a new class has been introduced called JsonContent, which derives from HttpContent. See in Microsoft docs

This class has a static method called Create(), which takes an object as a parameter.

Usage:

var myObject = new
{
    foo = "Hello",
    bar = "World",
};

JsonContent content = JsonContent.Create(myObject);

HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);

$.widget is not a function

Maybe placing the jquery.ui.widget.js as second after jquery.ui.core.js.

How do I find an element position in std::vector?

Get rid of the notion of vector entirely

template< typename IT, typename VT>
int index_of(IT begin, IT end, const VT& val)
{
    int index = 0;
    for (; begin != end; ++begin)
    {
        if (*begin == val) return index;
    }
    return -1;
}

This will allow you more flexibility and let you use constructs like

int squid[] = {5,2,7,4,1,6,3,0};
int sponge[] = {4,2,4,2,4,6,2,6};
int squidlen = sizeof(squid)/sizeof(squid[0]);
int position = index_of(&squid[0], &squid[squidlen], 3);
if (position >= 0) { std::cout << sponge[position] << std::endl; }

You could also search any other container sequentially as well.

How to clear form after submit in Angular 2?

To reset your form after submitting, you can just simply invoke this.form.reset(). By calling reset() it will:

  1. Mark the control and child controls as pristine.
  2. Mark the control and child controls as untouched.
  3. Set the value of control and child controls to custom value or null.
  4. Update value/validity/errors of affected parties.

Please find this pull request for a detailed answer. FYI, this PR has already been merged to 2.0.0.

Hopefully this can be helpful and let me know if you have any other questions in regards to Angular2 Forms.

click command in selenium webdriver does not work

I was working with EasyRepro, and when I debugged my code it was clicking on the element which is visible and enabled, and not navigating as expected. But finally I understood the root cause for the issue.

My Chrome was zoomed out 90%

Once i reset the zoom level, it clicked on the correct element and successfully navigated to next page.

Error: No default engine was specified and no extension was provided

if you've got this error by using the express generator, I've solved it by using

express --view=ejs myapp

instead of

express --view=pug myapp

How to Test Facebook Connect Locally

Create 2 apps and

In /initializers/env_variables.rb

if Rails.env == 'development'
    ENV['FB_APP_ID'] = "HERE"
    ENV["FB_SECRET"] = "HERE"
else
    ENV['FB_APP_ID'] = "HERE"
    ENV["FB_SECRET"] = "HERE"
end

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

select2 - hiding the search box

See this thread https://github.com/ivaynberg/select2/issues/489, you can hide the search box by setting minimumResultsForSearch to a negative value.

$('select').select2({
    minimumResultsForSearch: -1
});

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

try

_x000D_
_x000D_
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
_x000D_
<div id="date">23/05/2013</div>
_x000D_
_x000D_
_x000D_

Python: print a generator expression?

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

Defining lists as global variables in Python

When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

x = 0
def f():
    x = 1
f()
print x #=>0

and expect 1. Instead, you need do declare that you intend to use the global x:

x = 0
def f():
    global x
    x = 1
f()
print x #=>1

But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

Find which version of package is installed with pip

The python function returning just the package version in a machine-readable format:

from importlib.metadata import version 
version('numpy')

Prior to python 3.8:

pip install importlib-metadata 
from importlib_metadata import version
version('numpy')

The bash equivalent (here also invoked from python) would be much more complex (but more robust - see caution below):

import subprocess
def get_installed_ver(pkg_name):
    bash_str="pip freeze | grep -w %s= | awk -F '==' {'print $2'} | tr -d '\n'" %(pkg_name)
    return(subprocess.check_output(bash_str, shell=True).decode())

Sample usage:

# pkg_name="xgboost"
# pkg_name="Flask"
# pkg_name="Flask-Caching"
pkg_name="scikit-learn"

print(get_installed_ver(pkg_name))
>>> 0.22

Note that in both cases pkg_name parameter should contain package name in the format as returned by pip freeze and not as used during import, e.g. scikit-learn not sklearn or Flask-Caching, not flask_caching.

Note that while invoking pip freeze in bash version may seem inefficient, only this method proves to be sufficiently robust to package naming peculiarities and inconsistencies (e.g. underscores vs dashes, small vs large caps, and abbreviations such as sklearn vs scikit-learn).

Caution: in complex environments both variants can return surprise version numbers, inconsistent with what you can actually get during import.

One such problem arises when there are other versions of the package hidden in a user site-packages subfolder. As an illustration of the perils of using version() here's a situation I encountered:

$ pip freeze | grep lightgbm
lightgbm==2.3.1

and

$ python -c "import lightgbm; print(lightgbm.__version__)"
2.3.1

vs.

$ python -c "from importlib_metadata import version; print(version(\"lightgbm\"))"
2.2.3

until you delete the subfolder with the old version (here 2.2.3) from the user folder (only one would normally be preserved by `pip` - the one installed as last with the `--user` switch):

$ ls /home/jovyan/.local/lib/python3.7/site-packages/lightgbm*
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.2.3.dist-info
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.3.1.dist-info

Another problem is having some conda-installed packages in the same environment. If they share dependencies with your pip-installed packages, and versions of these dependencies differ, you may get downgrades of your pip-installed dependencies.

To illustrate, the latest version of numpy available in PyPI on 04-01-2020 was 1.18.0, while at the same time Anaconda's conda-forge channel had only 1.17.3 version on numpy as their latest. So when you installed a basemap package with conda (as second), your previously pip-installed numpy would get downgraded by conda to 1.17.3, and version 1.18.0 would become unavailable to the import function. In this case version() would be right, and pip freeze/conda list wrong:

$ python -c "from importlib_metadata import version; print(version(\"numpy\"))"
1.17.3

$ python -c "import numpy; print(numpy.__version__)"
1.17.3

$ pip freeze | grep numpy
numpy==1.18.0

$ conda list | grep numpy
numpy                     1.18.0                   pypi_0    pypi

Do I use <img>, <object>, or <embed> for SVG files?

You can insert a SVG indirectly using <img> HTML tag and this is possible on StackOverflow following what is described below:

I have following SVG file on my PC

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="350" height="350" viewBox="0 0 350 350">

  <title>SVG 3 Circles Intersection </title>

    <circle cx="110" cy="110" r="100"
            stroke="red"
            stroke-width="3"
            fill="none"
            />
    <text x="110" y="110" 
          text-anchor="middle"
          stroke="red"
          stroke-width="1px"
          > Label
    </text>
    <circle cx="240" cy="110" r="100" 
            stroke="blue" 
            stroke-width="3"
            fill="none"
            />
    <text x="240" y="110" 
          text-anchor="middle" 
          stroke="blue" 
          stroke-width="1px"
          > Ticket
    </text>
    <circle cx="170" cy="240" r="100" 
            stroke="green" 
            stroke-width="3" 
            fill="none"
            />
    <text x="170" y="240" 
          text-anchor="middle" 
          stroke="green" 
          stroke-width="1px"
          > Vecto
    </text>
</svg>

I have uploaded this image to https://svgur.com

After upload was terminated, I have obtained following URL:

https://svgshare.com/i/RJV.svg

I have then MANUALLY (without using IMAGE icon) added following html tag

<img src="https://svgshare.com/i/KJV.svg"/>

and the result is just below

For user with some doubt, it is possible to see what I have done in editing following answer on StackOverflow inserting SVG image

REMARK-1: the SVG file must contains <?xml?> element. At begin, I have simply created a SVG file that begins directly with <svg> tag and nothing worked !

REMARK-2: at begin, I have tried to insert an image using IMAGE icon of Edit Toolbar. I paste URL of my SVG file but StackOverflow don't accept this method. The <img> tag must be added manually.

I hope that this answer can help other users.

How to link a folder with an existing Heroku app

Use heroku's fork

  1. Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!

    heroku fork -a sourceapp targetapp
    
  2. Clone it local

    git clone [email protected]:youamazingapp.git
    
  3. Make a new repo on github and add it

    git remote add origin https://github.com/yourname/your_repo.git
    
  4. Push on github

    git push origin master
    

Flutter command not found

If you are using zsh, you need to follow the steps below in mac.

  • Download latest flutter from the official site.
  • Unzip it and move to the $HOME location of your mac.
  • Add to path via .zshrc file.
  • Run nano ~/.zshrc into iTerm2 terminal.
  • Export PATH=$HOME/flutter/bin:$PATH
  • Save and close the ~/.zshrc file.
  • Restart iTerm2.
  • Now you will have flutter available.

How do I sleep for a millisecond in Perl?

A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.

Delete all nodes and relationships in neo4j 1.8

As of 2.3.0 and up to 3.3.0

MATCH (n)
DETACH DELETE n

Docs

Pre 2.3.0

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

Docs

How do I center text horizontally and vertically in a TextView?

I don't think, You really need to do that just define your TextView in layout file like this

<RelativeLayout
    android:layout_width="width"
    android:layout_height="height">
    <TextView
        android:id="@+id/yourid"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your text" />
</RelativeLayout>

Functional, Declarative, and Imperative Programming

imperative and declarative describe two opposing styles of programming. imperative is the traditional "step by step recipe" approach while declarative is more "this is what i want, now you work out how to do it".

these two approaches occur throughout programming - even with the same language and the same program. generally the declarative approach is considered preferable, because it frees the programmer from having to specify so many details, while also having less chance for bugs (if you describe the result you want, and some well-tested automatic process can work backwards from that to define the steps then you might hope that things are more reliable than having to specify each step by hand).

on the other hand, an imperative approach gives you more low level control - it's the "micromanager approach" to programming. and that can allow the programmer to exploit knowledge about the problem to give a more efficient answer. so it's not unusual for some parts of a program to be written in a more declarative style, but for the speed-critical parts to be more imperative.

as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.

so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.

it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).

and if you do that - if you limit how variables can change - then almost by accident you end up forcing the programmer to write programs that are more declarative, because a large part of imperative programming is describing how variables change, and you can no longer do that! so it turns out that functional programming - particularly, programming in a functional language - tends to give more declarative code.

to summarise, then:

  • imperative and declarative are two opposing styles of programming (the same names are used for programming languages that encourage those styles)

  • functional programming is a style of programming where functions become very important and, as a consequence, changing values become less important. the limited ability to specify changes in values forces a more declarative style.

so "functional programming" is often described as "declarative".

How to query GROUP BY Month in a Year

You can use:

    select FK_Items,Sum(PoiQuantity) Quantity  from PurchaseOrderItems POI
    left join PurchaseOrder PO ON po.ID_PurchaseOrder=poi.FK_PurchaseOrder
    group by FK_Items,DATEPART(MONTH, TransDate)

opening a window form from another form programmatically

This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.

enter image description here

The code for the button click is below

private void button1_Click(object sender, EventArgs e)
{
    New_Form new_Form = new New_Form();
    new_Form.Show();
}

Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer

this.Load += new System.EventHandler(this.OnPageLoad);

This OnPageLoad function runs when that form is loaded

In NewForm.cs ,

public partial class New_Form : Form
{
    private Timer formClosingTimer;

    private void OnPageLoad(object sender, EventArgs e)
    {
        formClosingTimer = new Timer();  // Creating a new timer 
        formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
        formClosingTimer.Interval = 2000; // Time Interval in miliseconds
        formClosingTimer.Start(); // Starting a timer
    }
    private void CloseForm(object sender, EventArgs e)
    {
        formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
        this.Close(); // Closing the current form
    }
}

In this new form , a timer is used to invoke a method which closes that form.

Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.

enter image description here

For your knowledge,

form.close() will free the memory and we can never interact with that form again form.hide() will just hide the form, where the code part can still run

For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2

How to change the background colour's opacity in CSS

Use RGBA like this: background-color: rgba(255, 0, 0, .5)

PHP - Get key name of array value

If i understand correctly, can't you simply use:

foreach($arr as $key=>$value)
{
  echo $key;
}

See PHP manual

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

Prevent direct access to a php include file

You can use the following method below although, it does have a flaw, because it can be faked, except if you can add another line of code to make sure the request comes only from your server either by using Javascript. You can place this code in the Body section of your HTML code, so the error shows there.

<?
if(!isset($_SERVER['HTTP_REQUEST'])) { include ('error_file.php'); }
else { ?>

Place your other HTML code here

<? } ?>

End it like this, so the output of the error will always show within the body section, if that's how you want it to be.

Invalid syntax when using "print"?

You need parentheses:

print(2**100)

"You may need an appropriate loader to handle this file type" with Webpack and Babel

BABEL TEAM UPDATE:

We're super excited that you're trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5

If you are using Babel version 7 you will need to run npm install @babel/preset-env and have "presets": ["@babel/preset-env"] in your .babelrc configuration.

This will compile all latest features to es5 transpiled code:

Prerequisites:

  1. Webpack 4+
  2. Babel 7+

Step-1:: npm install --save-dev @babel/preset-env

Step-2: In order to compile JSX code to es5 babel provides @babel/preset-react package to convert reactjsx extension file to native browser understandable code.

Step-3: npm install --save-dev @babel/preset-react

Step-4: create .babelrc file inside root path path of your project where webpack.config.js exists.

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Step-5: webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        path: path.resolve(__dirname, 'output'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [{
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./public/index.html",
            filename: "./index.html"
         })
    ]
}

C#: Waiting for all threads to complete

Since the question got bumped I will go ahead and post my solution.

using (var finished = new CountdownEvent(1)) 
{ 
  for (DataObject data in dataList) 
  {   
    finished.AddCount();
    var localData = (DataObject)data.Clone(); 
    var thread = new Thread( 
        delegate() 
        {
          try
          {
            DoThreadStuff(localData); 
            threadFinish.Set();
          }
          finally
          {
            finished.Signal();
          }
        } 
    ); 
    thread.Start(); 
  }  
  finished.Signal(); 
  finished.Wait(YOUR_TIMEOUT); 
} 

Add column with constant value to pandas dataframe

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

Implementing IDisposable correctly

I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:

https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About

The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017

What is content-type and datatype in an AJAX request?

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/

contentType When sending data to the server, use this content type.

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

"text": A plain text string.

So you want contentType to be application/json and dataType to be text:

$.ajax({
    type : "POST",
    url : /v1/user,
    dataType : "text",
    contentType: "application/json",
    data : dataAttribute,
    success : function() {

    },
    error : function(error) {

    }
});

Insert and set value with max()+1 problems

You can't do it in a single query, but you could do it within a transaction. Do the initial MAX() select and lock the table, then do the insert. The transaction ensures that nothing will interrupt the two queries, and the lock ensures that nothing else can try doing the same thing elsewhere at the same time.

Show hide divs on click in HTML and CSS without jQuery

Using label and checkbox input

Keeps the selected item opened and togglable.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using label and named radio input

Similar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio" on both inputs.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using tabindex and :focus

Similar to radio inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.

_x000D_
_x000D_
.collapse > a{_x000D_
  background: #cdf;_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
  outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
  display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
  display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 1</a>_x000D_
  <div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 2</a>_x000D_
  <div>Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using :target

Similar to using radio input, you can additionally use Tab and keys to operate

_x000D_
_x000D_
.collapse a{_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
  display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_1">Collapse 1</a>_x000D_
  <div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_2">Collapse 2</a>_x000D_
  <div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using <detail> and <summary> tags (pure HTML)

You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.

_x000D_
_x000D_
<details>_x000D_
  <summary>Collapse 1</summary>_x000D_
  <p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
  <summary>Collapse 2</summary>_x000D_
  <p>Content 2...</p>_x000D_
</details>
_x000D_
_x000D_
_x000D_

How can I check if character in a string is a letter? (Python)

This works:

word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
    if not char.isalpha():
        notChar += 1
    else:
        isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

The answer to the question how to convert a .cer file into a .crt file (they are encoded differently!) is:

openssl pkcs7 -print_certs -in certificate.cer -out certificate.crt

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

A ClusterIP exposes the following:

  • spec.clusterIp:spec.ports[*].port

You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally.

A NodePort exposes the following:

  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP.

Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort.

A LoadBalancer exposes the following:

  • spec.loadBalancerIp:spec.ports[*].port
  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Delete dynamically-generated table row using jQuery

A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

http://jsfiddle.net/Z7fG7/2/

Use sed to replace all backslashes with forward slashes

$ echo "C:\Windows\Folder\File.txt" | sed -e 's/\\/\//g'
C:/Windows/Folder/File.txt

The sed command in this case is 's/OLD_TEXT/NEW_TEXT/g'.

The leading 's' just tells it to search for OLD_TEXT and replace it with NEW_TEXT.

The trailing 'g' just says to replace all occurrences on a given line, not just the first.

And of course you need to separate the 's', the 'g', the old, and the new from each other. This is where you must use forward slashes as separators.

For your case OLD_TEXT == '\' and NEW_TEXT == '/'. But you can't just go around typing slashes and expecting things to work as expected be taken literally while using them as separators at the same time. In general slashes are quite special and must be handled as such. They must be 'escaped' (i.e. preceded) by a backslash.

So for you, OLD_TEXT == '\\' and NEW_TEXT == '\/'. Putting these inside the 's/OLD_TEXT/NEW_TEXT/g' paradigm you get
's/\\/\//g'. That reads as
's / \\ / \/ / g' and after escapes is
's / \ / / / g' which will replace all backslashes with forward slashes.

MySQL: How to add one day to datetime field in query

You can use the DATE_ADD() function:

... WHERE DATE(DATE_ADD(eventdate, INTERVAL -1 DAY)) = CURRENT_DATE

It can also be used in the SELECT statement:

SELECT DATE_ADD('2010-05-11', INTERVAL 1 DAY) AS Tomorrow;
+------------+
| Tomorrow   |
+------------+
| 2010-05-12 |
+------------+
1 row in set (0.00 sec)

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

This is for 32 bit, we need to change the size if we consider 8 bits.

    void bitReverse(int num)
    {
        int num_reverse = 0;
        int size = (sizeof(int)*8) -1;
        int i=0,j=0;
        for(i=0,j=size;i<=size,j>=0;i++,j--)
        {
            if((num >> i)&1)
            {
                num_reverse = (num_reverse | (1<<j));
            }
        }
        printf("\n rev num = %d\n",num_reverse);
    }

Reading the input integer "num" in LSB->MSB order and storing in num_reverse in MSB->LSB order.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

How to restore PostgreSQL dump file into Postgres databases?

You might need to set permissions at the database level that allows your schema owner to restore the dump.

Javascript get object key name

Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.

function key(int) {
    var j = -1;
    for(var i in this) {
        j++;
        if(j==int) {
            return i;
        } else {
            continue;
        }
    }
}
Object.prototype.key = key;

This is numbered to work the same way that arrays do, to save headaches. In the case of your code:

buttons.key(0) // Should result in "button1"

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

What is the difference between linear regression and logistic regression?

Simply put, linear regression is a regression algorithm, which outpus a possible continous and infinite value; logistic regression is considered as a binary classifier algorithm, which outputs the 'probability' of the input belonging to a label (0 or 1).

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

To solve this, I opened httpd.conf and changed the following line:

Allow from 127.0.0.1

to:

Allow from 127.0.0.1 ::1

"SSL certificate verify failed" using pip to install packages

If you're using python3, you can try this too:

python3 -m pip install --upgrade Scrapy --trusted-host pypi.org --trusted-host files.pythonhosted.org

phpMyAdmin - The MySQL Extension is Missing

Your installation is missing some php modules, there should be a list of required modules in the phpmyadmin readme. If you recently enabled the modules, try restarting the apache service / daemon.

Edit: As it seems, there is no single "enable these modules" in the docs, so enable either mysql or mysqli in your php.ini (you might need to install it first).

The two messages are not important if you do not intend to upload or download compressed file within phpMyAdmin. If you do, enable the zlib and / or bz2 modules.

How to add a new line of text to an existing file in Java?

You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file.

Change your code to this:

output = new BufferedWriter(new FileWriter(my_file_name, true));

From FileWriter javadoc:

Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

How to create module-wide variables in Python?

Explicit access to module level variables by accessing them explicity on the module


In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

# db.py
import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = "Locally scoped db_name variable. Doesn't do anything here."
    else:
        msg = "Database is already initialized to {0}."
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
import db

if (db.db_name == 'mongo'):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value 
# that "db.db_name" has at import time of "client_c".

if (db_name == 'mongo'):  # checking is fine if "db.db_name" doesn't change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

How can I parse a CSV string with JavaScript, which contains comma in data?

Adding one more to the list, because I find all of the above not quite "KISS" enough.

This one uses regex to find either commas or newlines while skipping over quoted items. Hopefully this is something noobies can read through on their own. The splitFinder regexp has three things it does (split by a |):

  1. , - finds commas
  2. \r?\n - finds new lines, (potentially with carriage return if the exporter was nice)
  3. "(\\"|[^"])*?" - skips anynthing surrounded in quotes, because commas and newlines don't matter in there. If there is an escaped quote \\" in the quoted item, it will get captured before an end quote can be found.

_x000D_
_x000D_
const splitFinder = /,|\r?\n|"(\\"|[^"])*?"/g;_x000D_
_x000D_
function csvTo2dArray(parseMe) {_x000D_
  let currentRow = [];_x000D_
  const rowsOut = [currentRow];_x000D_
  let lastIndex = splitFinder.lastIndex = 0;_x000D_
  _x000D_
  // add text from lastIndex to before a found newline or comma_x000D_
  const pushCell = (endIndex) => {_x000D_
    endIndex = endIndex || parseMe.length;_x000D_
    const addMe = parseMe.substring(lastIndex, endIndex);_x000D_
    // remove quotes around the item_x000D_
    currentRow.push(addMe.replace(/^"|"$/g, ""));_x000D_
    lastIndex = splitFinder.lastIndex;_x000D_
  }_x000D_
_x000D_
_x000D_
  let regexResp;_x000D_
  // for each regexp match (either comma, newline, or quoted item)_x000D_
  while (regexResp = splitFinder.exec(parseMe)) {_x000D_
    const split = regexResp[0];_x000D_
_x000D_
    // if it's not a quote capture, add an item to the current row_x000D_
    // (quote captures will be pushed by the newline or comma following)_x000D_
    if (split.startsWith(`"`) === false) {_x000D_
      const splitStartIndex = splitFinder.lastIndex - split.length;_x000D_
      pushCell(splitStartIndex);_x000D_
_x000D_
      // then start a new row if newline_x000D_
      const isNewLine = /^\r?\n$/.test(split);_x000D_
      if (isNewLine) { rowsOut.push(currentRow = []); }_x000D_
    }_x000D_
  }_x000D_
  // make sure to add the trailing text (no commas or newlines after)_x000D_
  pushCell();_x000D_
  return rowsOut;_x000D_
}_x000D_
_x000D_
const rawCsv = `a,b,c\n"test\r\n","comma, test","\r\n",",",\nsecond,row,ends,with,empty\n"quote\"test"`_x000D_
const rows = csvTo2dArray(rawCsv);_x000D_
console.log(rows);
_x000D_
_x000D_
_x000D_

How do I implement basic "Long Polling"?

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)

msgsrv.php

<?php
if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");
    die();
}

/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

How can I extract embedded fonts from a PDF as valid font files?

PDF2SVG version 6.0 from PDFTron does a reasonable job. It produces OpenType (.otf) fonts by default. Use --preserve_fontnames to preserve "the font/font-family naming scheme as obtained from the source file."

PDF2SVG is a commercial product, but you can download a free demo executable (which includes watermarks on the SVG output but doesn't otherwise restrict usage). There may be other PDFTron products that also extract fonts, but I only recently discovered PDF2SVG myself.

CSS vertical alignment of inline/inline-block elements

Simply floating both elements left achieves the same result.

div {
background:yellow;
vertical-align:middle;
margin:10px;
}

a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}

span {
background:red;
display:inline-block;
float:left;
}

How do I tell if a regular file does not exist in Bash?

To reverse a test, use "!". That is equivalent to the "not" logical operator in other languages. Try this:

if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

Or written in a slightly different way:

if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or you could use:

if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or, presing all together:

if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

Which may be written (using then "and" operator: &&) as:

[ ! -f /tmp/foo.txt ] && echo "File not found!"

Which looks shorter like this:

[ -f /tmp/foo.txt ] || echo "File not found!"

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

"relocation R_X86_64_32S against " linking Error

Assuming you are generating a shared library, most probably what happens is that the variant of liblog4cplus.a you are using wasn't compiled with -fPIC. In linux, you can confirm this by extracting the object files from the static library and checking their relocations:

ar -x liblog4cplus.a  
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'

If the output is empty, then the static library is not position-independent and cannot be used to generate a shared object.

Since the static library contains object code which was already compiled, providing the -fPIC flag won't help.

You need to get ahold of a version of liblog4cplus.a compiled with -fPIC and use that one instead.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

_x000D_
_x000D_
/* HIDE RADIO */
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
_x000D_
<label>
  <input type="radio" name="test" value="small" checked>
  <img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>

<label>
  <input type="radio" name="test" value="big">
  <img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
_x000D_
_x000D_

Don't forget to add a class to your labels and in CSS use that class instead.


Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

_x000D_
_x000D_
body{color:#444;font:100%/1.4 sans-serif;}


/* CUSTOM RADIO & CHECKBOXES
   http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
  width: 25px;
  border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
}
_x000D_
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
</label>
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2
</label>

<br>

<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
</label>
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2
</label>
_x000D_
_x000D_
_x000D_

How to remove files from git staging area?

To remove all files from staging area use -
git reset
To remove specific file use -
git reset "File path"

jQuery removeClass wildcard

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

Simple dynamic breadcrumb

Also made a little script using RDFa (you can also use microdata or other formats) Check it out on google This script also keeps in mind your site structure.

function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $home = 'Home') {
//Use RDFa breadcrumb, can also be used for microformats etc.
$bc     =   '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text;
//Get the website:
$site   =   'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs =   array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the home breadcrumb
$bc    .=   '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; 
//Count all not empty breadcrumbs
$nm     =   count($crumbs);
$i      =   1;
//Loop the crumbs
foreach($crumbs as $crumb){
    //Make the link look nice
    $link    =  ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) );
    //Loose the last seperator
    $sep     =  $i==$nm?'':$sep;
    //Add crumbs to the root
    $site   .=  '/'.$crumb;
    //Make the next crumb
    $bc     .=  '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>';
    $i++;
}
$bc .=  '</div>';
//Return the result
return $bc;}

Check for special characters (/*-+_@&$#%) in a string?

A great way using C# and Linq here:

public static bool HasSpecialCharacter(this string s)
{
    foreach (var c in s)
    {
        if(!char.IsLetterOrDigit(c))
        {
            return true;
        }
    }
    return false;
 }

And access it like this:

myString.HasSpecialCharacter();

javascript: Disable Text Select

If you got a html page like this:

    <body
    onbeforecopy = "return false"
    ondragstart = "return false" 
    onselectstart = "return false" 
    oncontextmenu = "return false" 
    onselect = "document.selection.empty()" 
    oncopy = "document.selection.empty()">

There a simple way to disable all events:

document.write(document.body.innerHTML)

You got the html content and lost other things.

C++ - how to find the length of an integer

Closed formula for the longest int (I used int here, but works for any signed integral type):

1 + (int) ceil((8*sizeof(int)-1) * log10(2))

Explanation:

                  sizeof(int)                 // number bytes in int
                8*sizeof(int)                 // number of binary digits (bits)
                8*sizeof(int)-1               // discount one bit for the negatives
               (8*sizeof(int)-1) * log10(2)   // convert to decimal, because:
                                              // 1 bit == log10(2) decimal digits
    (int) ceil((8*sizeof(int)-1) * log10(2))  // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2))  // make room for the minus sign

For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".

If you want the number of decimal digits of some int value, you can use the following function:

unsigned base10_size(int value)
{
    if(value == 0) {
        return 1u;
    }

    unsigned ret;
    double dval;
    if(value > 0) {
        ret = 0;
        dval = value;
    } else {
        // Make room for the minus sign, and proceed as if positive.
        ret = 1;
        dval = -double(value);
    }

    ret += ceil(log10(dval+1.0));

    return ret;
}

I tested this function for the whole range of int in g++ 9.3.0 for x86-64.

CSS fill remaining width

I would probably do something along the lines of

<div id='search-logo-bar'><input type='text'/></div>

with css

div#search-logo-bar {
    padding-left:10%;
    background:#333 url(logo.png) no-repeat left center;
    background-size:10%;
}
input[type='text'] {
    display:block;
    width:100%;
}

DEMO

http://jsfiddle.net/5MHnt/

How do I convert an array object to a string in PowerShell?

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

Trim Cells using VBA in Excel

I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.

If you really want to use VBA I believe you could select first character

strSpace = left(range("A1").Value,1)

and use replace function in VBA the same way

Range("A1").Value = Replace(Range("A1").Value, strSpace, "")

or

for each cell in selection.cells
 cell.value = replace(cell.value, strSpace, "")
next

How to discard local commits in Git?

I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard or a branch -D fail to work, try

git pull origin
git reset --hard 

"implements Runnable" vs "extends Thread" in Java

The simplest explanation would be by implementing Runnable we can assign the same object to multiple threads and each Thread shares the same object states and behavior.

For example, suppose there are two threads, thread1 puts an integer in an array and thread2 takes integers from the array when the array is filled up. Notice that in order for thread2 to work it needs to know the state of array, whether thread1 has filled it up or not.

Implementing Runnable lets you to have this flexibility to share the object whereas extends Thread makes you to create new objects for each threads therefore any update that is done by thread1 is lost to thread2.

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

Why can't I use switch statement on a String?

JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

Now you can:

  • directly assign variable from switch expression,
  • use new form of switch label (case L ->):

    The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

  • use multiple constants per case, separated by commas,
  • and also there are no more value breaks:

    To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

So the demo from the answers (1, 2) might look like this:

  public static void main(String[] args) {
    switch (args[0]) {
      case "Monday", "Tuesday", "Wednesday" ->  System.out.println("boring");
      case "Thursday" -> System.out.println("getting better");
      case "Friday", "Saturday", "Sunday" -> System.out.println("much better");
    }

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

What does 'var that = this;' mean in JavaScript?

From Crockford

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

JS Fiddle

function usesThis(name) {
    this.myName = name;

    function returnMe() {
        return this;        //scope is lost because of the inner function
    }

    return {
        returnMe : returnMe
    }
}

function usesThat(name) {
    var that = this;
    this.myName = name;

    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }

    return {
        returnMe : returnMe
    }
}

var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);

This alerts...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

What's the difference between compiled and interpreted language?

What’s the difference between compiled and interpreted language?

The difference is not in the language; it is in the implementation.

Having got that out of my system, here's an answer:

  • In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.

  • In an interpreted implementation, the original program is translated into something else. Another program, called "the interpreter", then examines "something else" and performs whatever actions are called for. Depending on the language and its implementation, there are a variety of forms of "something else". From more popular to less popular, "something else" might be

    • Binary instructions for a virtual machine, often called bytecode, as is done in Lua, Python, Ruby, Smalltalk, and many other systems (the approach was popularized in the 1970s by the UCSD P-system and UCSD Pascal)

    • A tree-like representation of the original program, such as an abstract-syntax tree, as is done for many prototype or educational interpreters

    • A tokenized representation of the source program, similar to Tcl

    • The characters of the source program, as was done in MINT and TRAC

One thing that complicates the issue is that it is possible to translate (compile) bytecode into native machine instructions. Thus, a successful intepreted implementation might eventually acquire a compiler. If the compiler runs dynamically, behind the scenes, it is often called a just-in-time compiler or JIT compiler. JITs have been developed for Java, JavaScript, Lua, and I daresay many other languages. At that point you can have a hybrid implementation in which some code is interpreted and some code is compiled.

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"

Solved this by putting 'port' => '8889', in 'Datasources' => [

Is this a good way to clone an object in ES6?

Following on from the answer by @marcel I found some functions were still missing on the cloned object. e.g.

function MyObject() {
  var methodAValue = null,
      methodBValue = null

  Object.defineProperty(this, "methodA", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    },
    enumerable: true
  });

  Object.defineProperty(this, "methodB", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    }
  });
}

where on MyObject I could clone methodA but methodB was excluded. This occurred because it is missing

enumerable: true

which meant it did not show up in

for(let key in item)

Instead I switched over to

Object.getOwnPropertyNames(item).forEach((key) => {
    ....
  });

which will include non-enumerable keys.

I also found that the prototype (proto) was not cloned. For that I ended up using

if (obj.__proto__) {
  copy.__proto__ = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}

PS: Frustrating that I could not find a built in function to do this.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How do I use a C# Class Library in a project?

Here is a good article on creating and adding a class library. Even shows how to create Methods through the method wizard and how to use it in the application

How do I quickly rename a MySQL database (change schema name)?

This works for all databases and works by renaming each table with maatkit mysql toolkit

Use mk-find to print and rename each table. The man page has many more options and examples

mk-find --dblike OLD_DATABASE --print --exec "RENAME TABLE %D.%N TO NEW_DATABASE.%N"

If you have maatkit installed (which is very easy), then this is the simplest way to do it.

Crystal Reports 13 And Asp.Net 3.5

I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

How do you convert CString and std::string std::wstring to each other?

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The solution with copying 32-bit libs over to 64-bit did not work for me. What worked was unchecking Target Platform Prefer 32-bit check mark in project properties.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Declare a const array

You can't create a 'const' array because arrays are objects and can only be created at runtime and const entities are resolved at compile time.

What you can do instead is to declare your array as "readonly". This has the same effect as const except the value can be set at runtime. It can only be set once and it is thereafter a readonly (i.e. const) value.

How to check if all inputs are not empty with jQuery

Just use:

$("input:empty").length == 0;

If it's zero, none are empty.

To be a bit smarter though and also filter out items with just spaces in, you could do:

$("input").filter(function () {
    return $.trim($(this).val()).length == 0
}).length == 0;

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

How to get Android application id?

For getting AppId (or package name, how some says), just call this:

But be sure that you importing BuildConfig with your app id packages path

BuildConfig.APPLICATION_ID 

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

Accessing MVC's model property from Javascript

If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:

$(document).ready(function () {

    @{  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var json = serializer.Serialize(Model);
    }

    var model = @Html.Raw(json);
    if(model != null && @Html.Raw(json) != "undefined")
    {
        var id= model.Id;
        var mainFloorPlanId = model.MainFloorPlanId ;
        var imageDirectory = model.ImageDirectory ;
        var iconsDirectory = model.IconsDirectory ;
    }
});

Hope this helps...

Python loop that also accesses previous and next values

Very C/C++ style solution:

    foo = 5
    objectsList = [3, 6, 5, 9, 10]
    prev = nex = 0
    
    currentIndex = 0
    indexHigher = len(objectsList)-1 #control the higher limit of list
    
    found = False
    prevFound = False
    nexFound = False
    
    #main logic:
    for currentValue in objectsList: #getting each value of list
        if currentValue == foo:
            found = True
            if currentIndex > 0: #check if target value is in the first position   
                prevFound = True
                prev = objectsList[currentIndex-1]
            if currentIndex < indexHigher: #check if target value is in the last position
                nexFound = True
                nex = objectsList[currentIndex+1]
            break #I am considering that target value only exist 1 time in the list
        currentIndex+=1
    
    if found:
        print("Value %s found" % foo)
        if prevFound:
            print("Previous Value: ", prev)
        else:
            print("Previous Value: Target value is in the first position of list.")
        if nexFound:
            print("Next Value: ", nex)
        else:
            print("Next Value: Target value is in the last position of list.")
    else:
        print("Target value does not exist in the list.")

How do you discover model attributes in Rails?

For Schema related stuff

Model.column_names         
Model.columns_hash         
Model.columns 

For instance variables/attributes in an AR object

object.attribute_names                    
object.attribute_present?          
object.attributes

For instance methods without inheritance from super class

Model.instance_methods(false)

How to unit test abstract classes: extend with stubs?

one way is to write an abstract test case that corresponds to your abstract class, then write concrete test cases that subclass your abstract test case. do this for each concrete subclass of your original abstract class (i.e. your test case hierarchy mirrors your class hierarchy). see Test an interface in the junit recipies book: http://safari.informit.com/9781932394238/ch02lev1sec6. https://www.manning.com/books/junit-recipes or https://www.amazon.com/JUnit-Recipes-Practical-Methods-Programmer/dp/1932394230 if you don't have a safari account.

also see Testcase Superclass in xUnit patterns: http://xunitpatterns.com/Testcase%20Superclass.html

Add space between two particular <td>s

my choice was to add a td between the two td tags and set the width to 25px. It can be more or less to your liking. This may be cheesy but it is simple and it works.

Mean of a column in a data frame, given the column's name

I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get function as well:

 df1 <- data.frame(a=1:10, b=11:20)
 mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
 mean_col("df1", "b")
 # [1] 15.5

There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

Here is Ubuntu information of my laptop.

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:    18.04
Codename:   bionic

I use locate to find the .so files for boost_filesystem and boost_system

locate libboost_filesystem
locate libboost_system

Then link .so files to /usr/lib and rename to .so

sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1 /usr/lib/libboost_filesystem.so
sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.65.1 /usr/lib/libboost_system.so

Done! R package velocyto.R was successfully installed!

Is Safari on iOS 6 caching $.ajax results?

Things that DID NOT WORK for me with an iPad 4/iOS 6:

My request containing: Cache-Control:no-cache

//asp.net's:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)

Adding cache: false to my jQuery ajax call

 $.ajax(
        {
            url: postUrl,
            type: "POST",
            cache: false,
            ...

Only this did the trick:

var currentTime = new Date();
var n = currentTime.getTime();
postUrl = "http://www.example.com/test.php?nocache="+n;
$.post(postUrl, callbackFunction);

Can I append an array to 'formdata' in javascript?

We can simply do like this.

_x000D_
_x000D_
formData = new FormData;
words = ["apple", "ball", "cat"]
words.forEach((item) => formData.append("words[]", item))

// verify the data
console.log(formData.getAll("words[]"))
//["apple", "ball", "cat"]
_x000D_
_x000D_
_x000D_

On server-side you will get words = ["apple", "ball", "cat"]

How can I manually set an Angular form field as invalid?

In my Reactive form, I needed to mark a field as invalid if another field was checked. In ng version 7 I did the following:

    const checkboxField = this.form.get('<name of field>');
    const dropDownField = this.form.get('<name of field>');

    this.checkboxField$ = checkboxField.valueChanges
        .subscribe((checked: boolean) => {
            if(checked) {
                dropDownField.setValidators(Validators.required);
                dropDownField.setErrors({ required: true });
                dropDownField.markAsDirty();
            } else {
                dropDownField.clearValidators();
                dropDownField.markAsPristine();
            }
        });

So above, when I check the box it sets the dropdown as required and marks it as dirty. If you don't mark as such it then it won't be invalid (in error) until you try to submit the form or interact with it.

If the checkbox is set to false (unchecked) then we clear the required validator on the dropdown and reset it to a pristine state.

Also - remember to unsubscribe from monitoring field changes!

if, elif, else statement issues in Bash

You have some syntax issues with your script. Here is a fixed version:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

How to get the Power of some Integer in Swift language?

If you like, you could declare an infix operator to do it.

// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8

I used two carets so you can still use the XOR operator.

Update for Swift 3

In Swift 3 the "magic number" precedence is replaced by precedencegroups:

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))
}

// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

How do I convert a String to an int in Java?

It can be done in seven ways:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

String number = "999";
  1. Ints.tryParse:

    int result = Ints.tryParse(number);

  2. NumberUtils.createInteger:

    Integer result = NumberUtils.createInteger(number);

  3. NumberUtils.toInt:

    int result = NumberUtils.toInt(number);

  4. Integer.valueOf:

    Integer result = Integer.valueOf(number);

  5. Integer.parseInt:

    int result = Integer.parseInt(number);

  6. Integer.decode:

    int result = Integer.decode(number);

  7. Integer.parseUnsignedInt:

    int result = Integer.parseUnsignedInt(number);

How do I make a dictionary with multiple keys to one value?

Your example creates multiple key: value pairs if using fromkeys. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

Probably because you're using unsafe code.

Are you doing something with pointers or unmanaged assemblies somewhere?

Laravel 5 – Remove Public from URL

Just create .htaccess file at root and add these lines to it

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

That's it!

The above code works on the root public_html folder. Having said that your core laravel file should be inside the public_html folder, if your directory looks like public_html/laravelapp/public and if you put the above code inside laravelapp it won't work. Therefore you must copy all your core files into public_html and put the .htaccess file there .

If you want to keep the code in a subdirectory then you can create a subdomain then this code will work for that also.

How to split a string in shell and get the last field

A solution using the read builtin:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

Or, to make it more generic:

echo "${fields[-1]}" # prints the last item

Creating an empty Pandas DataFrame, then filling it?

Assume a dataframe with 19 rows

index=range(0,19)
index

columns=['A']
test = pd.DataFrame(index=index, columns=columns)

Keeping Column A as a constant

test['A']=10

Keeping column b as a variable given by a loop

for x in range(0,19):
    test.loc[[x], 'b'] = pd.Series([x], index = [x])

You can replace the first x in pd.Series([x], index = [x]) with any value

Connect to SQL Server through PDO using SQL Server Driver

Figured this out. Pretty simple:

 new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]",  "[username]", "[password]");

Java best way for string find and replace?

Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.

You can view the StringUtils API at the previously linked website.

"Don't reinvent the wheel"

Twitter Bootstrap 3: how to use media queries?

To improve the main response:

You can use the media attribute of the <link> tag (it support media queries) in order to download just the code the user needs.

<link href="style.css" rel="stylesheet">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">

With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.

Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.

Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css

Some tools that will help you to automate the separation of your css code in different files according to your media-querys

Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin

PostCSS https://www.npmjs.com/package/postcss-extract-media-query

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

In Netbeans, we can use Tools->Options-> General Tab - > Under proxy settings, select Use system proxy settings.

This way, it uses the proxy settings provided in Settings -> Control Panel -> Internet Options -> Connections -> Lan Settings -> use automatic configuration scripts.

If you are using maven, make sure the proxy settings are not provided there, so that it uses Netbeans settings provided above for proxy.

Hope this helps.

Shreedevi

Socket send and receive byte array

Try this, it's working for me.

Sender:

byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

dOut.writeInt(message.length); // write length of the message
dOut.write(message);           // write the message


Receiver:

Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());

int length = dIn.readInt();                    // read length of incoming message
if(length>0) {
    byte[] message = new byte[length];
    dIn.readFully(message, 0, message.length); // read the message
}

Member '<method>' cannot be accessed with an instance reference

You can only access static members using the name of the type.

Therefore, you need to either write,

MyClass.MyItem.Property1

Or (this is probably what you need to do) make Property1 an instance property by removing the static keyword from its definition.

Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.

How to get the Parent's parent directory in Powershell?

In powershell :

$this_script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName

$parent_folder = Split-Path $this_script_path -Leaf

How would I access variables from one class to another?

var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1


class ClassB(ClassA):
    def __init__(self):
        super().__init__()
        print("var1",self.var1)
        print("var2",self.var2)


object1 = ClassB()
sum = object1.methodA()
print(sum)

The given key was not present in the dictionary. Which key?

You can try this code

Dictionary<string,string> AllFields = new Dictionary<string,string>();  
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

If the key is not present, it simply returns a null value.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Installing Tomcat 7 as Service on Windows Server 2008

  1. Edit service.bat – Swap two lines so that they appear in following order: if not “%JAVA_HOME%“ == ““ goto got JdkHome if not “%JRE_HOME%“ == ““ goto got JreHome
  2. Open cmd and run command service.bat install
  3. Open Services and find Apache Tomcat 7.0 Tomcat7. Right click and Properties. Change its startup type to Automatic (with delay).
  4. Reboot machine to verify if the service started automatically

update to python 3.7 using anaconda

conda create -n py37 -c anaconda anaconda=5.3

seems to be working.

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

Insert multiple rows into single column

  INSERT INTO Data ( Col1 ) VALUES ('Hello'), ('World')

Install .ipa to iPad with or without iTunes

All of the other answers are either out of date or too much work where it doesn't need to be. Upload your .IPA file to diawi.com then either scan the QR-Code and install, or email the link to the device you want to install the app to, or type the shortened URL into your Safari browser and install that way.

I needed to get an app installed into an older iOS device today and this method took me less than 2 minutes to complete start to finish.

 https://www.diawi.com/

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

This is the Different Solution, Check if your Services are running correctly, if WAMP icon showing orange color, and 2 out of 3 services are running it's showing, then this solution will work . Root cause:

If in your system mysql was there, later you installed WAMP then again one MYSQL will install as WAMP package, default port for MYSQL is 3306 , So in both mysql the port will be 3306, which is a port conflict, So just change the port it will work fine. Steps to change the Port.

  1. Right click the WAMP icon.
  2. Chose Tool
  3. Change the port in Port used by MySql Section

App.Config change value

That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

Return a string method in C#

You don't have to have a method for that. You could create a property like this instead:

class SalesPerson
{
    string firstName, lastName;
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
    public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

The class could even be shortened to:

class SalesPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
       get { return this.FirstName + " " + this.LastName; } 
    }
}

The property could then be accessed like any other property:

class Program
{
    static void Main(string[] args)
    {
        SalesPerson x = new SalesPerson("John", "Doe");
        Console.WriteLine(x.FullName); // Will print John Doe
    }
}

MySQL Database won't start in XAMPP Manager-osx

check the err log on your /Applications/XAMPP/xamppfiles/var/mysql/ with filename like your_machine_name.local.err, if you find something like: "Attempted to open a previously opened tablespace. Previous tablespace ... uses space ID"

the following works for me:

edit file:

/Applications/XAMPP/xamppfiles/etc/my.cnf

find the [mysqld] section, add one line:

innodb_force_recovery = 1

then run

sudo /Applications/XAMPP/bin/mysql.server start

everything is ok again.

and then the last step:

edit the my.cnf again and remove the line you just added :

innodb_force_recovery = 1

and restart mysql again. Otherwise all your tables will be read only

Open soft keyboard programmatically

public final class AAUtilKeyboard {

public static void openKeyboard(final Activity activity, final EditText editText) {
    final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
}

public static void hideKeyboard(final Activity activity) {
    final View view = activity.getCurrentFocus();
    if (view != null) {
        final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

Remove last character of a StringBuilder?

if(sb.length() > 0){
    sb.deleteCharAt(sb.length() - 1);
}